diff --git a/.deepsource.toml b/.deepsource.toml new file mode 100644 index 0000000000..a352c02e4c --- /dev/null +++ b/.deepsource.toml @@ -0,0 +1,22 @@ +version = 1 + +exclude_patterns = [ + 'examples/**', + + # auto-generated files + 'twilio/rest/**', + 'twilio/twiml/**', + 'tests/integration/**', +] + +test_patterns = [ + 'tests/**' +] + +[[analyzers]] +name = "python" +enabled = true + + [analyzers.meta] + max_line_length = 100 + skip_doc_coverage = ["module", "magic", "class"] diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000000..6fb5f5e10e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,69 @@ +name: Bug report +description: Report a bug with the twilio-python helper library. +title: "[BUG] Describe the issue briefly" +labels: "type: bug" +body: + - type: markdown + attributes: + value: | + Thank you for reporting a bug in the twilio-python helper library. Please provide the details below to help us investigate and resolve the issue. + + - type: textarea + attributes: + label: Describe the bug + description: Provide a clear and concise description of the issue. + placeholder: A clear and concise description of the bug. + validations: + required: true + + - type: textarea + attributes: + label: Code snippet + description: Provide the code snippet that reproduces the issue. + placeholder: "```\n// Code snippet here\n```" + validations: + required: true + + - type: textarea + attributes: + label: Actual behavior + description: Describe what actually happened. + placeholder: A description of the actual behavior. + validations: + required: true + + - type: textarea + attributes: + label: Expected behavior + description: Describe what you expected to happen. + placeholder: A description of the expected outcome. + validations: + required: true + + - type: input + attributes: + label: twilio-python version + description: Specify the version of the twilio-python helper library you are using. + placeholder: e.g., 9.4.1 + validations: + required: true + + - type: input + attributes: + label: Python version + description: Specify the version of Python you are using. + placeholder: e.g., 3.9.1 + validations: + required: true + + - type: textarea + attributes: + label: Logs or error messages + description: Provide relevant logs or error messages (if any). + placeholder: "Error: Something went wrong..." + + - type: textarea + attributes: + label: Additional context + description: Add any other context about the problem here. + placeholder: Any additional diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000..b16697d703 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,10 @@ +contact_links: + - name: Twilio Support + url: https://twilio.com/help/contact + about: Get Support + - name: Stack Overflow + url: https://stackoverflow.com/questions/tagged/twilio-python+or+twilio+python + about: Ask questions on Stack Overflow + - name: Documentation + url: https://www.twilio.com/docs/libraries/reference/twilio-python + about: View Reference Documentation diff --git a/.github/workflows/pr-lint.yml b/.github/workflows/pr-lint.yml new file mode 100644 index 0000000000..31520079ca --- /dev/null +++ b/.github/workflows/pr-lint.yml @@ -0,0 +1,21 @@ +name: Lint PR +on: + pull_request_target: + types: [ opened, edited, synchronize, reopened ] + +jobs: + validate: + name: Validate title + runs-on: ubuntu-latest + steps: + - uses: amannn/action-semantic-pull-request@v5 + with: + types: | + chore + docs + fix + feat + misc + test + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/test-and-deploy.yml b/.github/workflows/test-and-deploy.yml new file mode 100644 index 0000000000..f5bd133256 --- /dev/null +++ b/.github/workflows/test-and-deploy.yml @@ -0,0 +1,133 @@ +name: Test and Deploy +on: + push: + branches: [ '*' ] + tags: [ '*' ] + pull_request: + branches: [ main ] + schedule: + # Run automatically at 8AM PST Monday-Friday + - cron: '0 15 * * 1-5' + workflow_dispatch: + +jobs: + test: + name: Test + runs-on: ubuntu-latest + timeout-minutes: 20 + strategy: + matrix: + python-version: [ '3.8', '3.9', '3.10', '3.11', '3.12', '3.13' ] + steps: + - name: Checkout twilio-python + uses: actions/checkout@v3 + with: + fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + + - name: Install Dependencies + run: | + pip install virtualenv --upgrade + make install test-install + make prettier + + - name: Run the tests + run: make test-with-coverage + + - name: Run Cluster Tests + if: (!github.event.pull_request.head.repo.fork) + env: + TWILIO_ACCOUNT_SID: ${{ secrets.TWILIO_ACCOUNT_SID }} + TWILIO_API_KEY: ${{ secrets.TWILIO_CLUSTER_TEST_API_KEY}} + TWILIO_API_SECRET: ${{ secrets.TWILIO_CLUSTER_TEST_API_KEY_SECRET }} + TWILIO_FROM_NUMBER: ${{ secrets.TWILIO_FROM_NUMBER }} + TWILIO_TO_NUMBER: ${{ secrets.TWILIO_TO_NUMBER }} + TWILIO_AUTH_TOKEN: ${{ secrets.TWILIO_AUTH_TOKEN }} + ASSISTANT_ID: ${{ secrets.ASSISTANT_ID }} + run: make cluster-test + + - name: Verify docs generation + run: make docs + + # only send coverage for PRs and branch updates + - name: SonarCloud Scan + if: (github.event_name == 'pull_request' || github.ref_type == 'branch') && !github.event.pull_request.head.repo.fork && matrix.python-version == '3.10' + uses: SonarSource/sonarcloud-github-action@master + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Needed to get PR information, if any + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + + deploy: + name: Deploy + if: success() && github.ref_type == 'tag' + needs: [ test ] + runs-on: ubuntu-latest + steps: + - name: Checkout twilio-python + uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.10' + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install build + + - name: Build package + run: python -m build + + - name: Login to Docker Hub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_AUTH_TOKEN }} + + # The expression strips off the shortest match from the front of the string to yield just the tag name as the output + - name: Get tagged version + run: echo "GITHUB_TAG=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV + + - name: Create GitHub Release + uses: sendgrid/dx-automator/actions/release@main + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and Push image + run: make docker-build docker-push + + - name: Publish package to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 + with: + user: __token__ + password: ${{ secrets.PYPI_TOKEN }} + + - name: Submit metric to Datadog + uses: sendgrid/dx-automator/actions/datadog-release-metric@main + env: + DD_API_KEY: ${{ secrets.DATADOG_API_KEY }} + + notify-on-failure: + name: Slack notify on failure + if: failure() && github.event_name != 'pull_request' && (github.ref == 'refs/heads/main' || github.ref_type == 'tag') + needs: [ test, deploy ] + runs-on: ubuntu-latest + steps: + - uses: rtCamp/action-slack-notify@v2 + env: + SLACK_COLOR: failure + SLACK_ICON_EMOJI: ':github:' + SLACK_MESSAGE: ${{ format('Test *{0}*, Deploy *{1}*, {2}/{3}/actions/runs/{4}', needs.test.result, needs.deploy.result, github.server_url, github.repository, github.run_id) }} + SLACK_TITLE: Action Failure - ${{ github.repository }} + SLACK_USERNAME: GitHub Actions + SLACK_MSG_AUTHOR: twilio-dx + SLACK_FOOTER: Posted automatically using GitHub Actions + SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }} + MSG_MINIMAL: true diff --git a/.gitignore b/.gitignore index dabcf4c17b..628f850c96 100644 --- a/.gitignore +++ b/.gitignore @@ -4,7 +4,7 @@ *.egg *.egg-info dist -build +/build/ eggs parts bin @@ -12,7 +12,7 @@ develop-eggs .installed.cfg scratch env -venv +venv* # Installer logs pip-log.txt @@ -20,13 +20,23 @@ pip-log.txt # Unit test / coverage reports .coverage .tox +coverage.xml .DS_Store -# Sphinx -docs/tmp -docs/_build -cover +# sphinx build and rst folder +docs/build +docs/source/_rst -# tools +# PyCharm/IntelliJ .idea + +#htmlcov +*htmlcov* + +# PyEnv +.python-version + +README.md.bak + +**/.openapi-generator* diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index dd4152eee0..0000000000 --- a/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -language: python -python: - - "2.5" - - "2.6" - - "2.7" - - "3.2" - - "3.3" -install: - - pip install . --use-mirrors - - pip install -r requirements.txt --use-mirrors - - pip install -r tests/requirements.txt --use-mirrors -script: - - flake8 --ignore=F401 twilio - - flake8 --ignore=E123,E126,E128,E501 tests - - nosetests diff --git a/AUTHORS.md b/AUTHORS.md new file mode 100644 index 0000000000..58eabd023d --- /dev/null +++ b/AUTHORS.md @@ -0,0 +1,41 @@ +# Authors + +We'd like to thank the following people who have contributed to the +`twilio-python` repository. + +- Adam Ballai +- Alex Brinsmead +- Alex Chan +- Andrew Benton +- Chad Selph +- Comrade DOS +- Dan Yang +- Dennis Pilarinos +- Doug Black +- Evan Fossier +- Fabian Topfstedt +- Florian Le Goff +- Frank Tobia +- Frederik De Bleser +- Guillaume BINET +- Hunter Blanks +- Joël Franusic +- Justin Van Koten +- Kenneth Reitz +- Kevin Burke +- Kyle Conroy +- Michael Parker +- Moses Palmér +- Ryan Horn +- Sam Kimbrel +- Skylar Saveland +- Tiberiu Ana +- Zachary Voase +- aes +- dnathe4th +- isbo +- negeorge +- Evan Cooke +- tysonholub +- Brodan +- Kyle Jones \ No newline at end of file diff --git a/CHANGES b/CHANGES deleted file mode 100644 index f905d0ad76..0000000000 --- a/CHANGES +++ /dev/null @@ -1,124 +0,0 @@ -twilio-python Changelog -======================= - -Here you can see the full list of changes between each twilio-python release. - -Version 3.4.5 -------------- - -Released on April 1, 2013 - -Allow the Account object to access usage records and usage trigger data, in -addition to the client. Reporter: Trenton McManus - -Version 3.4.4 -------------- - -Adds support for Sip - -Version 3.4.3 -------------- - -Adds correct dependencies to the `setup.py` file. - -Version 3.4.2 -------------- - -Released on January 2, 2013 - -Adds a convenience function to retrieve the members of a queue by running -client.members("QU123"). - -Version 3.4.1 -------------- - -Python3 support! - -Version 3.3.11 --------------- - -- Fix a bug where participants could not be kicked from a Conference - - -Version 3.3.10 --------------- - -- Add support for Queue. Fix a bug where the library wouldn't work in Python 2.5 - - -Version 3.3.9 -------------- - -- Fix an error introduced in 3.3.7 that prevented validation calls from - succeeding. - -Version 3.3.8 -------------- - -- Use next_page_uri when iterating over a list resource - - -Version 3.3.7 -------------- - -- Allow arbitrary keyword arguments on resource creation and listing - -Version 3.3.6 -------------- - -- Remove doc/tmp directory which was preventing installation on certain Windows machines -- Add Travis CI integration -- Update httplib2 dependency - -Version 3.3.5 -------------- - -Released on January 18, 2011 - -- Fix a bug with the deprecated `TwilioRestClient.request` method -- Fix a bug in filtering SMS messages by DateSent - -Version 3.3.4 -------------- - -Released on December 16, 2011 - -- Allow both unicode strings and encoded byte strings in request data -- Add support for SMS and Voice application sids to phone number updating -- Fix documentation error relating to phone number purchasing -- Include doc string information for decorated functions - -Version 3.3.3 -------------- - -Released on November 3, 2011 - -- Support unicode characters when validating requests -- Add support for Great Britain language on the Say verb -- Set Sms Application, Voice Application, and/or a Friendly - Name when purchasing a number -- Add missing parameters for resource creation and update - -Version 3.3.2 -------------- - -Released on September 29, 2011 - -- TwiML verbs can now be used as context managers - -Version 3.3.1 -------------- - -Released on September 27, 2011 - -- Allow phone numbers to be transferred between accounts and subaccounts - -Version 3.3.0 -------------- - -Released on September 21, 2011 - -- Add support for Twilio Connect. Connect applications and authorized Connect - applications are now availble via the REST client. -- Fix a problem where date and datetimes weren't coverted to strings when - querying list resources diff --git a/CHANGES.md b/CHANGES.md new file mode 100644 index 0000000000..37c7984d2f --- /dev/null +++ b/CHANGES.md @@ -0,0 +1,4368 @@ +twilio-python Changelog +======================= + +Here you can see the full list of changes between each twilio-python release. + +[2025-06-12] Version 9.6.3 +-------------------------- +**Library - Chore** +- [PR #869](https://github.com/twilio/twilio-python/pull/869): Remove knowledge files. Thanks to [@krishnakalluri](https://github.com/krishnakalluri)! + +**Api** +- Change DependentPhoneNumber `capabilities` type `object` and `date_created`, `date_updated` to `date_time` +- Updated the `Default` value from 0 to 1 in the Recordings Resource `channels` property + +**Serverless** +- Update `ienum` type level in Logs api + +**Verify** +- Update Channel list in Verify Attempst API +- Update `ienum` type for Conversion_Status in Verify Attempts API + +**Twiml** +- Add `us2` to the list of supported values for the region attribute in the `` TwiML noun. + + +[2025-05-29] Version 9.6.2 +-------------------------- +**Library - Chore** +- [PR #862](https://github.com/twilio/twilio-python/pull/862): update iam token endpoint. Thanks to [@manisha1997](https://github.com/manisha1997)! + +**Api** +- Added several usage category enums to `usage_record` API + +**Numbers** +- Update the porting documentation + +**Verify** +- Update `ienum` type for Channels in Verify Attempts API + + +[2025-05-13] Version 9.6.1 +-------------------------- +**Accounts** +- Changes to add date_of_consent param in Bulk Consent API + +**Api** +- Change `friendly_name`, `date_created` and `date_updated` properties to type `string`. + +**Twiml** +- Update twiml definition for `` and `` + + +[2025-05-05] Version 9.6.0 +-------------------------- +**Library - Fix** +- [PR #848](https://github.com/twilio/twilio-python/pull/848): Timezone changes in token_auth_strategy.py. Thanks to [@Pablo2113](https://github.com/Pablo2113)! +- [PR #853](https://github.com/twilio/twilio-python/pull/853): Fix deprecated/invalid config in `setup.cfg`. Thanks to [@abravalheri](https://github.com/abravalheri)! + +**Library - Chore** +- [PR #858](https://github.com/twilio/twilio-python/pull/858): fix oauth examples. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Library - Docs** +- [PR #855](https://github.com/twilio/twilio-python/pull/855): update pagination usage in README.md. Thanks to [@manisha1997](https://github.com/manisha1997)! + +**Api** +- Add `response_key` for `Usage Triggers` fetch endpoint. + +**Flex** +- Add Update Interaction API +- Adding `webhook_ttid` as optional parameter in Interactions API + +**Serverless** +- Add node22 as a valid Build runtime +- Add node20 as a valid Build runtime + +**Video** +- removed `transcribe_participants_on_connect` and `transcriptions_configuration` from the room resource **(breaking change)** +- Added `transcribe_participants_on_connect` and `transcriptions_configuration` to the room resource + + +[2025-04-07] Version 9.5.2 +-------------------------- +**Studio** +- Add documentation for parent_step_sid field in Step resource + + +[2025-03-20] Version 9.5.1 +-------------------------- +**Accounts** +- Update Safelist API docs as part of prefix supoort + +**Flex** +- Removing `first_name`, `last_name`, and `friendly_name` from the Flex User API + +**Messaging** +- Add missing tests under transaction/phone_numbers and transaction/short_code + + +[2025-03-11] Version 9.5.0 +-------------------------- +**Library - Feature** +- [PR #850](https://github.com/twilio/twilio-python/pull/850): Update UPGRADE.md. Thanks to [@manisha1997](https://github.com/manisha1997)! + +**Library - Fix** +- [PR #847](https://github.com/twilio/twilio-python/pull/847): AssistantsBase import. Thanks to [@sbansla](https://github.com/sbansla)! + +**Api** +- Add the missing `emergency_enabled` field for `Address Service` endpoints + +**Messaging** +- Add missing enums for A2P and TF + +**Numbers** +- add missing enum values to hosted_number_order_status + +**Twiml** +- Convert Twiml Attribute `speechModel` of type enum to string **(breaking change)** + + +[2025-02-20] Version 9.4.6 +-------------------------- +**Library - Chore** +- [PR #842](https://github.com/twilio/twilio-python/pull/842): issue 841. Thanks to [@manisha1997](https://github.com/manisha1997)! + +**Flex** +- Adding Digital Transfers APIs under v1/Interactions + +**Numbers** +- Convert webhook_type to ienum type in v1/Porting/Configuration/Webhook/{webhook_type} + +**Trusthub** +- Changing TrustHub SupportingDocument status enum from lowercase to uppercase since kyc-orch returns status capitalized and rest proxy requires strict casing + + +[2025-02-11] Version 9.4.5 +-------------------------- +**Api** +- Change downstream url and change media type for file `base/api/v2010/validation_request.json`. + +**Intelligence** +- Add json_results for Generative JSON operator results + +**Messaging** +- Add DestinationAlphaSender API to support Country-Specific Alpha Senders + +**Video** +- Change codec type from enum to case-insensitive enum in recording and room_recording apis + + +[2025-01-28] Version 9.4.4 +-------------------------- +**Library - Fix** +- [PR #822](https://github.com/twilio/twilio-python/pull/822): Fix for 10 vulnerabilities. Thanks to [@twilio-product-security](https://github.com/twilio-product-security)! + +**Library - Chore** +- [PR #834](https://github.com/twilio/twilio-python/pull/834): update httpclient. Thanks to [@manisha1997](https://github.com/manisha1997)! +- [PR #837](https://github.com/twilio/twilio-python/pull/837): enable newer versions of aiohttp-retry. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #833](https://github.com/twilio/twilio-python/pull/833): created bug report issue template. Thanks to [@sbansla](https://github.com/sbansla)! + +**Api** +- Add open-api file tag to `conference/call recordings` and `recording_transcriptions`. + +**Events** +- Add support for subaccount subscriptions (beta) + +**Insights** +- add new region to conference APIs + +**Lookups** +- Add new `parnter_sub_id` query parameter to the lookup request + + +[2025-01-13] Version 9.4.3 +-------------------------- +**Messaging** +- Adds validity period Default value in service resource documentation + + +[2025-01-09] Version 9.4.2 +-------------------------- +**Library - Chore** +- [PR #832](https://github.com/twilio/twilio-python/pull/832): remove test for 3.7. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Numbers** +- Change beta feature flag to use v2/BulkHostedNumberOrders + + +[2024-12-13] Version 9.4.1 +-------------------------- +**Library - Fix** +- [PR #827](https://github.com/twilio/twilio-python/pull/827): Fixing init file for preview iam domain. Thanks to [@AsabuHere](https://github.com/AsabuHere)! + +**Library - Chore** +- [PR #826](https://github.com/twilio/twilio-python/pull/826): fix orgs api changes. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + + +[2024-12-12] Version 9.4.0 +-------------------------- +**Library - Feature** +- [PR #825](https://github.com/twilio/twilio-python/pull/825): Docs update and examples for organization api uptake and public oauth. Thanks to [@AsabuHere](https://github.com/AsabuHere)! +- [PR #815](https://github.com/twilio/twilio-python/pull/815): Organizations Api uptake for twilio-python. Thanks to [@AsabuHere](https://github.com/AsabuHere)! + + +[2024-12-05] Version 9.3.8 +-------------------------- +**Api** +- Add optional parameter `intelligence_service` to `transcription` +- Updated `phone_number_sid` to be populated for sip trunking terminating calls. + +**Numbers** +- Add Update Hosted Number Order V2 API endpoint +- Update Port in docs + +**Twiml** +- Add optional parameter `intelligence_service` to `` +- Add support for new `` and `` noun +- Add `events` attribute to `` verb + + +[2024-11-15] Version 9.3.7 +-------------------------- +**Library - Chore** +- [PR #819](https://github.com/twilio/twilio-python/pull/819): use older verison of aiohttp_retry. Thanks to [@sbansla](https://github.com/sbansla)! + +**Api** +- Added `ivr-virtual-agent-custom-voices` and `ivr-virtual-agent-genai` to `usage_record` API. +- Add open-api file tag to realtime_transcriptions + +**Taskrouter** +- Add `api-tag` property to workers reservation +- Add `api-tag` property to task reservation + + +[2024-10-25] Version 9.3.6 +-------------------------- +**Library - Chore** +- [PR #818](https://github.com/twilio/twilio-python/pull/818): removing unavailable references from init files. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + + +[2024-10-24] Version 9.3.5 +-------------------------- +**Conversations** +- Expose ConversationWithParticipants resource that allows creating a conversation with participants + + +[2024-10-17] Version 9.3.4 +-------------------------- +**Api** +- Add response key `country` to fetch AvailablePhoneNumber resource by specific country. + +**Messaging** +- Make library and doc public for requestManagedCert Endpoint + + +[2024-10-03] Version 9.3.3 +-------------------------- +**Library - Chore** +- [PR #816](https://github.com/twilio/twilio-python/pull/816): add assistants init files. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Messaging** +- Add A2P external campaign CnpMigration flag + +**Numbers** +- Add address sid to portability API + +**Verify** +- Add `SnaClientToken` optional parameter on Verification check. +- Add `EnableSnaClientToken` optional parameter for Verification creation. + + +[2024-09-25] Version 9.3.2 +-------------------------- +**Accounts** +- Update docs and mounts. +- Change library visibility to public +- Enable consent and contact bulk upsert APIs in prod. + +**Serverless** +- Add is_plugin parameter in deployments api to check if it is plugins deployment + + +[2024-09-18] Version 9.3.1 +-------------------------- +**Library - Chore** +- [PR #813](https://github.com/twilio/twilio-python/pull/813): add static init file to iam domain. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Intelligence** +- Remove public from operator_type +- Update operator_type to include general-availablity and deprecated + +**Numbers** +- Remove beta flag for bundle clone API + + +[2024-09-05] Version 9.3.0 +-------------------------- +**Iam** +- updated library_visibility public for new public apikeys + +**Numbers** +- Add new field in Error Codes for Regulatory Compliance. +- Change typing of Port In Request date_created field to date_time instead of date **(breaking change)** + + +[2024-08-26] Version 9.2.4 +-------------------------- +**Library - Chore** +- [PR #810](https://github.com/twilio/twilio-python/pull/810): add license identifier to project metadata. Thanks to [@mschoettle](https://github.com/mschoettle)! +- [PR #808](https://github.com/twilio/twilio-python/pull/808): preview iam removal. Thanks to [@manisha1997](https://github.com/manisha1997)! +- [PR #807](https://github.com/twilio/twilio-python/pull/807): update intersphinx_mapping. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #804](https://github.com/twilio/twilio-python/pull/804): add init file. Thanks to [@manisha1997](https://github.com/manisha1997)! + +**Api** +- Update documentation of `error_code` and `error_message` on the Message resource. +- Remove generic parameters from `transcription` resource +- Added public documentation for Payload Data retrieval API + +**Flex** +- Adding update Flex User api + +**Insights** +- Added 'branded', 'business_profile' and 'voice_integrity' fields in List Call Summary + +**Intelligence** +- Add `words` array information to the Sentences v2 entity. +- Add `X-Rate-Limit-Limit`, `X-Rate-Limit-Remaining`, and `X-Rate-Limit-Config` headers for Operator Results. +- Change the path parameter when fetching an `/OperatorType/{}` from `sid` to `string` to support searching by SID or by name +- Add `X-Rate-Limit-Limit`, `X-Rate-Limit-Remaining`, and `X-Rate-Limit-Config` headers for Transcript and Service endpoints. + +**Messaging** +- Adds two new channel senders api to add/remove channel senders to/from a messaging service +- Extend ERC api to accept an optional attribute in request body to indicate CNP migration for an ERC + +**Numbers** +- Modify visibility to public in bundle clone API +- Add `port_date` field to Port In Request and Port In Phone Numbers Fetch APIs +- Change properties docs for port in phone numbers api +- Add is_test body param to the Bundle Create API +- Change properties docs for port in api + +**Trusthub** +- Add new field in themeSetId in compliance_inquiry. + +**Verify** +- Update `custom_code_enabled` description on verification docs + + +[2024-07-02] Version 9.2.3 +-------------------------- +**Intelligence** +- Deprecate account flag api.twilio-intelligence.v2 + + +[2024-06-27] Version 9.2.2 +-------------------------- +**Api** +- Add `transcription` resource + +**Flex** +- Changed mount name for flex_team v2 api + +**Intelligence** +- Add `X-Rate-Limit-Limit`, `X-Rate-Limit-Remaining`, and `X-Rate-Limit-Config` as Response Headers to Operator resources + +**Numbers** +- Added include_constraints query parameter to the Regulations API + +**Twiml** +- Add support for `` noun + + +[2024-06-21] Version 9.2.1 +-------------------------- +**Api** +- Add beta feature request managed cert + + +[2024-06-18] Version 9.2.0 +-------------------------- +**Library - Chore** +- [PR #796](https://github.com/twilio/twilio-python/pull/796): adding contentType in post and put. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Events** +- Add `status` and `documentation_url` to Event Types + +**Lookups** +- Removed unused `fraud` lookups in V1 only to facilitate rest proxy migration + +**Numbers** +- Add date_created field to the Get Port In Request API +- Rename the `status_last_time_updated_timestamp` field to `last_updated` in the Get Port In Phone Number API **(breaking change)** +- Add Rejection reason and rejection reason code to the Get Port In Phone Number API +- Remove the carrier information from the Portability API + +**Proxy** +- Change property `type` from enum to ienum + +**Trusthub** +- Add skipMessagingUseCase field in compliance_tollfree_inquiry. + + +[2024-06-06] Version 9.1.1 +-------------------------- +**Api** +- Mark MaxPrice as obsolete + +**Lookups** +- Update examples for `phone_number_quality_score` + +**Messaging** +- List tollfree verifications on parent account and all sub-accounts + + +[2024-05-24] Version 9.1.0 +-------------------------- +**Library - Chore** +- [PR #789](https://github.com/twilio/twilio-python/pull/789): [Snyk] Security upgrade aiohttp from 3.8.6 to 3.9.4. Thanks to [@twilio-product-security](https://github.com/twilio-product-security)! + +**Library - Fix** +- [PR #716](https://github.com/twilio/twilio-python/pull/716): Connection pool is full, discarding connection. Thanks to [@lightiverson](https://github.com/lightiverson)! + +**Api** +- Add ie1 as supported region for UserDefinedMessage and UserDefinedMessageSubscription. + +**Flex** +- Adding validated field to `plugin_versions` +- Corrected the data type for `runtime_domain`, `call_recording_webhook_url`, `crm_callback_url`, `crm_fallback_url`, `flex_url` in Flex Configuration +- Making `routing` optional in Create Interactions endpoint + +**Intelligence** +- Expose operator authoring apis to public visibility +- Deleted `language_code` parameter from updating service in v2 **(breaking change)** +- Add read_only_attached_operator_sids to v2 services + +**Numbers** +- Add API endpoint for GET Porting Webhook Configurations By Account SID +- Remove bulk portability api under version `/v1`. **(breaking change)** +- Removed porting_port_in_fetch.json files and move the content into porting_port_in.json files +- Add API endpoint to deleting Webhook Configurations +- Add Get Phone Number by Port in request SID and Phone Number SID api +- Add Create Porting webhook configuration API +- Added bundle_sid and losing_carrier_information fields to Create PortInRequest api to support Japan porting + +**Taskrouter** +- Add back `routing_target` property to tasks +- Add back `ignore_capacity` property to tasks +- Removing `routing_target` property to tasks due to revert +- Removing `ignore_capacity` property to tasks due to revert +- Add `routing_target` property to tasks +- Add `ignore_capacity` property to tasks + +**Trusthub** +- Add new field errors to bundle as part of public API response in customer_profile.json and trust_product.json **(breaking change)** +- Add themeSetId field in compliance_tollfree_inquiry. + +**Verify** +- Update `friendly_name` description on service docs + + +[2024-04-18] Version 9.0.5 +-------------------------- +**Library - Chore** +- [PR #742](https://github.com/twilio/twilio-python/pull/742): [Snyk] Fix for 3 vulnerabilities. Thanks to [@twilio-product-security](https://github.com/twilio-product-security)! + +**Flex** +- Add header `ui_version` to `web_channels` API + +**Messaging** +- Redeploy after failed pipeline + +**Numbers** +- Add Delete Port In request phone number api and Add Delete Port In request api + + +[2024-04-04] Version 9.0.4 +-------------------------- +**Api** +- Correct conference filtering by date_created and date_updated documentation, clarifying that times are UTC. + +**Flex** +- Remove optional parameter from `plugins` and it to `plugin_versions` + +**Lookups** +- Add new `pre_fill` package to the lookup response + +**Messaging** +- Cleanup api.messaging.next-gen from Messaging Services endpoints +- Readd Sending-Window after fixing test failure + +**Verify** +- Add `whatsapp.msg_service_sid` and `whatsapp.from` parameters to create, update, get and list of services endpoints + +**Voice** +- Correct conference filtering by date_created and date_updated documentation, clarifying that times are UTC. + +**Twiml** +- Add new `token_type` value `payment-method` for `Pay` verb + + +[2024-04-01] Version 9.0.3 +-------------------------- +**Api** +- Add property `queue_time` to conference participant resource +- Update RiskCheck documentation +- Correct call filtering by start and end time documentation, clarifying that times are UTC. + +**Flex** +- Adding optional parameter to `plugins` + +**Media** +- Remove API: MediaProcessor + +**Messaging** +- Remove Sending-Window due to test failure +- Add Sending-Window as a response property to Messaging Services, gated by a beta feature flag + +**Numbers** +- Correct valid_until_date field to be visible in Bundles resource +- Adding port_in_status field to the Port In resource and phone_number_status and sid fields to the Port In Phone Number resource + +**Oauth** +- Modified token endpoint response +- Added refresh_token and scope as optional parameter to token endpoint + +**Trusthub** +- Add update inquiry endpoint in compliance_registration. +- Add new field in themeSetId in compliance_registration. + +**Voice** +- Correct call filtering by start and end time documentation, clarifying that times are UTC. + +**Twiml** +- Add support for new Google voices (Q1 2024) for `Say` verb - gu-IN voices +- Add support for new Amazon Polly and Google voices (Q1 2024) for `Say` verb - Niamh (en-IE) and Sofie (da-DK) voices + + +[2024-03-15] Version 9.0.2 +-------------------------- +**Oauth** +- Add new APIs for vendor authorize and token endpoints + + +[2024-03-12] Version 9.0.1 +-------------------------- +**Library - Chore** +- [PR #775](https://github.com/twilio/twilio-python/pull/775): removing preview.understand references. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Api** +- Correct precedence documentation for application_sid vs status_callback in message creation +- Mark MaxPrice as deprecated + +**Flex** +- Making `plugins` visibility to public + +**Messaging** +- Add new `errors` attribute to the Brand Registration resource. +- Mark `brand_feedback` attribute as deprecated. +- Mark `failure_reason` attribute as deprecated. +- The new `errors` attribute is expected to provide additional information about Brand registration failures and feedback (if any has been provided by The Campaign Registry). Consumers should use this attribute instead of `brand_feedback` and `failure_reason`. + +**Numbers** +- Correcting mount_name for porting port in fetch API + +**Trusthub** +- Add new field in statusCallbackUrl in compliance_registration. +- Add new field in isvRegisteringForSelfOrTenant in compliance_registration. + +**Twiml** +- Expanded description of Action parameter for Message verb + + +[2024-02-27] Version 9.0.0 +-------------------------- +**Note:** This release contains breaking changes, check our [upgrade guide](./UPGRADE.md###-2024-02-20-8xx-to-9xx) for detailed migration notes. + +**Library - Feature** +- [PR #767](https://github.com/twilio/twilio-python/pull/767): Merge branch '9.0.0-rc' into main. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! **(breaking change)** + +**Library - Chore** +- [PR #771](https://github.com/twilio/twilio-python/pull/771): added check for unset values. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #768](https://github.com/twilio/twilio-python/pull/768): cluster tests enabled. Thanks to [@sbansla](https://github.com/sbansla)! + +**Api** +- remove feedback and feedback summary from call resource + +**Flex** +- Adding `routing_properties` to Interactions Channels Participant + +**Lookups** +- Add new `line_status` package to the lookup response +- Remove `live_activity` package from the lookup response **(breaking change)** + +**Messaging** +- Add tollfree multiple rejection reasons response array + +**Trusthub** +- Add ENUM for businessRegistrationAuthority in compliance_registration. **(breaking change)** +- Add new field in isIsvEmbed in compliance_registration. +- Add additional optional fields in compliance_registration for Individual business type. + +**Twiml** +- Add support for new Amazon Polly and Google voices (Q1 2024) for `Say` verb + + +[2024-02-09] Version 8.13.0 +--------------------------- +**Library - Fix** +- [PR #753](https://github.com/twilio/twilio-python/pull/753): added boolean_to_string converter. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Library - Chore** +- [PR #758](https://github.com/twilio/twilio-python/pull/758): disable cluster test. Thanks to [@sbansla](https://github.com/sbansla)! +- [PR #760](https://github.com/twilio/twilio-python/pull/760): run make prettier. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Api** +- Updated service base url for connect apps and authorized connect apps APIs **(breaking change)** +- Update documentation to reflect RiskCheck GA +- Added optional parameter `CallToken` for create participant api + +**Events** +- Marked as GA + +**Flex** +- Adding `flex_instance_sid` to Flex Configuration +- Adding `provisioning_status` for Email Manager +- Adding `offline_config` to Flex Configuration + +**Insights** +- add flag to restrict access to unapid customers +- decommission voice-qualitystats-endpoint role + +**Intelligence** +- Add text-generation operator (for example conversation summary) results to existing OperatorResults collection. + +**Lookups** +- Remove `carrier` field from `sms_pumping_risk` and leave `carrier_risk_category` **(breaking change)** +- Remove carrier information from call forwarding package **(breaking change)** + +**Messaging** +- Add update instance endpoints to us_app_to_person api +- Add tollfree edit_allowed and edit_reason fields +- Update Phone Number, Short Code, Alpha Sender, US A2P and Channel Sender documentation +- Add DELETE support to Tollfree Verification resource + +**Numbers** +- Add Get Port In request api + +**Push** +- Migrated to new Push API V4 with Resilient Notification Delivery. + +**Serverless** +- Add node18 as a valid Build runtime + +**Taskrouter** +- Add `jitter_buffer_size` param in update reservation +- Add container attribute to task_queue_bulk_real_time_statistics endpoint +- Remove beta_feature check on task_queue_bulk_real_time_statistics endpoint + +**Trusthub** +- Add optional field NotificationEmail to the POST /v1/ComplianceInquiries/Customers/Initialize API +- Add additional optional fields in compliance_tollfree_inquiry.json +- Rename did to tollfree_phone_number in compliance_tollfree_inquiry.json +- Add new optional field notification_email to compliance_tollfree_inquiry.json + +**Verify** +- `Tags` property added again to Public Docs **(breaking change)** +- Remove `Tags` from Public Docs **(breaking change)** +- Add `VerifyEventSubscriptionEnabled` parameter to service create and update endpoints. +- Add `Tags` optional parameter on Verification creation. +- Update Verify TOTP maturity to GA. + + +[2024-01-25] Version 8.12.0 +--------------------------- +**Oauth** +- updated openid discovery endpoint uri **(breaking change)** +- Added device code authorization endpoint +- added oauth JWKS endpoint +- Get userinfo resource +- OpenID discovery resource +- Add new API for token endpoint + + +[2024-01-14] Version 8.11.1 +--------------------------- +**Library - Chore** +- [PR #749](https://github.com/twilio/twilio-python/pull/749): removing webhook test. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Push** +- Migrated to new Push API V4 with Resilient Notification Delivery. + + +[2023-12-14] Version 8.11.0 +--------------------------- +**Library - Chore** +- [PR #741](https://github.com/twilio/twilio-python/pull/741): upgrade to python 3.12. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #740](https://github.com/twilio/twilio-python/pull/740): bump aiohttp. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Api** +- Updated service base url for connect apps and authorized connect apps APIs **(breaking change)** + +**Events** +- Marked as GA + +**Insights** +- decommission voice-qualitystats-endpoint role + +**Numbers** +- Add Get Port In request api + +**Taskrouter** +- Add `jitter_buffer_size` param in update reservation + +**Trusthub** +- Add additional optional fields in compliance_tollfree_inquiry.json + +**Verify** +- Remove `Tags` from Public Docs **(breaking change)** + + +[2023-12-01] Version 8.10.3 +--------------------------- +**Verify** +- Add `VerifyEventSubscriptionEnabled` parameter to service create and update endpoints. + + +[2023-11-17] Version 8.10.2 +--------------------------- +**Library - Chore** +- [PR #733](https://github.com/twilio/twilio-python/pull/733): bumping aiohttp from 3.8.5 to 3.8.6. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Api** +- Update documentation to reflect RiskCheck GA + +**Messaging** +- Add tollfree edit_allowed and edit_reason fields +- Update Phone Number, Short Code, Alpha Sender, US A2P and Channel Sender documentation + +**Taskrouter** +- Add container attribute to task_queue_bulk_real_time_statistics endpoint + +**Trusthub** +- Rename did to tollfree_phone_number in compliance_tollfree_inquiry.json +- Add new optional field notification_email to compliance_tollfree_inquiry.json + +**Verify** +- Add `Tags` optional parameter on Verification creation. + + +[2023-11-06] Version 8.10.1 +--------------------------- +**Flex** +- Adding `provisioning_status` for Email Manager + +**Intelligence** +- Add text-generation operator (for example conversation summary) results to existing OperatorResults collection. + +**Messaging** +- Add DELETE support to Tollfree Verification resource + +**Serverless** +- Add node18 as a valid Build runtime + +**Verify** +- Update Verify TOTP maturity to GA. + + +[2023-10-19] Version 8.10.0 +--------------------------- +**Library - Fix** +- [PR #730](https://github.com/twilio/twilio-python/pull/730): Requirement changes. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #727](https://github.com/twilio/twilio-python/pull/727): Requirement changes. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #726](https://github.com/twilio/twilio-python/pull/726): requirements changes. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Accounts** +- Updated Safelist metadata to correct the docs. +- Add Global SafeList API changes + +**Api** +- Added optional parameter `CallToken` for create participant api + +**Flex** +- Adding `offline_config` to Flex Configuration + +**Intelligence** +- Deleted `redacted` parameter from fetching transcript in v2 **(breaking change)** + +**Lookups** +- Add new `phone_number_quality_score` package to the lookup response +- Remove `disposable_phone_number_risk` package **(breaking change)** + +**Messaging** +- Update US App To Person documentation with current `message_samples` requirements + +**Taskrouter** +- Remove beta_feature check on task_queue_bulk_real_time_statistics endpoint +- Add `virtual_start_time` property to tasks +- Updating `task_queue_data` format from `map` to `array` in the response of bulk get endpoint of TaskQueue Real Time Statistics API **(breaking change)** + + +[2023-10-05] Version 8.9.1 +-------------------------- +**Library - Chore** +- [PR #721](https://github.com/twilio/twilio-python/pull/721): Drop dependency on `pytz` by using stdlib `datetime.timezone.utc`. Thanks to [@Zac-HD](https://github.com/Zac-HD)! +- [PR #723](https://github.com/twilio/twilio-python/pull/723): twilio help changes. Thanks to [@kridai](https://github.com/kridai)! + +**Library - Fix** +- [PR #724](https://github.com/twilio/twilio-python/pull/724): Update ValidateSslCertificate method. Thanks to [@AsabuHere](https://github.com/AsabuHere)! + +**Lookups** +- Add test api support for Lookup v2 + + +[2023-09-21] Version 8.9.0 +-------------------------- +**Conversations** +- Enable conversation email bindings, email address configurations and email message subjects + +**Flex** +- Adding `console_errors_included` to Flex Configuration field `debugger_integrations` +- Introducing new channel status as `inactive` in modify channel endpoint for leave functionality **(breaking change)** +- Adding `citrix_voice_vdi` to Flex Configuration + +**Taskrouter** +- Add Update Queues, Workers, Workflow Real Time Statistics API to flex-rt-data-api-v2 endpoint +- Add Update Workspace Real Time Statistics API to flex-rt-data-api-v2 endpoint + + +[2023-09-07] Version 8.8.0 +-------------------------- +**Api** +- Make message tagging parameters public **(breaking change)** + +**Flex** +- Adding `agent_conv_end_methods` to Flex Configuration + +**Messaging** +- Mark Mesasging Services fallback_to_long_code feature obsolete + +**Numbers** +- Add Create Port In request api +- Renaming sid for bulk_hosting_sid and remove account_sid response field in numbers/v2/BulkHostedNumberOrders **(breaking change)** + +**Pricing** +- gate resources behind a beta_feature + + +[2023-08-24] Version 8.7.0 +-------------------------- +**Library - Test** +- [PR #719](https://github.com/twilio/twilio-python/pull/719): Update test_webhook.py. Thanks to [@kridai](https://github.com/kridai)! + +**Api** +- Add new property `RiskCheck` for SMS pumping protection feature only (public beta to be available soon): Include this parameter with a value of `disable` to skip any kind of risk check on the respective message request + +**Flex** +- Changing `sid` path param to `sid` in interaction channel participant update endpoint **(breaking change)** + +**Messaging** +- Add Channel Sender api +- Fixing country code docs and removing Zipwhip references + +**Numbers** +- Request status changed in numbers/v2/BulkHostedNumberOrders **(breaking change)** +- Add bulk hosting orders API under version `/v2 + + +[2023-08-10] Version 8.6.0 +-------------------------- +**Insights** +- Normalize annotations parameters in list summary api to be prefixed + +**Numbers** +- Change Bulk_hosted_sid from BHR to BH prefix in HNO and dependent under version `/v2` API's. **(breaking change)** +- Added parameter target_account_sid to portability and account_sid to response body + +**Verify** +- Remove beta feature flag to list attempts API. +- Remove beta feature flag to verifications summary attempts API. + + +[2023-07-27] Version 8.5.1 +-------------------------- +**Api** +- Added `voice-intelligence`, `voice-intelligence-transcription` and `voice-intelligence-operators` to `usage_record` API. +- Added `tts-google` to `usage_record` API. + +**Lookups** +- Add new `disposable_phone_number_risk` package to the lookup response + +**Verify** +- Documentation of list attempts API was improved by correcting `date_created_after` and `date_created_before` expected date format. +- Documentation was improved by correcting `date_created_after` and `date_created_before` expected date format parameter on attempts summary API. +- Documentation was improved by adding `WHATSAPP` as optional valid parameter on attempts summary API. + +**Twiml** +- Added support for he-il inside of ssm_lang.json that was missing +- Added support for he-il language in say.json that was missing +- Add `statusCallback` and `statusCallbackMethod` attributes to ``. + + +[2023-07-13] Version 8.5.0 +-------------------------- +**Library - Fix** +- [PR #718](https://github.com/twilio/twilio-python/pull/718): Create __init__.py for intelligence domain. Thanks to [@AsabuHere](https://github.com/AsabuHere)! + +**Flex** +- Adding `interaction_context_sid` as optional parameter in Interactions API + +**Messaging** +- Making visiblity public for tollfree_verification API + +**Numbers** +- Remove Sms capability property from HNO creation under version `/v2` of HNO API. **(breaking change)** +- Update required properties in LOA creation under version `/v2` of Authorization document API. **(breaking change)** + +**Taskrouter** +- Add api to fetch task queue statistics for multiple TaskQueues + +**Verify** +- Add `RiskCheck` optional parameter on Verification creation. + +**Twiml** +- Add Google Voices and languages + + +[2023-06-28] Version 8.4.0 +-------------------------- +**Lookups** +- Add `reassigned_number` package to the lookup response + +**Numbers** +- Add hosted_number_order under version `/v2`. +- Update properties in Porting and Bulk Porting APIs. **(breaking change)** +- Added bulk Portability API under version `/v1`. +- Added Portability API under version `/v1`. + + +[2023-06-15] Version 8.3.0 +-------------------------- +**Api** +- Added `content_sid` as conditional parameter +- Removed `content_sid` as optional field **(breaking change)** + +**Insights** +- Added `annotation` to list summary output + + +[2023-06-01] Version 8.2.2 +-------------------------- +**Api** +- Add `Trim` to create Conference Participant API + +**Intelligence** +- First public beta release for Voice Intelligence APIs with client libraries + +**Messaging** +- Add new `errors` attribute to us_app_to_person resource. This attribute will provide additional information about campaign registration errors. + + +[2023-05-18] Version 8.2.1 +-------------------------- +**Conversations** +- Added `AddressCountry` parameter to Address Configuration endpoint, to support regional short code addresses +- Added query parameters `start_date`, `end_date` and `state` in list Conversations resource for filtering + +**Insights** +- Added annotations parameters to list summary api + +**Messaging** +- Add GET domainByMessagingService endpoint to linkShortening service +- Add `disable_https` to link shortening domain_config properties + +**Numbers** +- Add bulk_eligibility api under version `/v1`. + + +[2023-05-04] Version 8.2.0 +-------------------------- +**Conversations** +- Remove `start_date`, `end_date` and `state` query parameters from list operation on Conversations resource **(breaking change)** + +**Twiml** +- Add support for new Amazon Polly voices (Q1 2023) for `Say` verb + + +[2023-04-19] Version 8.1.0 +-------------------------- +**Library - Chore** +- [PR #709](https://github.com/twilio/twilio-python/pull/709): Drop `asyncio` from requirements. Thanks to [@setu4993](https://github.com/setu4993)! + +**Library - Docs** +- [PR #705](https://github.com/twilio/twilio-python/pull/705): consolidate. Thanks to [@stern-shawn](https://github.com/stern-shawn)! + +**Messaging** +- Remove `messaging_service_sids` and `messaging_service_sid_action` from domain config endpoint **(breaking change)** +- Add error_code and rejection_reason properties to tollfree verification API response + +**Numbers** +- Added the new Eligibility API under version `/v1`. + + +[2023-04-05] Version 8.0.0 +-------------------------- +**Note:** This release contains breaking changes, check our [upgrade guide](./UPGRADE.md###-2023-04-05-7xx-to-8xx) for detailed migration notes. + +**Library - Feature** +- [PR #702](https://github.com/twilio/twilio-python/pull/702): Merge branch '8.0.0-rc' to main. Thanks to [@childish-sambino](https://github.com/childish-sambino)! **(breaking change)** + +**Conversations** +- Expose query parameters `start_date`, `end_date` and `state` in list operation on Conversations resource for sorting and filtering + +**Insights** +- Added answered by filter in Call Summaries + +**Lookups** +- Remove `disposable_phone_number_risk` package **(breaking change)** + +**Messaging** +- Add support for `SOLE_PROPRIETOR` brand type and `SOLE_PROPRIETOR` campaign use case. +- New Sole Proprietor Brands should be created with `SOLE_PROPRIETOR` brand type. Brand registration requests with `STARTER` brand type will be rejected. +- New Sole Proprietor Campaigns should be created with `SOLE_PROPRIETOR` campaign use case. Campaign registration requests with `STARTER` campaign use case will be rejected. +- Add Brand Registrations OTP API + + +[2023-03-22] Version 7.17.0 +--------------------------- +**Api** +- Revert Corrected the data type for `friendly_name` in Available Phone Number Local, Mobile and TollFree resources +- Corrected the data type for `friendly_name` in Available Phone Number Local, Mobile and TollFree resources **(breaking change)** + +**Messaging** +- Add `linkshortening_messaging_service` resource +- Add new endpoint for GetDomainConfigByMessagingServiceSid +- Remove `validated` parameter and add `cert_in_validation` parameter to Link Shortening API **(breaking change)** + + +[2023-03-09] Version 7.16.5 +--------------------------- +**Api** +- Add new categories for whatsapp template + +**Lookups** +- Remove `validation_results` from the `default_output_properties` + +**Supersim** +- Add ESimProfile's `matching_id` and `activation_code` parameters to libraries + + +[2023-02-22] Version 7.16.4 +--------------------------- +**Api** +- Remove `scheduled_for` property from message resource +- Add `scheduled_for` property to message resource + + +[2023-02-08] Version 7.16.3 +--------------------------- +**Lookups** +- Add `disposable_phone_number_risk` package to the lookup response +- Add `sms_pumping_risk` package to the lookup response + + +[2023-01-25] Version 7.16.2 +--------------------------- +**Library - Chore** +- [PR #638](https://github.com/twilio/twilio-python/pull/638): relax test dependencies and remove unused dependencies. Thanks to [@childish-sambino](https://github.com/childish-sambino)! +- [PR #609](https://github.com/twilio/twilio-python/pull/609): Security upgrade pygments from 2.5.2 to 2.7.4. Thanks to [@twilio-product-security](https://github.com/twilio-product-security)! + +**Library - Docs** +- [PR #637](https://github.com/twilio/twilio-python/pull/637): remove docs output from repo. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Library - Test** +- [PR #636](https://github.com/twilio/twilio-python/pull/636): update tox config and replace deprecated test functions. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Api** +- Add `public_application_connect_enabled` param to Application resource + +**Messaging** +- Add new tollfree verification API property (ExternalReferenceId)] + +**Verify** +- Add `device_ip` parameter and channel `auto` for sna/sms orchestration + +**Twiml** +- Add support for `` noun and `` noun, nested `` to `` and `` verb + + +[2023-01-11] Version 7.16.1 +--------------------------- +**Conversations** +- Add support for creating Multi-Channel Rich Content Messages + +**Lookups** +- Changed the no data message for match postal code from `no_data` to `data_not_available` in identity match package + +**Messaging** +- Add update/edit tollfree verification API + + +[2022-12-14] Version 7.16.0 +--------------------------- +**Library - Docs** +- [PR #631](https://github.com/twilio/twilio-python/pull/631): Updated docstrings for timeout to be float instead of int. Thanks to [@byarmis](https://github.com/byarmis)! + +**Library - Chore** +- [PR #627](https://github.com/twilio/twilio-python/pull/627): add support for python 3.11. Thanks to [@JenniferMah](https://github.com/JenniferMah)! + +**Library - Test** +- [PR #628](https://github.com/twilio/twilio-python/pull/628): Pinning ubuntu version for python 3.6 test runs. Thanks to [@rakatyal](https://github.com/rakatyal)! + +**Api** +- Add `street_secondary` param to address create and update +- Make `method` optional for user defined message subscription **(breaking change)** + +**Flex** +- Flex Conversations is now Generally Available +- Adding the ie1 mapping for authorization api, updating service base uri and base url response attribute **(breaking change)** +- Change web channels to GA and library visibility to public +- Changing the uri for authorization api from using Accounts to Insights **(breaking change)** + +**Media** +- Gate Twilio Live endpoints behind beta_feature for EOS + +**Messaging** +- Mark `MessageFlow` as a required field for Campaign Creation **(breaking change)** + +**Oauth** +- updated openid discovery endpoint uri **(breaking change)** +- Added device code authorization endpoint + +**Supersim** +- Allow filtering the SettingsUpdates resource by `status` + +**Twiml** +- Add new Polly Neural voices +- Add tr-TR, ar-AE, yue-CN, fi-FI languages to SSML `` element. +- Add x-amazon-jyutping, x-amazon-pinyin, x-amazon-pron-kana, x-amazon-yomigana alphabets to SSML `` element. +- Rename `character` value for SSML `` `interpret-as` attribute to `characters`. **(breaking change)** +- Rename `role` attribute to `format` in SSML `` element. **(breaking change)** + + +[2022-11-30] Version 7.15.4 +--------------------------- +**Flex** +- Adding new `assessments` api in version `v1` + +**Lookups** +- Add `identity_match` package to the lookup response + +**Messaging** +- Added `validated` parameter to Link Shortening API + +**Serverless** +- Add node16 as a valid Build runtime +- Add ie1 and au1 as supported regions for all endpoints. + + +[2022-11-16] Version 7.15.3 +--------------------------- +**Library - Chore** +- [PR #624](https://github.com/twilio/twilio-python/pull/624): upgrade GitHub Actions dependencies. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Api** +- Set the Content resource to have public visibility as Preview + +**Flex** +- Adding new parameter `base_url` to 'gooddata' response in version `v1` + +**Insights** +- Added `answered_by` field in List Call Summary +- Added `answered_by` field in call summary + + +[2022-11-10] Version 7.15.2 +--------------------------- +**Flex** +- Adding two new authorization API 'user_roles' and 'gooddata' in version `v1` + +**Messaging** +- Add new Campaign properties (MessageFlow, OptInMessage, OptInKeywords, OptOutMessage, OptOutKeywords, HelpMessage, HelpKeywords) + +**Twiml** +- Add new speech models to `Gather`. + + +[2022-10-31] Version 7.15.1 +--------------------------- +**Api** +- Added `contentSid` and `contentVariables` to Message resource with public visibility as Beta +- Add `UserDefinedMessageSubscription` and `UserDefinedMessage` resource + +**Proxy** +- Remove FailOnParticipantConflict param from Proxy Session create and update and Proxy Participant create + +**Supersim** +- Update SettingsUpdates resource to remove PackageSid + +**Taskrouter** +- Add `Ordering` query parameter to Workers and TaskQueues for sorting by +- Add `worker_sid` query param for list reservations endpoint + +**Twiml** +- Add `url` and `method` attributes to `` + + +[2022-10-19] Version 7.15.0 +--------------------------- +**Api** +- Make link shortening parameters public **(breaking change)** + +**Oauth** +- added oauth JWKS endpoint +- Get userinfo resource +- OpenID discovery resource +- Add new API for token endpoint + +**Supersim** +- Add SettingsUpdates resource + +**Verify** +- Update Verify Push endpoints to `ga` maturity +- Verify BYOT add Channels property to the Get Templates response + +**Twiml** +- Add `requireMatchingInputs` attribute and `input-matching-failed` errorType to `` + + +[2022-10-05] Version 7.14.2 +--------------------------- +**Api** +- Added `virtual-agent` to `usage_record` API. +- Add AMD attributes to participant create request + +**Twiml** +- Add AMD attributes to `Number` and `Sip` + + +[2022-09-21] Version 7.14.1 +--------------------------- +**Library - Fix** +- [PR #617](https://github.com/twilio/twilio-python/pull/617): support duplicated query param values. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + + +[2022-09-07] Version 7.14.0 +--------------------------- +**Library - Fix** +- [PR #615](https://github.com/twilio/twilio-python/pull/615): support duplicate query param values. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Flex** +- Removed redundant `close` status from Flex Interactions flow **(breaking change)** +- Adding `debugger_integration` and `flex_ui_status_report` to Flex Configuration + +**Messaging** +- Add create, list and get tollfree verification API + +**Verify** +- Verify SafeList API endpoints added. + +**Video** +- Add `Anonymize` API + +**Twiml** +- Update `event` value `call-in-progress` to `call-answered` + + +[2022-08-24] Version 7.13.0 +--------------------------- +**Library - Test** +- [PR #614](https://github.com/twilio/twilio-python/pull/614): add test-docker rule. Thanks to [@beebzz](https://github.com/beebzz)! + +**Api** +- Remove `beta feature` from scheduling params and remove optimize parameters. **(breaking change)** + +**Routes** +- Remove Duplicate Create Method - Update Method will work even if Inbound Processing Region is currently empty/404. **(breaking change)** + +**Twiml** +- Add new Polly Neural voices +- Add new languages to SSML ``. + + +[2022-08-10] Version 7.12.1 +--------------------------- +**Routes** +- Inbound Proccessing Region API - Public GA + +**Supersim** +- Allow updating `DataLimit` on a Fleet + + +[2022-07-21] Version 7.12.0 +--------------------------- +**Flex** +- Add `status`, `error_code`, and `error_message` fields to Interaction `Channel` +- Adding `messenger` and `gbm` as supported channels for Interactions API + +**Messaging** +- Update alpha_sender docs with new valid characters + +**Verify** +- Reorder Verification Check parameters so `code` stays as the first parameter **(breaking change)** +- Rollback List Attempts API V2 back to pilot stage. + + +[2022-07-13] Version 7.11.0 +--------------------------- +**Library - Fix** +- [PR #611](https://github.com/twilio/twilio-python/pull/611): useragent regrex unit test for RC branch. Thanks to [@claudiachua](https://github.com/claudiachua)! + +**Library - Test** +- [PR #610](https://github.com/twilio/twilio-python/pull/610): Adding misc as PR type. Thanks to [@rakatyal](https://github.com/rakatyal)! + +**Conversations** +- Allowed to use `identity` as part of Participant's resource **(breaking change)** + +**Lookups** +- Remove `enhanced_line_type` from the lookup response **(breaking change)** + +**Supersim** +- Add support for `sim_ip_addresses` resource to helper libraries + +**Verify** +- Changed summary param `service_sid` to `verify_service_sid` to be consistent with list attempts API **(breaking change)** +- Make `code` optional on Verification check to support `sna` attempts. **(breaking change)** + + +[2022-06-29] Version 7.10.0 +--------------------------- +**Api** +- Added `amazon-polly` to `usage_record` API. + +**Insights** +- Added `annotation` field in call summary +- Added new endpoint to fetch/create/update Call Annotations + +**Verify** +- Remove `api.verify.totp` beta flag and set maturity to `beta` for Verify TOTP properties and parameters. **(breaking change)** +- Changed summary param `verify_service_sid` to `service_sid` to be consistent with list attempts API **(breaking change)** + +**Twiml** +- Add `maxQueueSize` to `Enqueue` + + +[2022-06-15] Version 7.9.3 +-------------------------- +**Lookups** +- Adding support for Lookup V2 API + +**Studio** +- Corrected PII labels to be 30 days and added context to be PII + +**Twiml** +- Add `statusCallbackMethod` attribute, nested `` elements to `` noun. +- Add support for new Amazon Polly voices (Q2 2022) for `Say` verb +- Add support for `` noun + + +[2022-06-01] Version 7.9.2 +-------------------------- +**Library - Chore** +- [PR #608](https://github.com/twilio/twilio-python/pull/608): use Docker 'rc' tag for release candidate images. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + + +[2022-05-18] Version 7.9.1 +-------------------------- +**Library - Fix** +- [PR #592](https://github.com/twilio/twilio-python/pull/592): Respect HTTPS_PROXY and other settings from env vars. Thanks to [@AlanCoding](https://github.com/AlanCoding)! + +**Api** +- Add property `media_url` to the recording resources + +**Verify** +- Include `silent` as a channel type in the verifications API. + + +[2022-05-04] Version 7.9.0 +-------------------------- +**Conversations** +- Expose query parameter `type` in list operation on Address Configurations resource + +**Supersim** +- Add `data_total_billed` and `billed_units` fields to Super SIM UsageRecords API response. +- Change ESimProfiles `Eid` parameter to optional to enable Activation Code download method support **(breaking change)** + +**Verify** +- Deprecate `push.include_date` parameter in create and update service. + + +[2022-04-20] Version 7.8.2 +-------------------------- +**Library - Fix** +- [PR #601](https://github.com/twilio/twilio-python/pull/601): Fixing logging of http request and response. Thanks to [@rakatyal](https://github.com/rakatyal)! + + +[2022-04-06] Version 7.8.1 +-------------------------- +**Library - Chore** +- [PR #600](https://github.com/twilio/twilio-python/pull/600): add jinja2 for make docs. Thanks to [@JenniferMah](https://github.com/JenniferMah)! +- [PR #599](https://github.com/twilio/twilio-python/pull/599): DI-1565 test case. Thanks to [@claudiachua](https://github.com/claudiachua)! +- [PR #597](https://github.com/twilio/twilio-python/pull/597): update user-agent string to standardize format. Thanks to [@claudiachua](https://github.com/claudiachua)! + +**Library - Fix** +- [PR #593](https://github.com/twilio/twilio-python/pull/593): revise malformed __str__(self) function. Thanks to [@twilio-aiss](https://github.com/twilio-aiss)! + +**Api** +- Updated `provider_sid` visibility to private + +**Verify** +- Verify List Attempts API summary endpoint added. +- Update PII documentation for `AccessTokens` `factor_friendly_name` property. + +**Voice** +- make annotation parameter from /Calls API private + + +[2022-03-23] Version 7.8.0 +-------------------------- +**Api** +- Change `stream` url parameter to non optional +- Add `verify-totp` and `verify-whatsapp-conversations-business-initiated` categories to `usage_record` API + +**Chat** +- Added v3 Channel update endpoint to support Public to Private channel migration + +**Flex** +- Private Beta release of the Interactions API to support the upcoming release of Flex Conversations at the end of Q1 2022. +- Adding `channel_configs` object to Flex Configuration + +**Media** +- Add max_duration param to PlayerStreamer + +**Supersim** +- Remove Commands resource, use SmsCommands resource instead **(breaking change)** + +**Taskrouter** +- Add limits to `split_by_wait_time` for Cumulative Statistics Endpoint + +**Video** +- Change recording `status_callback_method` type from `enum` to `http_method` **(breaking change)** +- Add `status_callback` and `status_callback_method` to composition +- Add `status_callback` and `status_callback_method` to recording + + +[2022-03-09] Version 7.7.1 +-------------------------- +**Library - Chore** +- [PR #591](https://github.com/twilio/twilio-python/pull/591): push Datadog Release Metric upon deploy success. Thanks to [@eshanholtz](https://github.com/eshanholtz)! + +**Api** +- Add optional boolean include_soft_deleted parameter to retrieve soft deleted recordings + +**Chat** +- Add `X-Twilio-Wehook-Enabled` header to `delete` method in UserChannel resource + +**Numbers** +- Expose `failure_reason` in the Supporting Documents resources + +**Verify** +- Add optional `metadata` parameter to "verify challenge" endpoint, so the SDK/App can attach relevant information from the device when responding to challenges. +- remove beta feature flag to list atempt api operations. +- Add `ttl` and `date_created` properties to `AccessTokens`. + + +[2022-02-23] Version 7.7.0 +-------------------------- +**Api** +- Add `uri` to `stream` resource +- Add A2P Registration Fee category (`a2p-registration-fee`) to usage records +- Detected a bug and removed optional boolean include_soft_deleted parameter to retrieve soft deleted recordings. **(breaking change)** +- Add optional boolean include_soft_deleted parameter to retrieve soft deleted recordings. + +**Numbers** +- Unrevert valid_until and sort filter params added to List Bundles resource +- Revert valid_until and sort filter params added to List Bundles resource +- Update sorting params added to List Bundles resource in the previous release + +**Preview** +- Moved `web_channels` from preview to beta under `flex-api` **(breaking change)** + +**Taskrouter** +- Add `ETag` as Response Header to List of Task, Reservation & Worker + +**Verify** +- Remove outdated documentation commentary to contact sales. Product is already in public beta. +- Add optional `metadata` to factors. + +**Twiml** +- Add new Polly Neural voices + + +[2022-02-09] Version 7.6.0 +-------------------------- +**Library - Chore** +- [PR #589](https://github.com/twilio/twilio-python/pull/589): upgrade supported language versions. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Library - Test** +- [PR #588](https://github.com/twilio/twilio-python/pull/588): migrate to pytest for python 3.10 compatibility. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Api** +- Add `stream` resource + +**Conversations** +- Fixed DELETE request to accept "sid_like" params in Address Configuration resources **(breaking change)** +- Expose Address Configuration resource for `sms` and `whatsapp` + +**Fax** +- Removed deprecated Programmable Fax Create and Update methods **(breaking change)** + +**Insights** +- Rename `call_state` to `call_status` and remove `whisper` in conference participant summary **(breaking change)** + +**Numbers** +- Expose valid_until filters as part of provisionally-approved compliance feature on the List Bundles resource + +**Supersim** +- Fix typo in Fleet resource docs +- Updated documentation for the Fleet resource indicating that fields related to commands have been deprecated and to use sms_command fields instead. +- Add support for setting and reading `ip_commands_url` and `ip_commands_method` on Fleets resource for helper libraries +- Changed `sim` property in requests to create an SMS Command made to the /SmsCommands to accept SIM UniqueNames in addition to SIDs + +**Verify** +- Update list attempts API to include new filters and response fields. + + +[2022-01-26] Version 7.5.1 +-------------------------- +**Insights** +- Added new endpoint to fetch Conference Participant Summary +- Added new endpoint to fetch Conference Summary + +**Messaging** +- Add government_entity parameter to brand apis + +**Verify** +- Add Access Token fetch endpoint to retrieve a previously created token. +- Add Access Token payload to the Access Token creation endpoint, including a unique Sid, so it's addressable while it's TTL is valid. + + +[2022-01-12] Version 7.5.0 +-------------------------- +**Library - Chore** +- [PR #587](https://github.com/twilio/twilio-python/pull/587): add sonarcloud integration. Thanks to [@BrimmingDev](https://github.com/BrimmingDev)! + +**Library - Feature** +- [PR #586](https://github.com/twilio/twilio-python/pull/586): add GitHub release step during deploy. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Api** +- Make fixed time scheduling parameters public **(breaking change)** + +**Messaging** +- Add update brand registration API + +**Numbers** +- Add API endpoint for List Bundle Copies resource + +**Video** +- Enable external storage for all customers + + +[2021-12-15] Version 7.4.0 +-------------------------- +**Library - Feature** +- [PR #582](https://github.com/twilio/twilio-python/pull/582): run tests before deploying. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Api** +- Add optional boolean send_as_mms parameter to the create action of Message resource **(breaking change)** +- Change team ownership for `call` delete + +**Conversations** +- Change wording for `Service Webhook Configuration` resource fields + +**Insights** +- Added new APIs for updating and getting voice insights flags by accountSid. + +**Media** +- Add max_duration param to MediaProcessor + +**Video** +- Add `EmptyRoomTimeout` and `UnusedRoomTimeout` properties to a room; add corresponding parameters to room creation + +**Voice** +- Add endpoint to delete archived Calls + + +[2021-12-01] Version 7.3.2 +-------------------------- +**Conversations** +- Add `Service Webhook Configuration` resource + +**Flex** +- Adding `flex_insights_drilldown` and `flex_url` objects to Flex Configuration + +**Messaging** +- Update us_app_to_person endpoints to remove beta feature flag based access + +**Supersim** +- Add IP Commands resource + +**Verify** +- Add optional `factor_friendly_name` parameter to the create access token endpoint. + +**Video** +- Add maxParticipantDuration param to Rooms + +**Twiml** +- Unrevert Add supported SSML children to ``, ``, `

`, ``, ``, and ``. +- Revert Add supported SSML children to ``, ``, `

`, ``, ``, and ``. + + +[2021-11-17] Version 7.3.1 +-------------------------- +**Library - Fix** +- [PR #578](https://github.com/twilio/twilio-python/pull/578): git log retrieval issues. Thanks to [@shwetha-manvinkurke](https://github.com/shwetha-manvinkurke)! + +**Frontline** +- Added `is_available` to User's resource + +**Messaging** +- Added GET vetting API + +**Verify** +- Add `WHATSAPP` to the attempts API. +- Allow to update `config.notification_platform` from `none` to `apn` or `fcm` and viceversa for Verify Push +- Add `none` as a valid `config.notification_platform` value for Verify Push + +**Twiml** +- Add supported SSML children to ``, ``, `

`, ``, ``, and ``. + + +[2021-11-03] Version 7.3.0 +-------------------------- +**Library - Chore** +- [PR #577](https://github.com/twilio/twilio-python/pull/577): migrate from travis ci to gh actions. Thanks to [@shwetha-manvinkurke](https://github.com/shwetha-manvinkurke)! + +**Api** +- Updated `media_url` property to be treated as PII + +**Messaging** +- Added a new enum for brand registration status named DELETED **(breaking change)** +- Add a new K12_EDUCATION use case in us_app_to_person_usecase api transaction +- Added a new enum for brand registration status named IN_REVIEW + +**Serverless** +- Add node14 as a valid Build runtime + +**Verify** +- Fix typos in Verify Push Factor documentation for the `config.notification_token` parameter. +- Added `TemplateCustomSubstitutions` on verification creation +- Make `TemplateSid` parameter public for Verification resource and `DefaultTemplateSid` parameter public for Service resource. **(breaking change)** + + +[2021-10-18] Version 7.2.0 +-------------------------- +**Library - Feature** +- [PR #576](https://github.com/twilio/twilio-python/pull/576): Add PlaybackGrant. Thanks to [@sarahcstringer](https://github.com/sarahcstringer)! + +**Api** +- Corrected enum values for `emergency_address_status` values in `/IncomingPhoneNumbers` response. **(breaking change)** +- Clarify `emergency_address_status` values in `/IncomingPhoneNumbers` response. + +**Messaging** +- Add PUT and List brand vettings api +- Removes beta feature flag based visibility for us_app_to_person_registered and usecase field.Updates test cases to add POLITICAL usecase. **(breaking change)** +- Add brand_feedback as optional field to BrandRegistrations + +**Video** +- Add `AudioOnly` to create room + + +[2021-10-06] Version 7.1.0 +-------------------------- +**Api** +- Add `emergency_address_status` attribute to `/IncomingPhoneNumbers` response. +- Add `siprec` resource + +**Conversations** +- Added attachment parameters in configuration for `NewMessage` type of push notifications + +**Flex** +- Adding `flex_insights_hr` object to Flex Configuration + +**Numbers** +- Add API endpoint for Bundle ReplaceItems resource +- Add API endpoint for Bundle Copies resource + +**Serverless** +- Add domain_base field to Service response + +**Taskrouter** +- Add `If-Match` Header based on ETag for Worker Delete **(breaking change)** +- Add `If-Match` Header based on Etag for Reservation Update +- Add `If-Match` Header based on ETag for Worker Update +- Add `If-Match` Header based on ETag for Worker Delete +- Add `ETag` as Response Header to Worker + +**Trunking** +- Added `transfer_caller_id` property on Trunks. + +**Verify** +- Document new pilot `whatsapp` channel. + + +[2021-09-22] Version 7.0.0 +-------------------------- +**Note:** This release contains breaking changes, check our [upgrade guide](./UPGRADE.md#2021-09-22-6xx-to-7xx) for detailed migration notes. + +**Library - Fix** +- [PR #560](https://github.com/twilio/twilio-python/pull/560): update code and tests for pyjwt>=2.0.0. Thanks to [@karls](https://github.com/karls)! **(breaking change)** + +**Library - Docs** +- [PR #570](https://github.com/twilio/twilio-python/pull/570): Add upgrade guide for dropping python 2.7, 3.4 & 3.5. Thanks to [@JenniferMah](https://github.com/JenniferMah)! + +**Events** +- Add segment sink + +**Messaging** +- Add post_approval_required attribute in GET us_app_to_person_usecase api response +- Add Identity Status, Russell 3000, Tax Exempt Status and Should Skip SecVet fields for Brand Registrations +- Add Should Skip Secondary Vetting optional flag parameter to create Brand API + + +[2021-09-08] Version 6.63.2 +--------------------------- +**Api** +- Revert adding `siprec` resource +- Add `siprec` resource + +**Messaging** +- Add 'mock' as an optional field to brand_registration api +- Add 'mock' as an optional field to us_app_to_person api +- Adds more Use Cases in us_app_to_person_usecase api transaction and updates us_app_to_person_usecase docs + +**Verify** +- Verify List Templates API endpoint added. + + +[2021-08-25] Version 6.63.1 +--------------------------- +**Api** +- Add Programmabled Voice SIP Refer call transfers (`calls-transfers`) to usage records +- Add Flex Voice Usage category (`flex-usage`) to usage records + +**Conversations** +- Add `Order` query parameter to Message resource read operation + +**Insights** +- Added `partial` to enum processing_state_request +- Added abnormal session filter in Call Summaries + +**Messaging** +- Add brand_registration_sid as an optional query param for us_app_to_person_usecase api + +**Pricing** +- add trunking_numbers resource (v2) +- add trunking_country resource (v2) + +**Verify** +- Changed to private beta the `TemplateSid` optional parameter on Verification creation. +- Added the optional parameter `Order` to the list Challenges endpoint to define the list order. + + +[2021-08-11] Version 6.63.0 +--------------------------- +**Library - Fix** +- [PR #572](https://github.com/twilio/twilio-python/pull/572): fix sonar analysis. Thanks to [@shwetha-manvinkurke](https://github.com/shwetha-manvinkurke)! + +**Library - Chore** +- [PR #571](https://github.com/twilio/twilio-python/pull/571): integrate with sonarcloud. Thanks to [@shwetha-manvinkurke](https://github.com/shwetha-manvinkurke)! + +**Api** +- Corrected the `price`, `call_sid_to_coach`, and `uri` data types for Conference, Participant, and Recording **(breaking change)** +- Made documentation for property `time_limit` in the call api public. **(breaking change)** +- Added `domain_sid` in sip_credential_list_mapping and sip_ip_access_control_list_mapping APIs **(breaking change)** + +**Insights** +- Added new endpoint to fetch Call Summaries + +**Messaging** +- Add brand_type field to a2p brand_registration api +- Revert brand registration api update to add brand_type field +- Add brand_type field to a2p brand_registration api + +**Taskrouter** +- Add `X-Rate-Limit-Limit`, `X-Rate-Limit-Remaining`, and `X-Rate-Limit-Config` as Response Headers to all TaskRouter endpoints + +**Verify** +- Add `TemplateSid` optional parameter on Verification creation. +- Include `whatsapp` as a channel type in the verifications API. + + +[2021-07-28] Version 6.62.1 +--------------------------- +**Conversations** +- Expose ParticipantConversations resource + +**Taskrouter** +- Adding `links` to the activity resource + +**Verify** +- Added a `Version` to Verify Factors `Webhooks` to add new fields without breaking old Webhooks. + + +[2021-07-14] Version 6.62.0 +--------------------------- +**Conversations** +- Changed `last_read_message_index` and `unread_messages_count` type in User Conversation's resource **(breaking change)** +- Expose UserConversations resource + +**Messaging** +- Add brand_score field to brand registration responses + + +[2021-06-30] Version 6.61.0 +--------------------------- +**Conversations** +- Read-only Conversation Email Binding property `binding` + +**Supersim** +- Add Billing Period resource for the Super Sim Pilot +- Add List endpoint to Billing Period resource for Super Sim Pilot +- Add Fetch endpoint to Billing Period resource for Super Sim Pilot + +**Taskrouter** +- Update `transcribe` & `transcription_configuration` form params in Reservation update endpoint to have private visibility **(breaking change)** +- Add `transcribe` & `transcription_configuration` form params to Reservation update endpoint + +**Twiml** +- Add `modify` event to `statusCallbackEvent` for ``. + + +[2021-06-16] Version 6.60.0 +--------------------------- +**Api** +- Update `status` enum for Messages to include 'canceled' +- Update `update_status` enum for Messages to include 'canceled' + +**Trusthub** +- Corrected the sid for policy sid in customer_profile_evaluation.json and trust_product_evaluation.json **(breaking change)** + + +[2021-06-02] Version 6.59.1 +--------------------------- +**Events** +- join Sinks and Subscriptions service + +**Verify** +- Improved the documentation of `challenge` adding the maximum and minimum expected lengths of some fields. +- Improve documentation regarding `notification` by updating the documentation of the field `ttl`. + + +[2021-05-19] Version 6.59.0 +--------------------------- +**Events** +- add query param to return types filtered by Schema Id +- Add query param to return sinks filtered by status +- Add query param to return sinks used/not used by a subscription + +**Messaging** +- Add fetch and delete instance endpoints to us_app_to_person api **(breaking change)** +- Remove delete list endpoint from us_app_to_person api **(breaking change)** +- Update read list endpoint to return a list of us_app_to_person compliance objects **(breaking change)** +- Add `sid` field to Preregistered US App To Person response + +**Supersim** +- Mark `unique_name` in Sim, Fleet, NAP resources as not PII + +**Video** +- [Composer] GA maturity level + + +[2021-05-05] Version 6.58.0 +--------------------------- +**Api** +- Corrected the data types for feedback summary fields **(breaking change)** +- Update the conference participant create `from` and `to` param to be endpoint type for supporting client identifier and sip address + +**Bulkexports** +- promoting API maturity to GA + +**Events** +- Add endpoint to update description in sink +- Remove beta-feature account flag + +**Messaging** +- Update `status` field in us_app_to_person api to `campaign_status` **(breaking change)** + +**Verify** +- Improve documentation regarding `push` factor and include extra information about `totp` factor. + + +[2021-04-21] Version 6.57.0 +--------------------------- +**Api** +- Revert Update the conference participant create `from` and `to` param to be endpoint type for supporting client identifier and sip address +- Update the conference participant create `from` and `to` param to be endpoint type for supporting client identifier and sip address + +**Bulkexports** +- moving enum to doc root for auto generating documentation +- adding status enum and default output properties + +**Events** +- Change schema_versions prop and key to versions **(breaking change)** + +**Messaging** +- Add `use_inbound_webhook_on_number` field in Service API for fetch, create, update, read + +**Taskrouter** +- Add `If-Match` Header based on ETag for Task Delete + +**Verify** +- Add `AuthPayload` parameter to support verifying a `Challenge` upon creation. This is only supported for `totp` factors. +- Add support to resend the notifications of a `Challenge`. This is only supported for `push` factors. + +**Twiml** +- Add Polly Neural voices. + + +[2021-04-07] Version 6.56.0 +--------------------------- +**Api** +- Added `announcement` event to conference status callback events +- Removed optional property `time_limit` in the call create request. **(breaking change)** + +**Messaging** +- Add rate_limits field to Messaging Services US App To Person API +- Add usecase field in Service API for fetch, create, update, read +- Add us app to person api and us app to person usecase api as dependents in service +- Add us_app_to_person_registered field in service api for fetch, read, create, update +- Add us app to person api +- Add us app to person usecase api +- Add A2P external campaign api +- Add Usecases API + +**Supersim** +- Add Create endpoint to Sims resource + +**Verify** +- The `Binding` field is now returned when creating a `Factor`. This value won't be returned for other endpoints. + +**Video** +- [Rooms] max_concurrent_published_tracks has got GA maturity + +**Twiml** +- Add `announcement` event to `statusCallbackEvent` for ``. + + +[2021-03-24] Version 6.55.0 +--------------------------- +**Api** +- Added optional parameter `CallToken` for create calls api +- Add optional property `time_limit` in the call create request. + +**Bulkexports** +- adding two new fields with job api queue_position and estimated_completion_time + +**Events** +- Add new endpoints to manage subscribed_events in subscriptions + +**Numbers** +- Remove feature flags for RegulatoryCompliance endpoints + +**Supersim** +- Add SmsCommands resource +- Add fields `SmsCommandsUrl`, `SmsCommandsMethod` and `SmsCommandsEnabled` to a Fleet resource + +**Taskrouter** +- Add `If-Match` Header based on ETag for Task Update +- Add `ETag` as Response Headers to Tasks and Reservations + +**Video** +- Recording rule beta flag **(breaking change)** +- [Rooms] Add RecordingRules param to Rooms + + +[2021-03-15] Version 6.54.0 +--------------------------- +**Library - Chore** +- [PR #563](https://github.com/twilio/twilio-python/pull/563): Add support for python 3.9. Thanks to [@tim-schilling](https://github.com/tim-schilling)! + +**Events** +- Set maturity to beta + +**Messaging** +- Adjust A2P brand registration status enum **(breaking change)** + +**Studio** +- Remove internal safeguards for Studio V2 API usage now that it's GA + +**Verify** +- Add support for creating and verifying totp factors. Support for totp factors is behind the `api.verify.totp` beta feature. + +**Twiml** +- Add support for `` noun + + +[2021-02-24] Version 6.53.0 +--------------------------- +**Library - Chore** +- [PR #561](https://github.com/twilio/twilio-python/pull/561): removed file exec to get version. Thanks to [@shwetha-manvinkurke](https://github.com/shwetha-manvinkurke)! + +**Events** +- Update description of types in the create sink resource + +**Messaging** +- Add WA template header and footer +- Remove A2P campaign and use cases API **(breaking change)** +- Add number_registration_status field to read and fetch campaign responses + +**Trusthub** +- Make all resources public + +**Verify** +- Verify List Attempts API endpoints added. + + +[2021-02-10] Version 6.52.0 +--------------------------- +**Library - Docs** +- [PR #553](https://github.com/twilio/twilio-python/pull/553): fix simple typo, ommited -> omitted. Thanks to [@timgates42](https://github.com/timgates42)! + +**Library - Fix** +- [PR #558](https://github.com/twilio/twilio-python/pull/558): shortcut syntax for new non-GA versions. Thanks to [@eshanholtz](https://github.com/eshanholtz)! + +**Api** +- Revert change that conference participant create `from` and `to` param to be endpoint type for supporting client identifier and sip address +- Update the conference participant create `from` and `to` param to be endpoint type for supporting client identifier and sip address + +**Events** +- Documentation should state that no fields are PII + +**Flex** +- Adding `notifications` and `markdown` to Flex Configuration + +**Messaging** +- Add A2P use cases API +- Add Brand Registrations API +- Add Campaigns API + +**Serverless** +- Add runtime field to Build response and as an optional parameter to the Build create endpoint. +- Add @twilio/runtime-handler dependency to Build response example. + +**Sync** +- Remove If-Match header for Document **(breaking change)** + +**Twiml** +- Add `refer_url` and `refer_method` to `Dial`. + + +[2021-01-27] Version 6.51.1 +--------------------------- +**Studio** +- Studio V2 API is now GA + +**Supersim** +- Allow updating `CommandsUrl` and `CommandsMethod` on a Fleet + +**Twiml** +- Add `status_callback` and `status_callback_method` to `Stream`. + + +[2021-01-13] Version 6.51.0 +--------------------------- +**Library - Docs** +- [PR #555](https://github.com/twilio/twilio-python/pull/555): Fixing documentation for list parameter types. Thanks to [@shwetha-manvinkurke](https://github.com/shwetha-manvinkurke)! + +**Library - Fix** +- [PR #552](https://github.com/twilio/twilio-python/pull/552): pin pyjwt dependency. Thanks to [@thinkingserious](https://github.com/thinkingserious)! + +**Api** +- Add 'Electric Imp v1 Usage' to usage categories + +**Conversations** +- Changed `last_read_message_index` type in Participant's resource **(breaking change)** + +**Insights** +- Added `created_time` to call summary. + +**Sync** +- Remove HideExpired query parameter for filtering Sync Documents with expired **(breaking change)** + +**Video** +- [Rooms] Expose maxConcurrentPublishedTracks property in Room resource + + +[2020-12-16] Version 6.50.1 +--------------------------- +**Api** +- Updated `call_event` default_output_properties to request and response. + +**Conversations** +- Added `last_read_message_index` and `last_read_timestamp` to Participant's resource update operation +- Added `is_notifiable` and `is_online` to User's resource +- Added `reachability_enabled` parameters to update method for Conversation Service Configuration resource + +**Messaging** +- Added WA template quick reply, URL, and phone number buttons + +**Twiml** +- Add `sequential` to `Dial`. + + +[2020-12-08] Version 6.50.0 +--------------------------- +**Api** +- Added optional `RecordingTrack` parameter for create calls, create participants, and create call recordings +- Removed deprecated Programmable Chat usage record categories **(breaking change)** + +**Twiml** +- Add `recordingTrack` to `Dial`. + + +[2020-12-02] Version 6.49.0 +--------------------------- +**Library - Feature** +- [PR #546](https://github.com/twilio/twilio-python/pull/546): Regional twr header in the access token. Thanks to [@charliesantos](https://github.com/charliesantos)! + +**Api** +- Remove `RecordingTrack` parameter for create calls, create participants, and create call recordings **(breaking change)** +- Added `RecordingTrack` parameter for create calls and create call recordings +- Add optional property `recording_track` in the participant create request + +**Lookups** +- Changed `caller_name` and `carrier` properties type to object **(breaking change)** + +**Trunking** +- Added dual channel recording options for Trunks. + +**Twiml** +- Add `jitterBufferSize` and `participantLabel` to `Conference`. + + +[2020-11-18] Version 6.48.0 +--------------------------- +**Api** +- Add new call events resource - GET /2010-04-01/Accounts/{account_sid}/Calls/{call_sid}/Events.json + +**Conversations** +- Fixed default response property issue for Service Notifications Configuration + +**Insights** +- Removing call_sid from participant summary. **(breaking change)** + +**Serverless** +- Allow Service unique name to be used in path (in place of SID) in Service update request + +**Sync** +- Added HideExpired query parameter for filtering Sync Documents with expired + +**Verify** +- Challenge `Details` and `HiddenDetails` properties are now marked as `PII` +- Challenge `expiration_date` attribute updated to set a default value of five (5) minutes and to allow max dates of one (1) hour after creation. +- Entity `identity` attribute updated to allow values between 8 and 64 characters. +- Verify Service frinedly_name attribute updated from 64 max lenght to 30 characters. + + +[2020-11-05] Version 6.47.0 +--------------------------- +**Library - Docs** +- [PR #544](https://github.com/twilio/twilio-python/pull/544): add debug logging example. Thanks to [@thinkingserious](https://github.com/thinkingserious)! + +**Api** +- Added `verify-push` to `usage_record` API + +**Bulkexports** +- When creating a custom export the StartDay, EndDay, and FriendlyName fields were required but this was not reflected in the API documentation. The API itself failed the request without these fields. **(breaking change)** +- Added property descriptions for Custom Export create method +- Clarified WebhookUrl and WebhookMethod must be provided together for Custom Export + +**Insights** +- Added video room and participant summary apis. + +**Ip_messaging** +- Create separate definition for ip-messaging +- Restore v2 endpoints for ip-messaging + +**Verify** +- Verify Push madurity were updated from `preview` to `beta` +- `twilio_sandbox_mode` header was removed from Verify Push resources **(breaking change)** + +**Video** +- [Rooms] Add Recording Rules API + + +[2020-10-14] Version 6.46.0 +--------------------------- +**Library - Docs** +- [PR #542](https://github.com/twilio/twilio-python/pull/542): add path limit error for windows. Thanks to [@hack3r-0m](https://github.com/hack3r-0m)! + +**Ai** +- Add `Annotation Project` and `Annotation Task` endpoints +- Add `Primitives` endpoints +- Add `meta.total` to the search endpoint + +**Conversations** +- Mutable Conversation Unique Names + +**Insights** +- Added `trust` to summary. + +**Preview** +- Simplified `Channels` resource. The path is now `/BrandedChannels/branded_channel_sid/Channels` **(breaking change)** + +**Verify** +- Changed parameters (`config` and `binding`) to use dot notation instead of JSON string (e.i. Before: `binding={"alg":"ES256", "public_key": "xxx..."}`, Now: `Binding.Alg="ES256"`, `Binding.PublicKey="xxx..."`). **(breaking change)** +- Changed parameters (`details` and `hidden_details`) to use dot notation instead of JSON string (e.i. Before: `details={"message":"Test message", "fields": "[{\"label\": \"Action 1\", \"value\":\"value 1\"}]"}`, Now: `details.Message="Test message"`, `Details.Fields=["{\"label\": \"Action 1\", \"value\":\"value 1\"}"]`). **(breaking change)** +- Removed `notify_service_sid` from `push` service configuration object. Add `Push.IncludeDate`, `Push.ApnCredentialSid` and `Push.FcmCredentialSid` service configuration parameters. **(breaking change)** + + +[2020-09-28] Version 6.45.4 +--------------------------- +**Library - Docs** +- [PR #541](https://github.com/twilio/twilio-python/pull/541): Fix pip download link. Thanks to [@swarnava](https://github.com/swarnava)! + +**Api** +- Add optional property `call_reason` in the participant create request +- Make sip-domain-service endpoints available in stage-au1 and prod-au1 + +**Messaging** +- Removed beta feature gate from WhatsApp Templates API + +**Serverless** +- Add Build Status endpoint + +**Video** +- [Rooms] Add new room type "go" for WebRTC Go + + +[2020-09-21] Version 6.45.3 +--------------------------- +**Library - Fix** +- [PR #540](https://github.com/twilio/twilio-python/pull/540): allow API redirect responses. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Accounts** +- Add Auth Token rotation API + +**Conversations** +- Change resource path for Webhook Configuration + +**Events** +- Schemas API get all Schemas names and versions + + +[2020-09-16] Version 6.45.2 +--------------------------- +**Conversations** +- Expose Configuration and Service Configuration resources +- Add Unique Name support for Conversations +- Add Services Push Notification resource +- Add Service scoped Conversation resources +- Support Identity in Users resource endpoint + +**Messaging** +- GA Deactivation List API +- Add domain cert API's(fetch, update, create) for link tracker + +**Numbers** +- Add API endpoint for Supporting Document deletion + +**Proxy** +- Updated usage of FailOnParticipantConflict param to apply only to accounts with ProxyAllowParticipantConflict account flag + +**Supersim** +- Add `AccountSid` parameter to Sim resource update request +- Add `ready` status as an available status for a Sim resource + + +[2020-09-02] Version 6.45.1 +--------------------------- +**Library - Docs** +- [PR #538](https://github.com/twilio/twilio-python/pull/538): convert markdown links to rst formatted links. Thanks to [@thinkingserious](https://github.com/thinkingserious)! + +**Ai** +- Initial release + +**Bulkexports** +- removing public beta feature flag from BulkExports Jobs API + +**Messaging** +- Add Deactivation List API +- Added page token parameter for fetch in WhatsApp Templates API + +**Numbers** +- Add API endpoint for End User deletion + +**Routes** +- Add Resource Route Configurations API +- Add Route Configurations API +- Initial Release + +**Trunking** +- Added `transfer_mode` property on Trunks. + + +[2020-08-19] Version 6.45.0 +--------------------------- +**Library - Chore** +- [PR #536](https://github.com/twilio/twilio-python/pull/536): update GitHub branch references to use HEAD. Thanks to [@thinkingserious](https://github.com/thinkingserious)! + +**Conversations** +- Allow Identity addition to Participants + +**Events** +- Sinks API Get all Sinks + +**Proxy** +- Clarified usage of FailOnParticipantConflict param as experimental +- Add FailOnParticipantConflict param to Proxy Session create and Proxy Participant create + +**Supersim** +- Add fleet, network, and isoCountryCode to the UsageRecords resource +- Change sort order of UsageRecords from ascending to descending with respect to start time field, records are now returned newest to oldest + +**Wireless** +- Removed `Start` and `End` parameters from the Data Sessions list endpoint. **(breaking change)** + + +[2020-08-05] Version 6.44.2 +--------------------------- +**Messaging** +- Add rejection reason support to WhatsApp API +- Removed status parameter for create and update in WhatsApp Templates API + +**Proxy** +- Add FailOnParticipantConflict param to Proxy Session update + +**Verify** +- Add `CustomFriendlyName` optional parameter on Verification creation. +- Changes in `Challenge` resource to update documentation of both `details` and `hidden_details` properties. + + +[2020-07-22] Version 6.44.1 +--------------------------- +**Api** +- Add optional Click Tracking and Scheduling parameters to Create action of Message resource + +**Supersim** +- Add callback_url and callback_method parameters to Sim resource update request + + +[2020-07-08] Version 6.44.0 +--------------------------- +**Library - Feature** +- [PR #528](https://github.com/twilio/twilio-python/pull/528): include API response headers in 'Last Response'. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Conversations** +- Allow Address updates for Participants +- Message delivery receipts + +**Events** +- Add account_sid to subscription and subscribed_events resources + +**Flex** +- Changed `wfm_integrations` Flex Configuration key to private **(breaking change)** + +**Messaging** +- Add error states to WhatsApp Sender status with failed reason **(breaking change)** +- Delete WhatsApp Template API +- Update WhatsApp Template API +- Add WhatsApp Template Get Api (fetch and read) + +**Numbers** +- Add `valid_until` in the Bundles resource +- Add API for Bundle deletion + +**Verify** +- Removed support for `sms`, `totp` and `app-push` factor types in Verify push **(breaking change)** + + +[2020-06-24] Version 6.43.0 +--------------------------- +**Api** +- Added optional `JitterBufferSize` parameter for creating conference participant +- Added optional `label` property for conference participants +- Added optional parameter `caller_id` for creating conference participant endpoint. + +**Autopilot** +- Remove Export resource from Autopilot Assistant + +**Conversations** +- Expose Conversation timers + +**Monitor** +- Update start/end date filter params to support date-or-time format **(breaking change)** + +**Numbers** +- Add `provisionally-approved` as a Supporting Document status + +**Preview** +- Removed `Authy` resources. **(breaking change)** + +**Supersim** +- Add ready state to the allowed transitions in the sim update call behind the feature flag supersim.ready-state.v1 + +**Verify** +- Webhook resources added to Verify services and put behind the `api.verify.push` beta feature + +**Twiml** +- Add more supported locales for the `Gather` verb. + + +[2020-06-10] Version 6.42.0 +--------------------------- +**Library - Docs** +- [PR #525](https://github.com/twilio/twilio-python/pull/525): link to handling exceptions. Thanks to [@thinkingserious](https://github.com/thinkingserious)! +- [PR #524](https://github.com/twilio/twilio-python/pull/524): link to custom HTTP client instructions. Thanks to [@thinkingserious](https://github.com/thinkingserious)! + +**Library - Fix** +- [PR #523](https://github.com/twilio/twilio-python/pull/523): drop the page limit calculation and correct the page limit stop condition. Thanks to [@childish-sambino](https://github.com/childish-sambino)! +- [PR #522](https://github.com/twilio/twilio-python/pull/522): drop passing a page limit when listing/streaming resources. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Api** +- Added `pstnconnectivity` to `usage_record` API + +**Autopilot** +- Add dialogue_sid param to Query list resource + +**Notify** +- delivery_callback_url and delivery_callback_enabled added + +**Numbers** +- Add `provisionally-approved` as a Bundle status + +**Preview** +- `BrandsInformation` endpoint now returns a single `BrandsInformation` +- Deleted phone number required field in the brand phone number endpoint from `kyc-api` +- Removed insights `preview API` from API Definitions **(breaking change)** +- Added `BrandsInformation` endpoint to query brands information stored in KYC + +**Supersim** +- Require a Network Access Profile when creating a Fleet **(breaking change)** + + +[2020-05-27] Version 6.41.0 +--------------------------- +**Api** +- Added `reason_conference_ended` and `call_sid_ending_conference` to Conference read/fetch/update +- Fixed some examples to use the correct "TK" SID prefix for Trunk resources. + +**Authy** +- Renamed `twilio_authy_sandbox_mode` headers to `twilio_sandbox_mode` **(breaking change)** +- Renamed `Twilio-Authy-*` headers to `Twilio-Veriry-*` **(breaking change)** + +**Flex** +- Adding `flex_service_instance_sid` to Flex Configuration + +**Preview** +- Removed insights preview API from API Definitions **(breaking change)** +- Added `Channels` endpoint to brand a phone number for BrandedCalls + +**Serverless** +- Add Build Sid to Log results + +**Supersim** +- Add Network Access Profile resource Networks subresource +- Allow specifying a Data Limit on Fleets + +**Trunking** +- Fixed some examples to use the correct "TK" SID prefix for Trunk resources. + + +[2020-05-13] Version 6.40.0 +--------------------------- +**Library - Feature** +- [PR #520](https://github.com/twilio/twilio-python/pull/520): add regional and edge support. Thanks to [@eshanholtz](https://github.com/eshanholtz)! + +**Api** +- Add optional `emergency_caller_sid` parameter to SIP Domain +- Updated `call_reason` optional property to be treated as PII +- Added optional BYOC Trunk Sid property to Sip Domain API resource + +**Autopilot** +- Add Restore resource to Autopilot Assistant + +**Contacts** +- Added contacts Create API definition + +**Events** +- Subscriptions API initial release + +**Numbers** +- Add Evaluations API + +**Supersim** +- Allow filtering the Fleets resource by Network Access Profile +- Allow assigning a Network Access Profile when creating and updating a Fleet +- Add Network Access Profiles resource + +**Verify** +- Add `CustomCode` optional parameter on Verification creation. +- Add delete action on Service resource. + +**Voice** +- Added endpoints for BYOC trunks, SIP connection policies and source IP mappings + + +[2020-04-29] Version 6.39.0 +--------------------------- +**Library - Feature** +- [PR #517](https://github.com/twilio/twilio-python/pull/517): add details to TwilioRestException. Thanks to [@ashish-s](https://github.com/ashish-s)! + +**Preview** +- Added `Dispatch` version to `preview` + +**Studio** +- Reroute Create Execution for V2 to the V2 downstream + +**Supersim** +- Add Networks resource + + +[2020-04-15] Version 6.38.1 +--------------------------- +**Library - Chore** +- [PR #513](https://github.com/twilio/twilio-python/pull/513): remove S3 URLs from test data. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Api** +- Updated description for property `call_reason` in the call create request + +**Contacts** +- Added Read, Delete All, and Delete by SID docs +- Initial Release + +**Studio** +- Rename `flow_valid` to `flow_validate` +- Removed `errors` and `warnings` from flows error response and added new property named `details` +- Add Update Execution endpoints to v1 and v2 to end execution via API +- Add new `warnings` attribute v2 flow POST api + +**Twiml** +- Add enhanced attribute to use with `speech_model` for the `Gather` verb + + +[2020-04-01] Version 6.38.0 +--------------------------- +**Api** +- Add optional 'secure' parameter to SIP Domain + +**Authy** +- Added an endpoint to list the challenges of a factor +- Added optional parameter `Push` when updating a service to send the service level push factor configuration + +**Bulkexports** +- exposing bulk exports (vault/slapchop) API as public beta API + +**Flex** +- Adding `queue_stats_configuration` and `wfm_integrations` to Flex Configuration + +**Serverless** +- Add Function Version Content endpoint +- Allow build_sid to be optional for deployment requests + +**Supersim** +- Remove `deactivated` status for Super SIM which is replaced by `inactive` **(breaking change)** + + +[2020-03-18] Version 6.37.0 +--------------------------- +**Api** +- Add optional `emergency_calling_enabled` parameter to SIP Domain +- Add optional property `call_reason` in the call create request + +**Authy** +- Added `friendly_name` and `config` as optional params to Factor update +- Added `config` param to Factor creation **(breaking change)** + +**Preview** +- Renamed `SuccessRate` endpoint to `ImpressionsRate` for Branded Calls (fka. Verified by Twilio) **(breaking change)** + + +[2020-03-04] Version 6.36.0 +--------------------------- +**Library - Feature** +- [PR #507](https://github.com/twilio/twilio-python/pull/507): add new max_retries param to TwilioHttpClient. Thanks to [@msaelices](https://github.com/msaelices)! + +**Authy** +- Added the `configuration` property to services to return the service level configurations +- Added optional parameter `Push` when creating a service to send the service level push factor configuration +- Remove FactorStrength support for Factors and Challenges **(breaking change)** + +**Messaging** +- Correct the alpha sender capabilities property type **(breaking change)** + +**Preview** +- Removed `/Devices` register Branded Calls endpoint, as per iOS sample app deprecation **(breaking change)** +- Removed `Twilio-Sandbox-Mode` request header from the Branded Calls endpoints, as not officially supported **(breaking change)** +- Removed `Verify` version from `preview` subdomain in favor to `verify` subdomain. **(breaking change)** + +**Serverless** +- Add UI-Editable field to Services + +**Supersim** +- Add `inactive` status for Super SIM which is an alias for `deactivated` + +**Taskrouter** +- Adding value range to `priority` in task endpoint + +**Verify** +- Fix `SendCodeAttempts` type. It's an array of objects instead of a unique object. **(breaking change)** + + +[2020-02-19] Version 6.35.5 +--------------------------- +**Api** +- Make call create parameters `async_amd`, `async_amd_status_callback`, and `async_amd_status_callback_method` public +- Add `trunk_sid` as an optional field to Call resource fetch/read responses +- Add property `queue_time` to successful response of create, fetch, and update requests for Call +- Add optional parameter `byoc` to conference participant create. + +**Authy** +- Added support for challenges associated to push factors + +**Flex** +- Adding `ui_dependencies` to Flex Configuration + +**Messaging** +- Deprecate Session API **(breaking change)** + +**Numbers** +- Add Regulations API + +**Studio** +- Add Execution and Step endpoints to v2 API +- Add webhook_url to Flow response and add new /TestUsers endpoint to v2 API + +**Taskrouter** +- Adding `longest_relative_task_age_in_queue` and `longest_relative_task_sid_in_queue` to TaskQueue Real Time Statistics API. +- Add `wait_duration_in_queue_until_accepted` aggregations to TaskQueues Cumulative Statistics endpoint +- Add TaskQueueEnteredDate property to Tasks. + +**Video** +- [Composer] Clarification for the composition hooks creation documentation: one source is mandatory, either the `audio_sources` or the `video_layout`, but one of them has to be provided +- [Composer] `audio_sources` type on the composer HTTP POST command, changed from `sid[]` to `string[]` **(breaking change)** +- [Composer] Clarification for the composition creation documentation: one source is mandatory, either the `audio_sources` or the `video_layout`, but one of them has to be provided + + +[2020-02-05] Version 6.35.4 +--------------------------- +**Api** +- Making content retention and address retention public +- Update `status` enum for Messages to include 'partially_delivered' + +**Authy** +- Added support for push factors + +**Autopilot** +- Add one new property in Query i.e dialogue_sid + +**Verify** +- Add `SendCodeAttempts` to create verification response. + +**Video** +- Clarification in composition creation documentation: one source is mandatory, either `audio_sources` or `video_layout`, but on of them has to be provided + +**Twiml** +- Add Polly Neural voices. + + +[2020-01-22] Version 6.35.3 +--------------------------- +**Library - Docs** +- [PR #504](https://github.com/twilio/twilio-python/pull/504): baseline all the templated markdown docs. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Api** +- Add payments public APIs +- Add optional parameter `byoc` to call create request. + +**Flex** +- Updating a Flex Flow `creation_on_message` parameter documentation + +**Preview** +- +- Removed Verify v2 from preview in favor of its own namespace as GA **(breaking change)** + +**Studio** +- Flow definition type update from string to object + +**Verify** +- Add `AppHash` parameter when creating a Verification. +- Add `DoNotShareWarningEnabled` parameter to the Service resource. + +**Twiml** +- Add `track` attribute to siprec noun. +- Add attribute `byoc` to `` + + +[2020-01-08] Version 6.35.2 +--------------------------- +**Numbers** +- Add Regulatory Compliance CRUD APIs + +**Studio** +- Add parameter validation for Studio v2 Flows API + +**Twiml** +- Add support for `speech_model` to `Gather` verb + + +[2019-12-18] Version 6.35.1 +--------------------------- +**Preview** +- Add `/Insights/SuccessRate` endpoint for Businesses Branded Calls (Verified by Twilio) + +**Studio** +- StudioV2 API in beta + +**Verify** +- Add `MailerSid` property to Verify Service resource. + +**Wireless** +- Added `data_limit_strategy` to Rate Plan resource. + + +[2019-12-12] Version 6.35.0 +--------------------------- +**Library** +- [PR #500](https://github.com/twilio/twilio-python/pull/500): feat: support http proxy in TwilioHttpClient. Thanks to [@thehackercat](https://github.com/thehackercat)! + +**Api** +- Make `twiml` conditional for create. One of `url`, `twiml`, or `application_sid` is now required. +- Add `bundle_sid` parameter to /IncomingPhoneNumbers API +- Removed discard / obfuscate parameters from ContentRetention, AddressRetention **(breaking change)** + +**Chat** +- Added `last_consumed_message_index` and `last_consumption_timestamp` parameters in update method for UserChannel resource **(breaking change)** + +**Conversations** +- Add Participant SID to Message properties + +**Messaging** +- Fix incorrectly typed capabilities property for ShortCodes. **(breaking change)** + + +[2019-12-04] Version 6.34.0 +--------------------------- +**Library** +- [PR #501](https://github.com/twilio/twilio-python/pull/501): BREAKING CHANGE feat: add custom HTTP header support. Thanks to [@eshanholtz](https://github.com/eshanholtz)! **(breaking change)** +- [PR #502](https://github.com/twilio/twilio-python/pull/502): fix: regenerate python lib with yoyodyne refactor. Thanks to [@eshanholtz](https://github.com/eshanholtz)! +- [PR #499](https://github.com/twilio/twilio-python/pull/499): docs: add supported language versions to README. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Api** +- Add optional `twiml` parameter for call create + +**Chat** +- Added `delete` method in UserChannel resource + +**Conversations** +- Allow Messaging Service update + +**Taskrouter** +- Support ReEvaluateTasks parameter on Workflow update + +**Twiml** +- Remove unsupported `mixed_track` value from `` **(breaking change)** +- Add missing fax `` optional attributes + + +[2019-11-13] Version 6.33.1 +--------------------------- +**Library** +- [PR #498](https://github.com/twilio/twilio-python/pull/498): docs: Add local testing docs. Thanks to [@childish-sambino](https://github.com/childish-sambino)! +- [PR #497](https://github.com/twilio/twilio-python/pull/497): fix: Resolve some bug risks and code quality issues. Thanks to [@sanketsaurav](https://github.com/sanketsaurav)! +- [PR #495](https://github.com/twilio/twilio-python/pull/495): Rename child twiml methods to be the tag name and deprecate old methods. Thanks to [@eshanholtz](https://github.com/eshanholtz)! +- [PR #490](https://github.com/twilio/twilio-python/pull/490): fix: Change ObsoleteException to inherit from Exception instead of BaseException. Thanks to [@fefi95](https://github.com/fefi95)! + +**Api** +- Make `persistent_action` parameter public +- Add `twiml` optional private parameter for call create +- Update the call `price` property type to be string **(breaking change)** + +**Autopilot** +- Add Export resource to Autopilot Assistant. + +**Flex** +- Added Integration.RetryCount attribute to Flex Flow +- Updating a Flex Flow `channel_type` options documentation + +**Insights** +- Added edges to events and metrics +- Added new endpoint definitions for Events and Metrics + +**Messaging** +- **create** support for sender registration +- **fetch** support for fetching a sender +- **update** support for sender verification + +**Supersim** +- Add `Direction` filter parameter to list commands endpoint +- Allow filtering commands list by Sim Unique Name +- Add `Iccid` filter parameter to list sims endpoint + +**Twiml** +- Add support for `` verb + + +[2019-10-30] Version 6.33.0 +--------------------------- +**Library** +- [PR #414](https://github.com/twilio/twilio-python/pull/414): Add support for passing custom logger into TwilioHttpClient. Thanks to [@tysonholub](https://github.com/tysonholub)! +- [PR #423](https://github.com/twilio/twilio-python/pull/423): Document exception case in README. Thanks to [@prateem](https://github.com/prateem)! +- [PR #489](https://github.com/twilio/twilio-python/pull/489): Include the license file when packaging the library. Thanks to [@marcelotrevisani](https://github.com/marcelotrevisani)! +- [PR #485](https://github.com/twilio/twilio-python/pull/485): Adding timeout to TwilioHttpClient constructor. Thanks to [@Kerl1310](https://github.com/Kerl1310)! +- [PR #488](https://github.com/twilio/twilio-python/pull/488): Update resources after sorting. Thanks to [@childish-sambino](https://github.com/childish-sambino)! +- [PR #486](https://github.com/twilio/twilio-python/pull/486): Declare support for Python 3.8. Thanks to [@Jamim](https://github.com/Jamim)! + +**Api** +- Add new usage categories to the public api `sms-messages-carrierfees` and `mms-messages-carrierfees` + +**Conversations** +- Add ProjectedAddress to Conversations Participant resource + +**Preview** +- Implemented different `Sid` for Current Calls (Verified by Twilio), instead of relying in `Call.Sid` from Voice API team **(breaking change)** + +**Supersim** +- Add List endpoint to Commands resource for Super Sim Pilot +- Add UsageRecords resource for the Super Sim Pilot +- Add List endpoint to UsageRecords resource for the Super Sim Pilot +- Allow assigning a Sim to a Fleet by Fleet SID or Unique Name for Super SIM Pilot +- Add Update endpoint to Fleets resource for Super Sim Pilot +- Add Fetch endpoint to Commands resource for Super Sim Pilot +- Allow filtering the Sims resource List endpoint by Fleet +- Add List endpoint to Fleets resource for Super Sim Pilot + +**Wireless** +- Added `account_sid` to Sim update parameters. + +**Twiml** +- Add new locales and voices for `Say` from Polly + + +[2019-10-16] Version 6.32.0 +--------------------------- +**Library** +- [PR #482](https://github.com/twilio/twilio-python/pull/482): Update a few property types in the lookups and trunking responses. Thanks to [@childish-sambino](https://github.com/childish-sambino)! +- [PR #483](https://github.com/twilio/twilio-python/pull/483): Update instance property marshaling to allow missing properties. Thanks to [@childish-sambino](https://github.com/childish-sambino)! +- [PR #484](https://github.com/twilio/twilio-python/pull/484): Feature/remove socks dependency. Thanks to [@Kerl1310](https://github.com/Kerl1310)! +- [PR #481](https://github.com/twilio/twilio-python/pull/481): Change typehint for `PhoneNumberInstance.carrier`. Thanks to [@NCPlayz](https://github.com/NCPlayz)! +- [PR #480](https://github.com/twilio/twilio-python/pull/480): Auto-deploy via Travis CI upon tagged commit to master. Thanks to [@thinkingserious](https://github.com/thinkingserious)! +- [PR #479](https://github.com/twilio/twilio-python/pull/479): breaking: Correct video composition date types. Thanks to [@childish-sambino](https://github.com/childish-sambino)! **(breaking change)** + +**Api** +- Add new property `attempt` to sms_messages +- Fixed a typo in the documentation for Feedback outcome enum **(breaking change)** +- Update the call price to be optional for deserializing **(breaking change)** + +**Flex** +- Added `JanitorEnabled` attribute to Flex Flow +- Change `features_enabled` Flex Configuration key to private **(breaking change)** + +**Supersim** +- Add Fetch endpoint to Fleets resource for Super Sim Pilot +- Allow assigning a Sim to a Fleet for Super Sim Pilot +- Add Create endpoint to Fleets resource for Super Sim Pilot + +**Twiml** +- Update `` rename "whisper" attribute to "coach" **(breaking change)** + + +[2019-10-02] Version 6.31.1 +--------------------------- +**Library** +- [PR #477](https://github.com/twilio/twilio-python/pull/477): added validation of signature without stripping port number. Thanks to [@eshanholtz](https://github.com/eshanholtz)! + +**Conversations** +- Add media to Conversations Message resource + +**Supersim** +- Add List endpoint to Sims resource for Super Sim Pilot + + +[2019-09-18] Version 6.31.0 +---------------------------- +**Numbers** +- Add v2 of the Identites API + +**Preview** +- Changed authentication method for SDK Trusted Comms endpoints: `/CPS`, `/CurrentCall`, and `/Devices`. Please use `Authorization: Bearer ` **(breaking change)** + +**Voice** +- Add Recordings endpoints + + +[2019-09-04] Version 6.30.0 +---------------------------- +**Api** +- Pass Twiml in call update request + +**Conversations** +- Add attributes to Conversations resources + +**Flex** +- Adding `features_enabled` and `serverless_service_sids` to Flex Configuration + +**Messaging** +- Message API required params updated **(breaking change)** + +**Preview** +- Added support for the optional `CallSid` to `/BrandedCalls` endpoint + + +[2019-08-21] Version 6.29.4 +---------------------------- +**Library** +- [PR #474](https://github.com/twilio/twilio-python/pull/474): Use PyJWT version >= 1.4.2 in requirements.txt. Thanks to [@storymode7](https://github.com/storymode7)! +- [PR #473](https://github.com/twilio/twilio-python/pull/473): Update the IP messaging domain name to be 'chat'. Thanks to [@childish-sambino](https://github.com/childish-sambino)! + +**Conversations** +- Add Chat Conversation SID to conversation default output properties + +**Flex** +- Adding `outbound_call_flows` object to Flex Configuration +- Adding read and fetch to channels API + +**Supersim** +- Add Sims and Commands resources for the Super Sim Pilot + +**Sync** +- Added configuration option for enabling webhooks from REST. + +**Wireless** +- Added `usage_notification_method` and `usage_notification_url` properties to `rate_plan`. + +**Twiml** +- Add support for `ach-debit` transactions in `Pay` verb + + +[2019-08-05] Version 6.29.3 +---------------------------- +**Preview** +- Added support for the header `Twilio-Sandbox-Mode` to mock all Voice dependencies + +**Twiml** +- Add support for `` noun +- Add support for `` noun +- Create verbs `` and `` + + +[2019-07-24] Version 6.29.2 +---------------------------- +**Insights** +- Added `properties` to summary. + +**Preview** +- Added endpoint to brand a call without initiating it, so it can be initiated manually by the Customer + +**Twiml** +- Update `` recording events **(breaking change)** + + +[2019-07-10] Version 6.29.1 +---------------------------- +**Api** +- Make `friendly_name` optional for applications create +- Add new property `as_of` date to Usage Record API calls + +**Wireless** +- Added Usage Records resource. + + +[2019-06-26] Version 6.29.0 +---------------------------- +**Autopilot** +- Adds two new properties in Assistant i.e needs_model_build and development_stage + +**Preview** +- Changed phone numbers from _URL|Path_ to `X-XCNAM-Sensitive` headers **(breaking change)** + +**Verify** +- Add `MessagingConfiguration` resource to verify service + + +[2019-06-12] Version 6.28.0 +---------------------------- +**Autopilot** +- Add Webhooks resource to Autopilot Assistant. + +**Flex** +- Added missing 'custom' type to Flex Flow +- Adding `integrations` to Flex Configuration + +**Insights** +- Added attributes to summary. + +**Messaging** +- Message API Create updated with conditional params **(breaking change)** + +**Proxy** +- Document that Proxy will return a maximum of 100 records for read/list endpoints **(breaking change)** +- Remove non-updatable property parameters for Session update (mode, participants) **(breaking change)** + +**Sync** +- Added reachability debouncing configuration options. + +**Verify** +- Add `RateLimits` and `Buckets` resources to Verify Services +- Add `RateLimits` optional parameter on `Verification` creation. + +**Twiml** +- Fix `` participantIdentity casing + + +[2019-05-29] Version 6.27.1 +---------------------------- +**Verify** +- Add `approved` to status enum + + +[2019-05-15] Version 6.27.0 +---------------------------- +**Api** +- Make `method` optional for queue members update + +**Chat** +- Removed `webhook.*.format` update parameters in Service resource from public library visibility in v1 **(breaking change)** + +**Insights** +- Added client metrics as sdk_edge to summary. +- Added optional query param processing_state. + +**Numbers** +- Add addtional metadata fields on a Document +- Add status callback fields and parameters + +**Taskrouter** +- Added `channel_optimized_routing` attribute to task-channel endpoint + +**Video** +- [Rooms] Add Video Subscription API + +**Wireless** +- Added `imei` to Data Session resource. +- Remove `imeisv` from Data Session resource. **(breaking change)** + + +[2019-05-01] Version 6.26.3 +---------------------------- +**Serverless** +- Documentation + +**Wireless** +- Added `imeisv` to Data Session resource. + + +[2019-04-24] Version 6.26.2 +---------------------------- +**Library** +- PR #465: Prepend the repo root to the system paths during doc generation. Thanks to @childish-sambino! +- PR #463: Migrate the README to markdown. Thanks to @childish-sambino! + +**Api** +- Add `verified` property to Addresses + +**Numbers** +- Add API for Identites and documents + +**Proxy** +- Add in use count on number instance + + +[2019-04-12] Version 6.26.1 +---------------------------- +**Library** +- PR #459: Add py37 to TravisCI config. Thanks to @childish-sambino! +- PR #458: Make the Yoyodyne watermark a raw string. Thanks to @childish-sambino! + +**Flex** +- Adding PluginService to Flex Configuration + +**Numbers** +- Add API for Proof of Addresses + +**Proxy** +- Clarify documentation for Service and Session fetch + +**Serverless** +- Serverless scaffolding + + +[2019-03-28] Version 6.26.0 +---------------------------- +**Api** +- Remove optional `if_machine` call create parameter from helper libraries **(breaking change)** +- Changed `call_sid` path parameter type on QueueMember fetch and update requests **(breaking change)** + +**Voice** +- changed file names to dialing_permissions prefix **(breaking change)** + +**Wireless** +- Added `ResetStatus` property to Sim resource to allow resetting connectivity via the API. + + +[2019-03-15] Version 6.25.2 +---------------------------- +**Library** +- PR #457: Add Help Center and Support Ticket links to the README. Thanks to @childish-sambino! + +**Api** +- Add `machine_detection_speech_threshold`, `machine_detection_speech_end_threshold`, `machine_detection_silence_timeout` optional params to Call create request + +**Flex** +- Adding Flex Channel Orchestration +- Adding Flex Flow + + +[2019-03-06] Version 6.25.1 +---------------------------- +**Twiml** +- Add `de1` to `` regions + + +[2019-03-01] Version 6.25.0 +---------------------------- +**Api** +- Make conference participant preview parameters public + +**Authy** +- Added support for FactorType and FactorStrength for Factors and Challenges + +**Iam** +- First public release + +**Verify** +- Add endpoint to update/cancel a Verification **(breaking change)** + +**Video** +- [Composer] Make RoomSid mandatory **(breaking change)** +- [Composer] Add `enqueued` state to Composition + +**Twiml** +- Update message body to not be required for TwiML `Dial` noun. + + +[2019-02-15] Version 6.24.1 +---------------------------- +**Api** +- Add `force_opt_in` optional param to Messages create request +- Add agent conference category to usage records + +**Flex** +- First public release + +**Taskrouter** +- Adding `reject_pending_reservations` to worker update endpoint +- Added `event_date_ms` and `worker_time_in_previous_activity_ms` to Events API response +- Add ability to filter events by TaskChannel + +**Verify** +- Add `EnablePsd2` optional parameter for PSD2 on Service resource creation or update. +- Add `Amount`, `Payee` optional parameters for PSD2. + + +[2019-02-04] Version 6.24.0 +---------------------------- +**Library** +- PR #453: Switch body validator to use hex instead of base64. Thanks to @cjcodes! + +**Video** +- [Recordings] Add media type filter to list operation +- [Composer] Filter Composition Hook resources by FriendlyName + +**Twiml** +- Update `language` enum for `Gather` to fix language code for Filipino (Philippines) and include additional supported languages **(breaking change)** + + +[2019-01-11] Version 6.23.1 +---------------------------- +**Verify** +- Add `lookup` information in the response when creating a new verification (depends on the LookupEnabled flag being enabled at the service level) +- Add `VerificationSid` optional parameter on Verification check. + + +[2019-01-10] Version 6.23.0 +---------------------------- +**Chat** +- Mark Member attributes as PII + +**Proxy** +- Remove unsupported query parameters **(breaking change)** +- Remove invalid session statuses in doc + + +[2019-01-02] Version 6.22.1 +---------------------------- +**Insights** +- Initial revision. + + +[2018-12-17] Version 6.22.0 +---------------------------- +**Authy** +- Reverted the change to `FactorType` and `FormType`, avoiding conflicts with Helper Libraries reserved words (`type`) **(breaking change)** + +**Proxy** +- Remove incorrect parameter for Session List + +**Studio** +- Support date created filtering on list of executions + +**Taskrouter** +- Adding ability to Create, Modify and Delete Task Channels. + +**Verify** +- Add `SkipSmsToLandlines`, `TtsName`, `DtmfInputRequired` optional parameters on Service resource creation or update. + +**Wireless** +- Added delete action on Command resource. +- Added delete action on Sim resource. + +**Twiml** +- Change `currency` from enum to string for `Pay` **(breaking change)** + + +[2018-11-30] Version 6.21.0 +---------------------------- +**Api** +- Add `interactive_data` optional param to Messages create request + +**Authy** +- Required authentication for `/v1/Forms/{type}` endpoint **(breaking change)** +- Removed `Challenge.reason` to `Challenge.responded_reason` +- Removed `verification_sid` from Challenge responses +- Removed `config` param from the Factor creation +- Replaced all occurrences of `FactorType` and `FormType` in favor of a unified `Type` **(breaking change)** + +**Chat** +- Add Member attributes + +**Preview** +- Removed `Authy` version from `preview` subdomain in favor to `authy` subdomain. **(breaking change)** + +**Verify** +- Add `CustomCode` optional parameter on Verication creation. + + +[2018-11-16] Version 6.20.0 +---------------------------- +**Messaging** +- Session API + +**Twiml** +- Change `master-card` to `mastercard` as `cardType` for `Pay` and `Prompt`, remove attribute `credential_sid` from `Pay` **(breaking change)** + + +[2018-10-29] Version 6.19.2 +---------------------------- +**Api** +- Add new Balance resource: + - url: '/v1/Accounts/{account sid}/Balance' + - supported methods: GET + - returns the balance of the account + +**Proxy** +- Add chat_instance_sid to Service + +**Verify** +- Add `Locale` optional parameter on Verification creation. + + +[2018-10-15] Version 6.19.1 +---------------------------- +**Api** +- Add Verb Transactions category to usage records + +**Twiml** +- Add support for `Pay` verb + + +[2018-10-15] Version 6.19.0 +---------------------------- +**Api** +- Add `coaching` and `call_sid_to_coach` to participant properties, create and update requests. + +**Authy** +- Set public library visibility, and added PII stanza +- Dropped support for `FactorType` param given new Factor prefixes **(breaking change)** +- Supported `DELETE` actions for Authy resources +- Move Authy Services resources to `authy` subdomain + +**Autopilot** +- Introduce `autopilot` subdomain with all resources from `preview.understand` + +**Preview** +- Renamed Understand intent to task **(breaking change)** +- Deprecated Authy endpoints from `preview` to `authy` subdomain + +**Taskrouter** +- Allow TaskQueue ReservationActivitySid and AssignmentActivitySid to not be configured for MultiTask Workspaces + +**Verify** +- Add `LookupEnabled` optional parameter on Service resource creation or update. +- Add `SendDigits` optional parameter on Verification creation. +- Add delete action on Service resourse. + +**Twiml** +- Add custom parameters to TwiML `Client` noun and renamed the optional `name` field to `identity`. This is a breaking change in Ruby, and applications will need to transition from `dial.client ''` and `dial.client 'alice'` formats to `dial.client` and `dial.client(identity: alice)` formats. **(breaking change)** + + +[2018-10-04] Version 6.18.1 +---------------------------- +**Preview** +- Renamed response headers for Challenge and Factors Signatures + +**Video** +- [Composer] Add Composition Hook resources + +**Twiml** +- Add `debug` to `Gather` +- Add `participantIdentity` to `Room` + + +[2018-09-28] Version 6.18.0 +---------------------------- +**Api** +- Set `call_sid_to_coach` parameter in participant to be `preview` + +**Preview** +- Supported `totp` in Authy preview endpoints +- Allowed `latest` in Authy Challenges endpoints + +**Voice** +- changed path param name from parent_iso_code to iso_code for highrisk_special_prefixes api **(breaking change)** +- added geo permissions public api + + +[2018-09-20] Version 6.17.0 +---------------------------- +**Preview** +- Add `Form` resource to Authy preview given a `form_type` +- Add Authy initial api-definitions in the 4 main resources: Services, Entities, Factors, Challenges + +**Pricing** +- add voice_numbers resource (v2) + +**Verify** +- Move from preview to beta **(breaking change)** + + +[2018-08-31] Version 6.16.4 +---------------------------- +**Library** +- PR #444: VCORE-3651 Add support for *for* attribute in twiml element. Thanks to @nmahure! + +**Api** +- Add `call_sid_to_coach` parameter to participant create request +- Add `voice_receive_mode` param to IncomingPhoneNumbers create + +**Video** +- [Recordings] Expose `offset` property in resource + + +[2018-08-23] Version 6.16.3 +---------------------------- +**Chat** +- Add User Channel instance resource + + +[2018-08-17] Version 6.16.2 +---------------------------- +**Api** +- Add Proxy Active Sessions category to usage records + +**Preview** +- Add `Actions` endpoints and remove `ResponseUrl` from assistants on the Understand api + +**Pricing** +- add voice_country resource (v2) + + +[2018-08-09] Version 6.16.1 +---------------------------- +**Library** +- PR #443: move index and readme_include to root. Thanks to @mbichoffe! + +**Studio** +- Studio is now GA + + +[2018-08-03] Version 6.16.0 +---------------------------- +**Library** +- PR #442: Auto generate docs with sphinx. Thanks to @mbichoffe! +- PR #437: Tag and push Docker latest image when deploying with TravisCI. Thanks to @jonatasbaldin! + +**Chat** +- Make message From field updatable +- Add REST API webhooks + +**Notify** +- Removing deprecated `segments`, `users`, `segment_memberships`, `user_bindings` classes from helper libraries. **(breaking change)** + +**Preview** +- Add new Intent Statistics endpoint +- Remove `ttl` from Assistants + +**Twiml** +- Add `Connect` and `Room` for Programmable Video Rooms + + +[2018-07-27] Version 6.15.2 +---------------------------- +**Api** +- Add support for sip domains to map credential lists for registrations + +**Preview** +- Remove `ttl` from Assistants + +**Proxy** +- Enable setting a proxy number as reserved + +**Twiml** +- Add support for SSML lang tag on Say verb + + +[2018-07-17] Version 6.15.1 +---------------------------- +**Library** +- PR #439: Override generated attributes when generating TwiML. Thanks to @cjcodes! + +**Video** +- Add `group-small` room type + + +[2018-07-16] Version 6.15.0 +---------------------------- +**Library** +- PR #436: Add request body validation. Thanks to @cjcodes! + +**Twiml** +- Add support for SSML on Say verb, the message body is changed to be optional **(breaking change)** + + +[2018-07-11] Version 6.14.10 +----------------------------- +**Api** +- Add `cidr_prefix_length` param to SIP IpAddresses API + +**Studio** +- Add new /Execution endpoints to begin Engagement -> Execution migration + +**Video** +- [Rooms] Allow deletion of individual recordings from a room + + +[2018-07-05] Version 6.14.9 +---------------------------- +**Library** +- PR #434: Escape DOCKER_PASSWORD and DOCKER_USERNAME when logging into Docker Hub. Thanks to @jonatasbaldin! + + +[2018-07-05] Version 6.14.8 +---------------------------- +**Library** +- PR #433: Fix all Docker image build and push issues. Thanks to @jonatasbaldin! +- PR #432: Add docker to TravisCI. Thanks to @jonatasbaldin! +- PR #431: Add provider to TravisCI. Thanks to @jonatasbaldin! +- PR #430: Deploy just on tags and Python 3.6. Thanks to @jonatasbaldin! + +**Api** +- Release `Call Recording Controls` feature support in helper libraries +- Add Voice Insights sub-category keys to usage records + + +[2018-06-29] Version 6.14.7 +---------------------------- +**Library** +- PR #428: Add Dockerfile and related changes to build the Docker image. Thanks to @jonatasbaldin! + + +[2018-06-21] Version 6.14.6 +---------------------------- +**Library** +- PR #429: Do not use ElementTree.__nonzero__; add test for mixed content. Thanks to @ekarson! + +**Api** +- Add Fraud Lookups category to usage records + +**Video** +- Allow user to set `ContentDisposition` when obtaining media URLs for Room Recordings and Compositions +- Add Composition Settings resource + + +[2018-06-19] Version 6.14.5 +---------------------------- +**Library** +- PR #425: Allow adding TwiML children with generic tag names. Thanks to @mbichoffe! +- PR #422: Allow adding text to TwiML nodes. Thanks to @ekarson! +- PR #421: Add method to validate ssl certificate. Thanks to @yannieyip! + +**Twiml** +- Add methods to helper libraries to inject arbitrary text under a TwiML node + + +[2018-06-04] Version 6.14.4 +---------------------------- +**Lookups** +- Add back support for `fraud` lookup type + + +[2018-05-25] Version 6.14.3 +---------------------------- +**Library** +- PR #417: Migrate readme to rst and load it in with setup.py. Thanks to @cjcodes! + + +[2018-05-25] Version 6.14.2 +---------------------------- +**Chat** +- Add Binding and UserBinding documentation + + +[2018-05-25] Version 6.14.1 +---------------------------- +**Library** +- PR #416: Remove Python 3.3 support. Thanks to @cjcodes! + +**Api** +- Add more programmable video categories to usage records +- Add 'include_subaccounts' parameter to all variation of usage_record fetch + +**Studio** +- Add endpoint to delete engagements + +**Trunking** +- Added cnam_lookup_enabled parameter to Trunk resource. +- Added case-insensitivity for recording parameter to Trunk resource. + + +[2018-05-11] Version 6.14.0 +---------------------------- +**Chat** +- Add Channel Webhooks resource + +**Monitor** +- Update event filtering to support date/time **(breaking change)** + +**Wireless** +- Updated `maturity` to `ga` for all wireless apis + + +[2018-04-28] Version 6.13.0 +---------------------------- +**Video** +- Redesign API by adding custom `VideoLayout` object. **(breaking change)** + + +[2018-04-20] Version 6.12.1 +---------------------------- +**Twiml** +- Gather input Enum: remove unnecessary "dtmf speech" value as you can now specify multiple enum values for this parameter and both "dtmf" and "speech" are already available. + + +[2018-04-13] Version 6.12.0 +---------------------------- +**Library** +- PR #413: Add incoming.allow to AccessToken VoiceGrant. Thanks to @ryan-rowland! + +**Preview** +- Support for Understand V2 APIs - renames various resources and adds new fields + +**Studio** +- Change parameters type from string to object in engagement resource + +**Video** +- [Recordings] Change `size` type to `long`. **(breaking change)** + + +[2018-03-22] Version 6.11.0 +---------------------------- +**Lookups** +- Disable support for `fraud` lookups *(breaking change)* + +**Preview** +- Add `BuildDuration` and `ErrorCode` to Understand ModelBuild + +**Studio** +- Add new /Context endpoint for step and engagement resources. + + +[2018-03-12] Version 6.10.5 +---------------------------- +**Api** +- Add `caller_id` param to Outbound Calls API +- Release `trim` recording Outbound Calls API functionality in helper libraries + +**Video** +- [composer] Add `room_sid` to Composition resource. + +**Twiml** +- Adds support for passing in multiple input type enums when setting `input` on `Gather` + + +[2018-02-23] Version 6.10.4 +---------------------------- +**Api** +- Add `trim` param to Outbound Calls API + +**Lookups** +- Add support for `fraud` lookup type + +**Numbers** +- Initial Release + +**Video** +- [composer] Add `SEQUENCE` value to available layouts, and `trim` and `reuse` params. + + +[2018-02-09] Version 6.10.3 +---------------------------- +**Api** +- Add `AnnounceUrl` and `AnnounceMethod` params for conference announce + +**Chat** +- Add support to looking up user channels by identity in v1 + + +[2018-01-30] Version 6.10.2 +---------------------------- +**Preview** +- Remove Studio Engagement Deletion + +**Studio** +- Initial Release + + +[2018-01-30] Version 6.10.1 +---------------------------- +**Api** +- Add `studio-engagements` usage key + +**Video** +- [omit] Beta: Allow updates to `SubscribedTracks`. +- Add `SubscribedTracks`. +- Add track name to Video Recording resource +- Add Composition and Composition Media resources + + +[2018-01-19] Version 6.10.1 +---------------------------- +**Api** +- Add `conference_sid` property on Recordings +- Add proxy and sms usage key + +**Chat** +- Make user channels accessible by identity +- Add notifications logs flag parameter + +**Fax** +- Added `ttl` parameter + `ttl` is the number of minutes a fax is considered valid. + +**Preview** +- Add `call_delay`, `extension`, `verification_code`, and `verification_call_sids`. +- Add `failure_reason` to HostedNumberOrders. +- Add DependentHostedNumberOrders endpoint for AuthorizationDocuments preview API. + +**Taskrouter** +- Less verbose naming of cumulative and real time statistics *(breaking change)* + + +[2017-12-15] Version 6.10.0 +---------------------------- +**Library** +- Fix camelCased custom twiml parameters getting converted to lower case. (Issue #349) + +**Api** +- Add `voip`, `national`, `shared_cost`, and `machine_to_machine` sub-resources to `/2010-04-01/Accounts/{AccountSid}/AvailablePhoneNumbers/{IsoCountryCode}/` +- Add programmable video keys + +**Preview** +- Add `verification_type` and `verification_document_sid` to HostedNumberOrders. + +**Proxy** +- Fixed typo in session status enum value + +**Twiml** +- Fix Dial record property incorrectly typed as accepting TrimEnum values when it actually has its own enum of values. *(breaking change)* +- Add `priority` and `timeout` properties to Task TwiML. +- Add support for `recording_status_callback_event` for Dial verb and for Conference + + +[2017-12-01] Version 6.9.1 +--------------------------- +**Api** +- Use the correct properties for Dependent Phone Numbers of an Address *(breaking change)* +- Update Call Recordings with the correct properties + +**Preview** +- Add `status` and `email` query param filters for AuthorizationDocument list endpoint + +**Proxy** +- Added DELETE support to Interaction +- Standardized enum values to dash-case +- Rename Service#friendly_name to Service#unique_name + +**Video** +- Remove beta flag from `media_region` and `video_codecs` + +**Wireless** +- Bug fix: Changed `operator_mcc` and `operator_mnc` in `DataSessions` subresource from `integer` to `string` + + +[2017-11-17] Version 6.9.0 +--------------------------- +**Sync** +- Add TTL support for Sync objects *(breaking change)* + - The required `data` parameter on the following actions is now optional: "Update Document", "Update Map Item", "Update List Item" + - New actions available for updating TTL of Sync objects: "Update List", "Update Map", "Update Stream" + +**Video** +- [bi] Rename `RoomParticipant` to `Participant` +- Add Recording Settings resource +- Expose EncryptionKey and MediaExternalLocation properties in Recording resource + + +[2017-11-10] Version 6.8.4 +--------------------------- +**Accounts** +- Add AWS credential type + +**Preview** +- Removed `iso_country` as required field for creating a HostedNumberOrder. + +**Proxy** +- Added new fields to Service: geo_match_level, number_selection_behavior, intercept_callback_url, out_of_session_callback_url + + +[2017-11-03] Version 6.8.3 +--------------------------- +**Api** +- Add programmable video keys + +**Video** +- Add `Participants` + + +[2017-10-27] Version 6.8.2 +--------------------------- +**Chat** +- Add Binding resource +- Add UserBinding resource + + +[2017-10-20] Version 6.8.1 +--------------------------- +**Library** +- #394 Update request validator to remove port numbers from https urls. Thanks @Brodan! +- #385 Add request logging and hooking. Thanks @tysonholub! + +**Api** +- Add `address_sid` param to IncomingPhoneNumbers create and update +- Add 'fax_enabled' option for Phone Number Search + + +[2017-10-13] Version 6.8.0 +--------------------------- +**Api** +- Add `smart_encoded` param for Messages +- Add `identity_sid` param to IncomingPhoneNumbers create and update + +**Preview** +- Make 'address_sid' and 'email' optional fields when creating a HostedNumberOrder +- Add AuthorizationDocuments preview API. + +**Proxy** +- Initial Release + +**Wireless** +- Added `ip_address` to sim resource + +**Twiml** +- Rename `number` to `phone_number` in Voice Number TwiML. *(breaking change)* +- Rename `message` to `body` in Messaging TwiML. *(breaking change)* + + +[2017-10-06] Version 6.7.1 +--------------------------- +**Preview** +- Add `acc_security` (authy-phone-verification) initial api-definitions + +**Taskrouter** +- [bi] Less verbose naming of cumulative and real time statistics + + +[2017-09-28] Version 6.7.0 +--------------------------- +**Chat** +- Make member accessible through identity +- Make channel subresources accessible by channel unique name +- Set get list 'max_page_size' parameter to 100 +- Add service instance webhook retry configuration +- Add media message capability +- Make `body` an optional parameter on Message creation. *(breaking change)* + +**Notify** +- `data`, `apn`, `gcm`, `fcm`, `sms` parameters in `Notifications` create resource are dicts/objects instead of strings. Passing manually stringified json will continue to work. + +**Taskrouter** +- Add new query ability by TaskChannelSid or TaskChannelUniqueName +- Move Events, Worker, Workers endpoint over to CPR +- Add new RealTime and Cumulative Statistics endpoints + +**Video** +- Create should allow an array of video_codecs. +- Add video_codecs as a property of room to make it externally visible. + + +[2017-09-15] Version 6.6.3 +--------------------------- +**Api** +- Add `sip_registration` property on SIP Domains +- Add new video and market usage category keys + + +[2017-09-01] Version 6.6.2 +--------------------------- +- Added last_response and last_request to http_client + +[2017-09-01] Version 6.6.1 +--------------------------- +**Sync** +- Add support for Streams + +**Wireless** +- Added DataSessions sub-resource to Sims. + + +[2017-08-25] Version 6.6.0 +--------------------------- +**Library** +- Allow creating AccessTokens/Jwts without generating `nbf`. Passing `None` in the constructor will remove `nbf` from jwt payload. + +**Api** +- Update `status` enum for Recordings to include 'failed' +- Add `error_code` property on Recordings + +**Chat** +- Add mutable parameters for channel, members and messages + +**Video** +- New `media_region` parameter when creating a room, which controls which region media will be served out of. + +**Twiml** +- Add support for `speech_timeout`, `max_speech_time`, and `profanity_filter` attributes on Gather verb. + + +[2017-08-18] Version 6.5.2 +--------------------------- +**Library** +- Remove bundled certificates, use `certifi` package via `requests`. +- Add option to use connection pooling. This is enabled by default and will use one Session for all requests +in Client. + - To disable this, pass `pool_connections` parameter when creating your Twilio client. +```python +from twilio.rest import Client +from twilio.http.http_client import TwilioHttpClient + +client = Client( + username, + password, + http_client=TwilioHttpClient(pool_connections=False) +) +``` + +**Api** +- Add VoiceReceiveMode {'voice', 'fax'} option to IncomingPhoneNumber UPDATE requests + +**Chat** +- Add channel message media information +- Add service instance message media information + +**Preview** +- Removed 'email' from bulk_exports configuration api [bi]. No migration plan needed because api has not been used yet. +- Add DeployedDevices. + +**Sync** +- Add support for Service Instance unique names + +[2017-08-10] Version 6.5.1 +--------------------------- +Fixed PyJWT >= 1.5.1 exception + + +**Api** +- Add New wireless usage keys added +- Add `auto_correct_address` param for Addresses create and update +- Add ChatGrant grant and deprecate IpMessagingGrant + +**Video** +- Add `video_codec` enum and `video_codecs` parameter, which can be set to either `VP8` or `H264` during room creation. +- Restrict recordings page size to 100 + +[2017-07-27] Version 6.5.0 +--------------------------- +This release adds Beta and Preview products to main artifact. + +Previously, Beta and Preview products were only included in the `alpha` +artifact. They are now being included in the main artifact to ease product +discoverability and the collective operational overhead of maintaining multiple +artifacts per library. + +**Api** +- Remove unused `encryption_type` property on Recordings *(breaking change)* +- Update `status` enum for Messages to include 'accepted' + +**Messaging** +- Fix incorrectly typed capabilities property for PhoneNumbers. + +**Notify** +- Add `ToBinding` optional parameter on Notifications resource creation. Accepted values are json strings. + +**Preview** +- Add `sms_application_sid` to HostedNumberOrders. + +**Taskrouter** +- Fully support conference functionality in reservations. + + +[2017-07-12] Version 6.4.3 +--------------------------- +**Api** +- Update `AnnounceMethod` parameter naming for consistency + +**Notify** +- Add `ToBinding` optional parameter on Notifications resource creation. Accepted values are json strings. + +**Preview** +- Add `verification_attempts` to HostedNumberOrders. +- Add `status_callback_url` and `status_callback_method` to HostedNumberOrders. + +**Video** +- Filter recordings by date using the parameters `DateCreatedAfter` and `DateCreatedBefore`. +- Override the default time-to-live of a recording's media URL through the `Ttl` parameter (in seconds, default value is 3600). +- Add query parameters `SourceSid`, `Status`, `DateCreatedAfter` and `DateCreatedBefore` to the convenience method for retrieving Room recordings. + +**Wireless** +- Added national and international data limits to the RatePlans resource. + + +[2017-06-27] Version 6.4.2 +-------------------------- + +- Pin PyJWT to below version `1.5.1` to fix broken build. +- Fix json load error for python 3.3 - 3.5 + +[2017-06-16] Version 6.4.1 +-------------------------- + +- Add several missing `` attributes. + - `partial_result_callback` + - `partial_result_callback_method` + - `language` + - `hints` + - `barge_in` + - `acknowledge_sound_url` + - `input` +- Remove client-side max page size validation. +- Support `announce_url` and `announce_url_method` on Conference Participants. +- TwiML docstring corrections. + +[2017-06-15] Version 6.4.0 +-------------------------- + +- Remove support for Python 2.6. +- Add `locality` field to `AvailablePhoneNumbers`. +- Add `origin` field to `IncomingPhoneNumbers`. +- Add `in_locality` parameter to `AvailablePhoneNumbers`. +- Add `origin` parameter to `IncomingPhoneNumbers`. +- Add new sync categories to `UsageRecords`. +- Support unicode in `validation_client`. +- Add `muted` parameter to `` Twiml. + +[2017-05-24] Version 6.3.0 +-------------------------- + +- Rename RoomList to RoomRecordingsList. + +[2017-05-19] Version 6.2.0 +-------------------------- + +- Add video domain. +- Update usage record categories. +- Add `get_page` method for reentrant paging. + +[2017-05-12] Version 6.1.2 +---------------------------------- + +- Allow *kwargs in TwiML Gather + +[2017-05-10] Version 6.1.1 +---------------------------------- + +- Add Task verb to VoiceResponse +- Add Echo verb to VoiceResponse +- Add Sim verb to VoiceResponse + +[2017-04-27] Version 6.1.0 +-------------------------- + +- Add v2 of chat.twilio.com. +- Add `recording_channels` parameter to Participant create and update. +- Add `recording_status_callback` parameter to Participant create and update. +- Add `recording_status_callback_method` parameter to Participant create and update. +- Add `sip_auth_username` parameter to Participant create and update. +- Add `region` parameter to Participant create and update. +- Add `conference_recording_status_callback` parameter to Participant create and update. +- Add `conference_recording_status_callback_method` parameter to Participant create and update. +- Add `validity_period` parameter to Messages. + +[2017-04-03] Version 6.0.0 +-------------------------- +**New Major Version** + +The newest version of the `twilio-python` helper library! + +This version brings a host of changes to update and modernize the `twilio-python` helper library. It is auto-generated to produce a more consistent and correct product. + +- [Full API Documentation](https://twilio.github.io/twilio-python/) +- [General Documentation](https://www.twilio.com/docs/libraries/python) + +Version 4.4.0 +------------- + +Released May 19, 2015: + +- Add support for the beta field to IncomingPhoneNumbers and AvailablePhoneNumbers + +Version 4.3.0 +------------- + +Released May 14, 2015: + +- Add support for Call Status Events in TwiML + +Version 4.2.0 +------------- + +Released May 7, 2015: + +- Add support for the Twilio Monitor APIs: Events and Alerts + +Version 4.1.0 +------------- + +Released May 6, 2015: + +- Add support for the Twilio Pricing API + +Version 4.0.0 +------------- + +Released April 16, 2015: + +- Remove the deprecated count function from ListResource + +Version 3.8.0 +------------- + +Released March 31, 2015: + +- Support for the new Twilio Lookups API + +Version 3.7.3 +------------- + +Released March 10, 2015: + +- Add missing docstrings and examples for TaskRouter + +Version 3.7.2 +------------- + +Released February 24, 2015: + +- Restore Tokens resource to TwilioRestClient + +Version 3.7.1 +------------- + +Released February 20, 2015: + +- Restore Python 2.6 and 3.x support + +Version 3.7.0 +------------- + +Released February 18, 2015: + +- Add TaskRouterClient and resources to support the new TaskRouter API +- Stop prepending numeric error code to exception error messages + +Version 3.6.15 +-------------- + +Released January 14, 2015 + +- Update request construction for Tokens + +Version 3.6.14 +-------------- + +Released December 22, 2014 + +- Specify Python 3 dependencies in wheel package + +Version 3.6.12 +-------------- + +Released November 24, 2014 + +- Fix compatibility issue for Python 3.4 + +Version 3.6.11 +-------------- + +Released November 21, 2014 + +- Add support for the new Tokens endpoint + +Version 3.6.10 +-------------- + +Released November 13, 2014 + +- Add support for DELETE to Call and Message records +- Add support for redacting Message body fields + +Version 3.6.9 +------------- + +Released October 30, 2014 + +- Add Python 3.4 support +- Add wheel packaging +- Fix compatibility with earlier Python 2 releases + +Version 3.6.8 +------------- + +Released October 9, 2014 + +- Remove unneeded unittest2py3k dependency. +- Restore backwards-compatible exception import paths. + +Version 3.6.7 +------------- + +Released August 6, 2014 + +- Fix Python 2.5 compatibility. +- Add CallFeedback resources. +- Typo fixes and formatting cleanup. +- Refactor exception hierarchy and imports. +- Documentation improvements. + +Version 3.6.6 +-------------- + +Released on February 27, 2014 + +- Previously the error message was set based on the `tty` value; instead now we + detect `tty` when you try to print the error message. The `msg` property of + the exception is set to a decent value. +- `twilio-python` now uses entirely relative imports, so it may be easier to + include it as a part of another package. + +Version 3.6.5 +-------------- + +- Remove unittest2 dependency. +- Tests no longer run against Python 2.5. +- update(), delete() work on Application, Transcription and UsageTrigger + instance classes. + +Version 3.6.4 +------------- + +Released November 5, 2013 + +- Adds support for the 'digits' attribute of Play verbs in TwiML creation. +- Updates documentation for Message TwiML verb +- Bugfix for tty detection in error formatting + +Version 3.6.3 +------------- + +Released October 21, 2013 + +- Adds support for filtering by type to IncomingPhoneNumbers. + +- Adds support for filtering for mobile numbers to both IncomingPhoneNumbers + and AvailablePhoneNumbers. + + +Version 3.6.2 +------------- + +Released on September 24, 2013 + +- Adds support for HTTP and SOCKS4/5 proxies to the REST client. + + +Version 3.6.0, 3.6.1 +-------------------- + +Released on September 18, 2013 + +- Adds support for the new Message and SIP resources to the REST API client. +- Adds support for the new Message verb to the TwiML generator. + + +Version 3.5.3, 3.5.4 +-------------------- + +Released on September 6, 2013 + +- twilio-python now includes an SSL certfication file to ensure that + connections to api.twilio.com don't fail with SSLError. + +Version 3.5.2 +------------- + +Released on August 26, 2013 + +- You can now delete transcriptions + +Version 3.5.1 +------------- + +Released on May 21, 2013 + +- Fixes an issue in the 3.5.0 release where null dates would cause the library + to raise a TypeError. + +Version 3.5.0 +------------- + +Released on May 21, 2013 + +- `date_created` and `date_updated` objects are now returned as Python + `datetime.datetime` objects instead of as RFC 2822 formatted strings. This is + a backwards incompatible change. (via [@abrinsmead](/abrinsmead)) +- The library will not throw a UnicodeDecodeError when parsing API responses + with Python 3. +- You can pass integers to Twiml arguments. (via [@jvankoten](/jvankoten)) +- Ensuring the tests always pass on Python 3. (via [@ftobia](/ftobia)) +- Add the list of AUTHORS +- Fixes a timing attack vector in signature validation. (via [@zacharyvoase](/zacharyvoase)) + +Version 3.4.5 +------------- + +Released on April 1, 2013 + +Allow the Account object to access usage records and usage trigger data, in +addition to the client. Reporter: Trenton McManus + +Version 3.4.4 +------------- + +Adds support for Sip + +Version 3.4.3 +------------- + +Adds correct dependencies to the `setup.py` file. + +Version 3.4.2 +------------- + +Released on January 2, 2013 + +Adds a convenience function to retrieve the members of a queue by running +client.members("QU123"). + +Version 3.4.1 +------------- + +Python3 support! + +Version 3.3.11 +-------------- + +- Fix a bug where participants could not be kicked from a Conference + + +Version 3.3.10 +-------------- + +- Add support for Queue. Fix a bug where the library wouldn't work in Python 2.5 + + +Version 3.3.9 +------------- + +- Fix an error introduced in 3.3.7 that prevented validation calls from + succeeding. + +Version 3.3.8 +------------- + +- Use next_page_uri when iterating over a list resource + + +Version 3.3.7 +------------- + +- Allow arbitrary keyword arguments on resource creation and listing + +Version 3.3.6 +------------- + +- Remove doc/tmp directory which was preventing installation on certain Windows machines +- Add Travis CI integration +- Update httplib2 dependency + +Version 3.3.5 +------------- + +Released on January 18, 2011 + +- Fix a bug with the deprecated `TwilioRestClient.request` method +- Fix a bug in filtering SMS messages by DateSent + +Version 3.3.4 +------------- + +Released on December 16, 2011 + +- Allow both unicode strings and encoded byte strings in request data +- Add support for SMS and Voice application sids to phone number updating +- Fix documentation error relating to phone number purchasing +- Include doc string information for decorated functions + +Version 3.3.3 +------------- + +Released on November 3, 2011 + +- Support unicode characters when validating requests +- Add support for Great Britain language on the Say verb +- Set Sms Application, Voice Application, and/or a Friendly + Name when purchasing a number +- Add missing parameters for resource creation and update + +Version 3.3.2 +------------- + +Released on September 29, 2011 + +- TwiML verbs can now be used as context managers + +Version 3.3.1 +------------- + +Released on September 27, 2011 + +- Allow phone numbers to be transferred between accounts and subaccounts + +Version 3.3.0 +------------- + +Released on September 21, 2011 + +- Add support for Twilio Connect. Connect applications and authorized Connect + applications are now availble via the REST client. +- Fix a problem where date and datetimes weren't coverted to strings when + querying list resources diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000..2f0727ed54 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,73 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +- Using welcoming and inclusive language +- Being respectful of differing viewpoints and experiences +- Gracefully accepting constructive criticism +- Focusing on what is best for the community +- Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +- The use of sexualized language or imagery and unwelcome sexual attention or + advances +- Trolling, insulting/derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or electronic + address, without explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at open-source@twilio.com. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000000..41cb4474d0 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,162 @@ +# Contributing to `twilio-python` + +We'd love for you to contribute to our source code and to make `twilio-python` +even better than it is today! Here are the guidelines we'd like you to follow: + + - [Code of Conduct](#coc) + - [Question or Problem?](#question) + - [Issues and Bugs](#issue) + - [Feature Requests](#feature) + - [Documentation fixes](#docs) + - [Submission Guidelines](#submit) + - [Coding Rules](#rules) + - [Local Testing](#testing) + + +## Code of Conduct + +Help us keep `twilio-python` open and inclusive. Please be kind to and considerate +of other developers, as we all have the same goal: make `twilio-python` as good as +it can be. + +## Got an API/Product Question or Problem? + +If you have questions about how to use `twilio-python`, please see our +[docs](./README.md), and if you don't find the answer there, please contact +[Twilio Support](https://www.twilio.com/help/contact) with any issues you have. + +## Found an Issue? + +If you find a bug in the source code or a mistake in the documentation, you can +help us by submitting [an issue][issue-link]. If the file in which the error +exists has this header: +``` +""" +This code was generated by +\ / _ _ _| _ _ + | (_)\/(_)(_|\/| |(/_ v1.0.0 + / / +""" +``` +then it is a generated file and the change will need to be made by us, but +submitting an issue will help us track it and keep you up-to-date. If the file +isn't generated, you can help us out even more by submitting a Pull Request with +a fix. + +**Please see the [Submission Guidelines](#submit) below.** + +## Want a Feature? + +You can request a new feature by submitting an issue to our +[GitHub Repository][github]. If you would like to implement a new feature then +consider what kind of change it is: + +* **Major Changes** that you wish to contribute to the project should be + discussed first with `twilio-python` contributors in an issue or pull request so + that we can develop a proper solution and better coordinate our efforts, + prevent duplication of work, and help you to craft the change so that it is + successfully accepted into the project. +* **Small Changes** can be crafted and submitted to the + [GitHub Repository][github] as a Pull Request. + +## Want a Doc Fix? + +If you want to help improve the docs in the helper library, it's a good idea to +let others know what you're working on to minimize duplication of effort. Create +a new issue (or comment on a related existing one) to let others know what +you're working on. + +For large fixes, please build and test the documentation before submitting the +PR to be sure you haven't accidentally introduced layout or formatting issues. + +## Submission Guidelines + +### Submitting an Issue +Before you submit your issue search the archive, maybe your question was already +answered. + +If your issue appears to be a bug, and hasn't been reported, open a new issue. +Help us to maximize the effort we can spend fixing issues and adding new +features by not reporting duplicate issues. Providing the following information +will increase the chances of your issue being dealt with quickly: + +* **Overview of the Issue** - if an error is being thrown a non-minified stack + trace helps +* **Motivation for or Use Case** - explain why this is a bug for you +* **`twilio-python` Version(s)** - is it a regression? +* **Operating System (if relevant)** - is this a problem with all systems or + only specific ones? +* **Reproduce the Error** - provide an isolated code snippet or an unambiguous + set of steps. +* **Related Issues** - has a similar issue been reported before? +* **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point + to what might be causing the problem (line of code or commit) + +**If you get help, help others. Good karma rules!** + +### Submitting a Pull Request +Before you submit your pull request consider the following guidelines: + +* Search [GitHub][github] for an open or closed Pull Request that relates to + your submission. You don't want to duplicate effort. +* Make your changes in a new git branch: + + ```shell + git checkout -b my-fix-branch main + ``` + +* Create your patch, **including appropriate test cases**. +* Follow our [Coding Rules](#rules). +* Run the full `twilio-python` test suite (aliased by `make test`), and ensure + that all tests pass. +* Commit your changes using a descriptive commit message. + + ```shell + git commit -a + ``` + Note: the optional commit `-a` command line option will automatically "add" + and "rm" edited files. + +* Build your changes locally to ensure all the tests pass: + + ```shell + make test + ``` + +* Push your branch to GitHub: + + ```shell + git push origin my-fix-branch + ``` + +In GitHub, send a pull request to `twilio-python:main`. +If we suggest changes, then: + +* Make the required updates. +* Re-run the `twilio-python` test suite to ensure tests are still passing. +* Commit your changes to your branch (e.g. `my-fix-branch`). +* Push the changes to your GitHub repository (this will update your Pull Request). + +That's it! Thank you for your contribution! + +#### After your pull request is merged + +After your pull request is merged, you can safely delete your branch and pull +the changes from the main (upstream) repository. + +## Coding Rules + +To ensure consistency throughout the source code, keep these rules in mind as +you are working: + +* All features or bug fixes **must be tested** by one or more tests. +* All classes and methods **must be documented**. + +## Local Testing +There exists a separate `requirements.txt` document under `tests` that contains dependencies required for running unit tests. To install them and run the unit tests, try this: +``` +make test-install test +``` + +[issue-link]: https://github.com/twilio/twilio-python/issues/new +[github]: https://github.com/twilio/twilio-python \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000..065eb8d852 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,15 @@ +FROM python:3.7 + +ENV PYTHONUNBUFFERED 1 + +RUN mkdir /twilio +WORKDIR /twilio + +COPY setup.py . +COPY requirements.txt . +COPY README.md . +COPY twilio ./twilio +COPY tests ./tests + +RUN pip install . +RUN pip install -r tests/requirements.txt diff --git a/ISSUE_TEMPLATE.md b/ISSUE_TEMPLATE.md new file mode 100644 index 0000000000..e6154b546b --- /dev/null +++ b/ISSUE_TEMPLATE.md @@ -0,0 +1,30 @@ + + +### Issue Summary +A summary of the issue and the environment in which it occurs. If suitable, include the steps required to reproduce the bug. Please feel free to include screenshots, screencasts, or code examples. + +### Steps to Reproduce +1. This is the first step +2. This is the second step +3. Further steps, etc. + +### Code Snippet +```python +# paste code here +``` + +### Exception/Log +``` +# paste exception/log here +``` + +### Technical details: +* twilio-python version: +* python version: + diff --git a/LICENSE b/LICENSE index a2cd4a3636..6485c1f845 100644 --- a/LICENSE +++ b/LICENSE @@ -1,22 +1,21 @@ -Copyright (c) 2012 Twilio, Inc. +MIT License -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: +Copyright (C) 2023, Twilio, Inc. -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000000..bc75be523a --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,3 @@ +# Include the SSL certificate file in the package distributed by pip +recursive-include twilio/conf * +include LICENSE diff --git a/Makefile b/Makefile index 0a0cfbeebb..72cabbcfb1 100644 --- a/Makefile +++ b/Makefile @@ -1,12 +1,78 @@ +.PHONY: clean install analysis test test-install test-docker develop docs docs-install prettier prettier-check + venv: - virtualenv venv + @python --version || (echo "Python is not installed, Python 3.7+"; exit 1); + virtualenv --python=python venv install: venv . venv/bin/activate; pip install . +test-install: install + . venv/bin/activate; pip install -r tests/requirements.txt + +test-docker: + docker build -t twilio/twilio-python . + docker run twilio/twilio-python pytest tests --ignore=tests/cluster + +develop: venv + . venv/bin/activate; pip install -e . --use-mirrors + . venv/bin/activate; pip install -r tests/requirements.txt + analysis: - . venv/bin/activate; flake8 --ignore=E123,E126,E128,E501 tests - . venv/bin/activate; flake8 --ignore=F401 twilio + . venv/bin/activate; flake8 --ignore=E123,E126,E128,E501,W391,W291,W293,F401,W503,E203 tests + . venv/bin/activate; flake8 --ignore=E402,F401,W391,W291,W293,W503,E203 twilio --max-line-length=300 + +test: analysis prettier-check + . venv/bin/activate; pytest tests --ignore=tests/cluster + +test-with-coverage: prettier-check + . venv/bin/activate; \ + pytest --cov-config=setup.cfg --cov-report xml --cov=twilio tests --ignore=tests/cluster + +cluster-test: + . venv/bin/activate; pytest tests/cluster + +docs-install: + . venv/bin/activate; pip install -r tests/requirements.txt + +docs: + -rm -rf docs/source/_rst + -rm -rf docs/build + . venv/bin/activate; sphinx-apidoc -f twilio -o docs/source/_rst + . venv/bin/activate; sphinx-build -b html -c ./docs -d docs/build/doctrees . docs/build/html + + +release: + . venv/bin/activate; python setup.py sdist upload + . venv/bin/activate; python setup.py bdist_wheel upload + +build: test-install + . venv/bin/activate; python setup.py sdist + . venv/bin/activate; python setup.py bdist_wheel + +clean: + rm -rf venv + +nopyc: + find . -name \*.pyc -delete + +prettier: + . venv/bin/activate; autoflake --remove-all-unused-imports -i -r --exclude venv . + . venv/bin/activate; black . + +prettier-check: + . venv/bin/activate; autoflake --check-diff --quiet --remove-all-unused-imports -r --exclude venv . + . venv/bin/activate; black --check . + +API_DEFINITIONS_SHA=$(shell git log --oneline | grep Regenerated | head -n1 | cut -d ' ' -f 5) +CURRENT_TAG=$(shell expr "${GITHUB_TAG}" : ".*-rc.*" >/dev/null && echo "rc" || echo "latest") +docker-build: + docker build -t twilio/twilio-python . + docker tag twilio/twilio-python twilio/twilio-python:${GITHUB_TAG} + docker tag twilio/twilio-python twilio/twilio-python:apidefs-${API_DEFINITIONS_SHA} + docker tag twilio/twilio-python twilio/twilio-python:${CURRENT_TAG} -test: analysis - . venv/bin/activate; nosetests +docker-push: + docker push twilio/twilio-python:${GITHUB_TAG} + docker push twilio/twilio-python:apidefs-${API_DEFINITIONS_SHA} + docker push twilio/twilio-python:${CURRENT_TAG} diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000000..8510bbcb42 --- /dev/null +++ b/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,31 @@ + + +# Fixes # + +A short description of what this PR does. + +### Checklist +- [x] I acknowledge that all my contributions will be made under the project's license +- [ ] I have made a material change to the repo (functionality, testing, spelling, grammar) +- [ ] I have read the [Contribution Guidelines](https://github.com/twilio/twilio-python/blob/main/CONTRIBUTING.md) and my PR follows them +- [ ] I have titled the PR appropriately +- [ ] I have updated my branch with the main branch +- [ ] I have added tests that prove my fix is effective or that my feature works +- [ ] I have added the necessary documentation about the functionality in the appropriate .md file +- [ ] I have added inline documentation to the code I modified + +If you have questions, please file a [support ticket](https://twilio.com/help/contact), or create a GitHub Issue in this repository. diff --git a/README.md b/README.md index 93f758cac6..ed277788d1 100644 --- a/README.md +++ b/README.md @@ -1,52 +1,128 @@ # twilio-python -[![Build Status](https://secure.travis-ci.org/twilio/twilio-python.png?branch=master)](http://travis-ci.org/twilio/twilio-python) +[![Tests](https://github.com/twilio/twilio-python/actions/workflows/test-and-deploy.yml/badge.svg)](https://github.com/twilio/twilio-python/actions/workflows/test-and-deploy.yml) +[![PyPI](https://img.shields.io/pypi/v/twilio.svg)](https://pypi.python.org/pypi/twilio) +[![PyPI](https://img.shields.io/pypi/pyversions/twilio.svg)](https://pypi.python.org/pypi/twilio) +[![Learn OSS Contribution in TwilioQuest](https://img.shields.io/static/v1?label=TwilioQuest&message=Learn%20to%20contribute%21&color=F22F46&labelColor=1f243c&style=flat-square&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAMAAAD04JH5AAAASFBMVEUAAAAZGRkcHBwjIyMoKCgAAABgYGBoaGiAgICMjIyzs7PJycnMzMzNzc3UoBfd3d3m5ubqrhfrMEDu7u739/f4vSb/3AD///9tbdyEAAAABXRSTlMAAAAAAMJrBrEAAAKoSURBVHgB7ZrRcuI6EESdyxXGYoNFvMD//+l2bSszRgyUYpFAsXOeiJGmj4NkuWx1Qeh+Ekl9DgEXOBwOx+Px5xyQhDykfgq4wG63MxxaR4ddIkg6Ul3g84vCIcjPBA5gmUMeXESrlukuoK33+33uID8TWeLAdOWsKpJYzwVMB7bOzYSGOciyUlXSn0/ABXTosJ1M1SbypZ4O4MbZuIDMU02PMbauhhHMHXbmebmALIiEbbbbbUrpF1gwE9kFfRNAJaP+FQEXCCTGyJ4ngDrjOFo3jEL5JdqjF/pueR4cCeCGgAtwmuRS6gDwaRiGvu+DMFwSBLTE3+jF8JyuV1okPZ+AC4hDFhCHyHQjdjPHUKFDlHSJkHQXMB3KpSwXNGJPcwwTdZiXlRN0gSp0zpWxNtM0beYE0nRH6QIbO7rawwXaBYz0j78gxjokDuv12gVeUuBD0MDi0OQCLvDaAho4juP1Q/jkAncXqIcCfd+7gAu4QLMACCLxpRsSuQh0igu0C9Svhi7weAGZg50L3IE3cai4IfkNZAC8dfdhsUD3CgKBVC9JE5ABAFzg4QL/taYPAAWrHdYcgfLaIgAXWJ7OV38n1LEF8tt2TH29E+QAoDoO5Ve/LtCQDmKM9kPbvCEBApK+IXzbcSJ0cIGF6e8gpcRhUDogWZ8JnaWjPXc/fNnBBUKRngiHgTUSivSzDRDgHZQOLvBQgf8rRt+VdBUUhwkU6VpJ+xcOwQUqZr+mR0kvBUgv6cB4+37hQAkXqE8PwGisGhJtN4xAHMzrsgvI7rccXqSvKh6jltGlrOHA3Xk1At3LC4QiPdX9/0ndHpGVvTjR4bZA1ypAKgVcwE5vx74ulwIugDt8e/X7JgfkucBMIAr26ndnB4UCLnDOqvteQsHlgX9N4A+c4cW3DXSPbwAAAABJRU5ErkJggg==)](https://twil.io/learn-open-source) -A module for using the Twilio REST API and generating valid -[TwiML](http://www.twilio.com/docs/api/twiml/ "TwiML - -Twilio Markup Language"). [Click here to read the full -documentation.](http://readthedocs.org/docs/twilio-python/en/latest/ "Twilio -Python library documentation") +## Documentation + +The documentation for the Twilio API can be found [here][apidocs]. + +The Python library documentation can be found [here][libdocs]. + +## Versions + +`twilio-python` uses a modified version of [Semantic Versioning](https://semver.org) for all changes. [See this document](VERSIONS.md) for details. + +### Supported Python Versions + +This library supports the following Python implementations: + +- Python 3.7 +- Python 3.8 +- Python 3.9 +- Python 3.10 +- Python 3.11 +- Python 3.12 +- Python 3.13 ## Installation -Install from PyPi using [pip](http://www.pip-installer.org/en/latest/), a +Install from PyPi using [pip](https://pip.pypa.io/en/latest/), a package manager for Python. - $ pip install twilio +```shell +pip3 install twilio +``` + +If pip install fails on Windows, check the path length of the directory. If it is greater 260 characters then enable [Long Paths](https://docs.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation) or choose other shorter location. Don't have pip installed? Try installing it, by running this from the command line: - $ curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python +```shell +curl https://bootstrap.pypa.io/get-pip.py | python +``` Or, you can [download the source code -(ZIP)](https://github.com/twilio/twilio-python/zipball/master "twilio-python -source code") for `twilio-python`, and then run: +(ZIP)](https://github.com/twilio/twilio-python/zipball/main 'twilio-python +source code') for `twilio-python`, and then run: + +```shell +python3 setup.py install +``` - $ python setup.py install +> **Info** +> If the command line gives you an error message that says Permission Denied, try running the above commands with `sudo` (e.g., `sudo pip3 install twilio`). + +### Test your installation + +Try sending yourself an SMS message. Save the following code sample to your computer with a text editor. Be sure to update the `account_sid`, `auth_token`, and `from_` phone number with values from your [Twilio account](https://console.twilio.com). The `to` phone number will be your own mobile phone. + +```python +from twilio.rest import Client + +# Your Account SID and Auth Token from console.twilio.com +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +auth_token = "your_auth_token" + +client = Client(account_sid, auth_token) + +message = client.messages.create( + to="+15558675309", + from_="+15017250604", + body="Hello from Python!") + +print(message.sid) +``` + +Save the file as `send_sms.py`. In the terminal, `cd` to the directory containing the file you just saved then run: + +```shell +python3 send_sms.py +``` -You may need to run the above commands with `sudo`. +After a brief delay, you will receive the text message on your phone. -## Getting Started +> **Warning** +> It's okay to hardcode your credentials when testing locally, but you should use environment variables to keep them secret before committing any code or deploying to production. Check out [How to Set Environment Variables](https://www.twilio.com/blog/2017/01/how-to-set-environment-variables.html) for more information. -Getting started with the Twilio API couldn't be easier. Create a -`TwilioRestClient` and you're ready to go. +## OAuth Feature for Twilio APIs +We are introducing Client Credentials Flow-based OAuth 2.0 authentication. This feature is currently in beta and its implementation is subject to change. + +API examples [here](https://github.com/twilio/twilio-python/blob/main/examples/public_oauth.py) + +Organisation API examples [here](https://github.com/twilio/twilio-python/blob/main/examples/organization_api.py) + +## Use the helper library ### API Credentials -The `TwilioRestClient` needs your Twilio credentials. You can either pass these -directly to the constructor (see the code below) or via environment variables. +The `Twilio` client needs your Twilio credentials. You can either pass these directly to the constructor (see the code below) or via environment variables. + +Authenticating with Account SID and Auth Token: + +```python +from twilio.rest import Client + +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +auth_token = "your_auth_token" +client = Client(account_sid, auth_token) +``` + +Authenticating with API Key and API Secret: ```python -from twilio.rest import TwilioRestClient +from twilio.rest import Client -account = "ACXXXXXXXXXXXXXXXXX" -token = "YYYYYYYYYYYYYYYYYY" -client = TwilioRestClient(account, token) +api_key = "XXXXXXXXXXXXXXXXX" +api_secret = "YYYYYYYYYYYYYYYYYY" +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +client = Client(api_key, api_secret, account_sid) ``` -Alternately, a `TwilioRestClient` constructor without these parameters will +Alternatively, a `Client` constructor without these parameters will look for `TWILIO_ACCOUNT_SID` and `TWILIO_AUTH_TOKEN` variables inside the current environment. @@ -54,52 +130,174 @@ We suggest storing your credentials as environment variables. Why? You'll never have to worry about committing your credentials and accidentally posting them somewhere public. +```python +from twilio.rest import Client +client = Client() +``` + +### Specify Region and/or Edge + +To take advantage of Twilio's [Global Infrastructure](https://www.twilio.com/docs/global-infrastructure), specify the target Region and Edge for the client: + +> **Note:** When specifying a `region` parameter for a helper library client, be sure to also specify the `edge` parameter. For backward compatibility purposes, specifying a `region` without specifying an `edge` will result in requests being routed to US1. ```python -from twilio.rest import TwilioRestClient -client = TwilioRestClient() +from twilio.rest import Client + +client = Client(region='au1', edge='sydney') ``` +A `Client` constructor without these parameters will also look for `TWILIO_REGION` and `TWILIO_EDGE` variables inside the current environment. + +Alternatively, you may specify the edge and/or region after constructing the Twilio client: + +```python +from twilio.rest import Client + +client = Client() +client.region = 'au1' +client.edge = 'sydney' +``` + +This will result in the `hostname` transforming from `api.twilio.com` to `api.sydney.au1.twilio.com`. + ### Make a Call ```python -from twilio.rest import TwilioRestClient +from twilio.rest import Client -account = "ACXXXXXXXXXXXXXXXXX" -token = "YYYYYYYYYYYYYYYYYY" -client = TwilioRestClient(account, token) +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +auth_token = "your_auth_token" +client = Client(account_sid, auth_token) -call = client.calls.create(to="9991231234", - from_="9991231234", +call = client.calls.create(to="9991231234", + from_="9991231234", url="http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient") -print call.sid +print(call.sid) +``` + +### Get data about an existing call + +```python +from twilio.rest import Client + +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +auth_token = "your_auth_token" +client = Client(account_sid, auth_token) + +call = client.calls.get("CA42ed11f93dc08b952027ffbc406d0868") +print(call.to) ``` -### Send an SMS +### Iterate through records + +The library automatically handles paging for you. Collections, such as `calls` and `messages`, have `list` and `stream` methods that page under the hood. With both `list` and `stream`, you can specify the number of records you want to receive (`limit`) and the maximum size you want each page fetch to be (`page_size`). The library will then handle the task for you. + +`list` eagerly fetches all records and returns them as a list, whereas `stream` returns an iterator and lazily retrieves pages of records as you iterate over the collection. You can also page manually using the `page` method. + +`page_size` as a parameter is used to tell how many records should we get in every page and `limit` parameter is used to limit the max number of records we want to fetch. + +#### Use the `list` method + +```python +from twilio.rest import Client + +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +auth_token = "your_auth_token" +client = Client(account_sid, auth_token) + +for sms in client.messages.list(): + print(sms.to) +``` ```python -from twilio.rest import TwilioRestClient +client.messages.list(limit=20, page_size=20) +``` +This will make 1 call that will fetch 20 records from backend service. -account = "ACXXXXXXXXXXXXXXXXX" -token = "YYYYYYYYYYYYYYYYYY" -client = TwilioRestClient(account, token) +```python +client.messages.list(limit=20, page_size=10) +``` +This will make 2 calls that will fetch 10 records each from backend service. -message = client.sms.messages.create(to="+12316851234", from_="+15555555555", - body="Hello there!") +```python +client.messages.list(limit=20, page_size=100) ``` +This will make 1 call which will fetch 100 records but user will get only 20 records. -### Handling a call using TwiML +### Asynchronous API Requests -To control phone calls, your application needs to output -[TwiML](http://www.twilio.com/docs/api/twiml/ "TwiML - Twilio Markup -Language"). Use `twilio.twiml.Response` to easily create such responses. +By default, the Twilio Client will make synchronous requests to the Twilio API. To allow for asynchronous, non-blocking requests, we've included an optional asynchronous HTTP client. When used with the Client and the accompanying `*_async` methods, requests made to the Twilio API will be performed asynchronously. ```python -from twilio import twiml +from twilio.http.async_http_client import AsyncTwilioHttpClient +from twilio.rest import Client + +async def main(): + account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + auth_token = "your_auth_token" + http_client = AsyncTwilioHttpClient() + client = Client(account_sid, auth_token, http_client=http_client) + + message = await client.messages.create_async(to="+12316851234", from_="+15555555555", + body="Hello there!") + +asyncio.run(main()) +``` + +### Enable Debug Logging + +Log the API request and response data to the console: -r = twiml.Response() +```python +import logging + +client = Client(account_sid, auth_token) +logging.basicConfig() +client.http_client.logger.setLevel(logging.INFO) +``` + +Log the API request and response data to a file: + +```python +import logging + +client = Client(account_sid, auth_token) +logging.basicConfig(filename='./log.txt') +client.http_client.logger.setLevel(logging.INFO) +``` + +### Handling Exceptions + +Version 8.x of `twilio-python` exports an exception class to help you handle exceptions that are specific to Twilio methods. To use it, import `TwilioRestException` and catch exceptions as follows: + +```python +from twilio.rest import Client +from twilio.base.exceptions import TwilioRestException + +account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" +auth_token = "your_auth_token" +client = Client(account_sid, auth_token) + +try: + message = client.messages.create(to="+12316851234", from_="+15555555555", + body="Hello there!") +except TwilioRestException as e: + print(e) +``` + +### Generating TwiML + +To control phone calls, your application needs to output [TwiML][twiml]. + +Use `twilio.twiml.Response` to easily create such responses. + +```python +from twilio.twiml.voice_response import VoiceResponse + +r = VoiceResponse() r.say("Welcome to twilio!") -print str(r) +print(str(r)) ``` ```xml @@ -107,22 +305,20 @@ print str(r) Welcome to twilio! ``` -### Digging Deeper +### Other advanced examples + +- [Learn how to create your own custom HTTP client](./advanced-examples/custom-http-client.md) + +### Docker Image + +The `Dockerfile` present in this repository and its respective `twilio/twilio-python` Docker image are currently used by Twilio for testing purposes only. + +### Getting help -The full power of the Twilio API is at your fingertips. The [full -documentation](http://readthedocs.org/docs/twilio-python/en/latest/ "Twilio -Python library documentation") explains all the awesome features available to -use. +If you need help installing or using the library, please check the [Twilio Support Help Center](https://support.twilio.com) first, and [file a support ticket](https://twilio.com/help/contact) if you don't find an answer to your question. -* [Retrieve Call Records][calls] -* [Retrieve SMS Message Records][sms-messages] -* [Search for a Phone Number][number] -* [Buy a Number][number] -* [Validate a Phone Number][validate] -* [List Recordings][recordings] +If you've instead found a bug in the library or would like new features added, go ahead and open issues or pull requests against this repo! -[number]: http://twilio-python.readthedocs.org/en/latest/usage/phone-numbers.html#searching-and-buying-a-number -[validate]: http://twilio-python.readthedocs.org/en/latest/usage/caller-ids.html -[recordings]: http://twilio-python.readthedocs.org/en/latest/usage/recordings.html#listing-your-recordings -[sms-messages]: http://twilio-python.readthedocs.org/en/latest/usage/messages.html#retrieving-sent-messages -[calls]: http://twilio-python.readthedocs.org/en/latest/usage/phone-calls.html#retrieve-a-call-record +[apidocs]: https://www.twilio.com/docs/api +[twiml]: https://www.twilio.com/docs/api/twiml +[libdocs]: https://twilio.github.io/twilio-python diff --git a/UPGRADE.md b/UPGRADE.md new file mode 100644 index 0000000000..03c196bf5b --- /dev/null +++ b/UPGRADE.md @@ -0,0 +1,145 @@ +# Upgrade Guide + +_`MAJOR` version bumps will have upgrade notes +posted here._ + +## [2024-02-20] 8.x.x to 9.x.x +### Overview + +##### Twilio Python Helper Library’s major version 9.0.0 is now available. We ensured that you can upgrade to Python helper Library 9.0.0 version without any breaking changes of existing apis + +Behind the scenes Python Helper is now auto-generated via OpenAPI with this release. This enables us to rapidly add new features and enhance consistency across versions and languages. +We're pleased to inform you that version 9.0.0 adds support for the application/json content type in the request body. + + +## [2023-04-05] 7.x.x to 8.x.x + +- **Supported Python versions updated** + - Dropped support for Python 3.6 ([#632](https://github.com/twilio/twilio-python/pull/632)) + - Python 3.7 is the new required minimum version to use twilio-python helper library +- **Deletion of TwiML Voice Deprecated Methods ([#643](https://github.com/twilio/twilio-python/pull/643))** + + - [``](https://www.twilio.com/docs/voice/twiml/refer) + - `Refer.refer_sip()` replaced by `Refer.sip()` + - [``](https://www.twilio.com/docs/voice/twiml/say/text-speech#generating-ssml-via-helper-libraries) + + - `Say.ssml_break()` replaced by `Say.break_()` + - `Say.ssml_emphasis()` replaced by `Say.emphasis()` + - `Say.ssml_lang()` replaced by `Say.lang()` + - `Say.ssml_p()` replaced by `Say.p()` + - `Say.ssml_phoneme()` replaced by `Say.phoneme()` + - `Say.ssml_prosody()` replaced by `Say.prosody()` + - `Say.ssml_s()` replaced by `Say.s()` + - `Say.ssml_say_as()` replaced by `Say.say_as()` + - `Say.ssml_sub()` replaced by `Say.sub()` + - `Say.ssml_w()` replaced by `Say.w()` + + Old: + + ```python + from twilio.twiml.voice_response import VoiceResponse + resp = VoiceResponse() + say = resp.say("Hello") + say.ssml_emphasis("you") + ``` + + New: + + ```python + from twilio.twiml.voice_response import VoiceResponse + resp = VoiceResponse() + say = resp.say("Hello") + say.emphasis("you") + ``` + +- **JWT token building deprecations ([#644](https://github.com/twilio/twilio-python/pull/644))** + - `ConversationsGrant` has been deprecated in favor of `VoiceGrant` + - `IpMessagingGrant` has been removed +- `twilio.rest.api.v2010.account.available_phone_number` has been renamed to `twilio.rest.api.v2010.account.available_phone_number_country` +- **[TaskRouter Workers Statistics](https://www.twilio.com/docs/taskrouter/api/worker/statistics) operations updated ([#653](https://github.com/twilio/twilio-python/pull/653))** + + - Cumulative and Real-Time Workers Statistics no longer accept a WorkerSid + - `GET /v1/Workspaces/{WorkspaceSid}/Workers/CumulativeStatistics` + + Old: `client.taskrouter.v1.workspaces('WS...').workers('WK...).cumulative_statistics()` + + New: `client.taskrouter.v1.workspaces('WS...').workers.cumulative_statistics()` + + - `GET /v1/Workspaces/{WorkspaceSid}/Workers/RealTimeStatistics` + + Old: `client.taskrouter.v1.workspaces('WS...').workers('WK...).real_time_statistics()` + + New: `client.taskrouter.v1.workspaces('WS...').workers.real_time_statistics()` + +- **Internal refactor of `instance._properties`** + - Instance properties moved out of the generic `_properties` dict ([#696](https://github.com/twilio/twilio-python/pull/696)) + - This is an implementation detail that should not be depended upon + +## [2021-09-22] 6.x.x to 7.x.x + +### Overview + +Version `7.x.x` is the first version that officially drops support for Python versions 2.7, 3.4, and 3.5. + +#### Removal of files and dependencies that were added to support Python 2.7, 3.4, and 3.5 + +- [Six](https://github.com/twilio/twilio-python/pull/560/files#diff-4d7c51b1efe9043e44439a949dfd92e5827321b34082903477fd04876edb7552L4) + - Removed use of `u` a fake unicode literal + - Removed use of `b` a fake bytes literal + - Removed `PY3` a boolean indicating if the code is running on Python 3 + - `text_type` type for representing (Unicode) textual data --> `str` + - `iteritems` returns an iterator over dictionary’s items --> `items` + - `string_types` possible types for text data like basestring() in Python 2 and str in Python 3.--> `str` +- [twilio/compat.py](https://github.com/twilio/twilio-python/pull/560/files?file-filters%5B%5D=.md&file-filters%5B%5D=.py&file-filters%5B%5D=.toml&file-filters%5B%5D=.txt&file-filters%5B%5D=.yml&file-filters%5B%5D=No+extension#diff-e327449701a8717c94e1a084cdfc7dbf334c634cddf3867058b8f991d2de52c1L1) + - `from twilio.compat import urlencode` --> `from urllib.parse import urlencode` + - `izip` --> `zip` +- [twilio/jwt/compat.py](https://github.com/twilio/twilio-python/pull/560/files?file-filters%5B%5D=.md&file-filters%5B%5D=.py&file-filters%5B%5D=.toml&file-filters%5B%5D=.txt&file-filters%5B%5D=.yml&file-filters%5B%5D=No+extension#diff-03276a6bdd4ecdf37ab6bedf60032dd05f640e1b470e4353badc787d80ba73d5L1) + - Removed `compat.compare_digest` +- [twilio/jwt/**init**.py](https://github.com/twilio/twilio-python/pull/560/files?file-filters%5B%5D=.ini&file-filters%5B%5D=.py&file-filters%5B%5D=.yml#diff-9152dd65476e69cc34a307781d5cef195070f48da5670ed0934fd34a9ac91150L12-L16) + - Removed import for `simplejson` and `json` + +#### Updated dependencies + +- [Updated PyJWT to >=2.0.0](https://github.com/twilio/twilio-python/pull/560/files#diff-4d7c51b1efe9043e44439a949dfd92e5827321b34082903477fd04876edb7552L6) + +### CHANGED - [Remove the ability to override the `algorithm` in `Jwt.to_jwt()`](https://github.com/twilio/twilio-python/pull/560/commits/dab158f429015e0894217d6503f55b517c27c474) + +#### Removed the ability to override the algorithm while using a jwt access token + +```python +// 6.x.x +from twilio.jwt.access_token import AccessToken +token.to_jwt(algorithm='HS512') +``` + +```python +// 7.x.x +from twilio.jwt.access_token import AccessToken +token.to_jwt() +``` + +## [2017-09-28] 6.6.x to 6.7.x + +### CHANGED - `Body` parameter on Chat `Message` creation is no longer required + +#### Rationale + +This was changed to add support for sending media in Chat messages, users can now either provide a `body` or a `media_sid`. + +#### 6.6.x + +```python +from twilio.rest import Client + +client = Client('AC123', 'auth') +client.chat.v2.services('IS123').channels('CH123').messages.create("this is the body") +``` + +#### 6.7.x + +```python +from twilio.rest import Client + +client = Client('AC123', 'auth') +client.chat.v2.services('IS123').channels('CH123').messages.create(body="this is the body") +``` diff --git a/VERSIONS.md b/VERSIONS.md new file mode 100644 index 0000000000..0c2ae8d5b6 --- /dev/null +++ b/VERSIONS.md @@ -0,0 +1,35 @@ +# Versioning Strategy + +`twilio-python` uses a modified version of [Semantic Versioning][semver] for +all changes to the helper library. It is strongly encouraged that you pin at +least the major version and potentially the minor version to avoid pulling in +breaking changes. + +Semantic Versions take the form of `MAJOR.MINOR.PATCH` + +When bugs are fixed in the library in a backwards-compatible way, the `PATCH` +level will be incremented by one. When new features are added to the library +in a backwards-compatible way, the `PATCH` level will be incremented by one. +`PATCH` changes should _not_ break your code and are generally safe for upgrade. + +When a new large feature set comes online or a small breaking change is +introduced, the `MINOR` version will be incremented by one and the `PATCH` +version reset to zero. `MINOR` changes _may_ require some amount of manual code +change for upgrade. These backwards-incompatible changes will generally be +limited to a small number of function signature changes. + +The `MAJOR` version is used to indicate the family of technology represented by +the helper library. Breaking changes that require extensive reworking of code +will cause the `MAJOR` version to be incremented by one, and the `MINOR` and +`PATCH` versions will be reset to zero. Twilio understands that this can be very +disruptive, so we will only introduce this type of breaking change when +absolutely necessary. New `MAJOR` versions will be communicated in advance with +`Release Candidates` and a schedule. + +## Supported Versions + +Only the current `MAJOR` version of `twilio-python` is supported. New +features, functionality, bug fixes, and security updates will only be added to +the current `MAJOR` version. + +[semver]: https://semver.org \ No newline at end of file diff --git a/advanced-examples/custom-http-client.md b/advanced-examples/custom-http-client.md new file mode 100644 index 0000000000..b3b5a7d20e --- /dev/null +++ b/advanced-examples/custom-http-client.md @@ -0,0 +1,154 @@ +# Custom HTTP Clients for the Twilio Python Helper Library + +If you are working with the Twilio Python Helper Library, and you need to be able to modify the HTTP requests that the library makes to the Twilio servers, you’re in the right place. The most common reason for altering the HTTP request is to connect and authenticate with an enterprise’s proxy server. We’ll provide sample code that you can use in your app to handle this and other use cases. + +## Connect and authenticate with a proxy server + +To connect to a proxy server that's between your app and Twilio, you need a way to modify the HTTP requests that the Twilio helper library makes on your behalf to the Twilio REST API. + +In Python, the Twilio helper library uses the [requests](https://docs.python-requests.org/en/master/) library under the hood to make the HTTP requests, and this allows you to [provide your own `http_client`](/docs/libraries/reference/twilio-python/{{ twilio-python-version }}/docs/source/\_rst/twilio.http.html#module-twilio.http.http_client) for making API requests. + +So the question becomes: how do we apply this to a typical Twilio REST API request, such as? + +```python +client = Client(account_sid, auth_token) + +message = client.messages \ + .create( + to="+15558675310", + body="Hey there!", + from_="+15017122661" + ) + +``` + +To start, you should understand when and where a `http_client` is created and used. + +The helper library creates a default `http_client` for you whenever you call the `Client` constructor with your Twilio credentials. Here, you have the option of creating your own `http_client`, and passing to the constructor, instead of using the default implementation. + +Here’s an example of sending an SMS message with a custom client: + +```python +import os +from twilio.rest import Client +from custom_client import MyRequestClass + +from dotenv import load_dotenv +load_dotenv() + +# Custom HTTP Class +my_request_client = MyRequestClass() + +client = Client(os.getenv("ACCOUNT_SID"), os.getenv("AUTH_TOKEN"), + http_client=my_request_client) + +message = client.messages \ + .create( + to="+15558675310", + body="Hey there!", + from_="+15017122661" + ) + +print('Message SID: {}'.format(message.sid)) +``` + +## Create your custom TwilioRestClient + +When you take a closer look at the constructor for `HttpClient`, you see that the `http_client` parameter is actually of type `twilio.http.HttpClient`. + +`HttpClient` is an abstraction that allows plugging in any implementation of an HTTP client you want (or even creating a mocking layer for unit testing). + +However, within the helper library, there is an implementation of `twilio.http.HttpClient` called `TwilioHttpClient`. This class wraps the `twilio.http.HttpClient` and provides it to the Twilio helper library to make the necessary HTTP requests. + +## Call Twilio through a proxy server + +Now that we understand how all the components fit together, we can create our own `HttpClient` that can connect through a proxy server. To make this reusable, here’s a class that you can use to create this `HttpClient` whenever you need one. + +```python +import os +from requests import Request, Session, hooks +from twilio.http.http_client import TwilioHttpClient +from twilio.http.response import Response + +class MyRequestClass(TwilioHttpClient): + def __init__(self): + self.response = None + + def request(self, method, url, params=None, data=None, headers=None, auth=None, timeout=None, + allow_redirects=False): + # Here you can change the URL, headers and other request parameters + kwargs = { + 'method': method.upper(), + 'url': url, + 'params': params, + 'data': data, + 'headers': headers, + 'auth': auth, + } + + session = Session() + request = Request(**kwargs) + + prepped_request = session.prepare_request(request) + session.proxies.update({ + 'http': os.getenv('HTTP_PROXY'), + 'https': os.getenv('HTTPS_PROXY') + }) + response = session.send( + prepped_request, + allow_redirects=allow_redirects, + timeout=timeout, + ) + + return Response(int(response.status_code), response.text) +``` + +In this example, we are using some environment variables loaded at the program startup to retrieve various configuration settings: + +Your Twilio Account Sid and Auth Token ([found here, in the Twilio console](https://console.twilio.com)) + +A proxy address in the form of http://127.0.0.1:8888 + +These settings are located in an .env file, like so: + +```env +ACCOUNT_SID=ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +AUTH_TOKEN= your_auth_token + +HTTPS_PROXY=https://127.0.0.1:8888 +HTTP_PROXY=http://127.0.0.1:8888 +``` + +Here’s the full program that sends a text message and shows how it all can work together. + +```python +import os +from twilio.rest import Client +from custom_client import MyRequestClass + +from dotenv import load_dotenv +load_dotenv() + +# Custom HTTP Class +my_request_client = MyRequestClass() + +client = Client(os.getenv("ACCOUNT_SID"), os.getenv("AUTH_TOKEN"), + http_client=my_request_client) + +message = client.messages \ + .create( + to="+15558675310", + body="Hey there!", + from_="+15017122661" + ) + +print('Message SID: {}'.format(message.sid)) +``` + +## What else can this technique be used for? + +Now that you know how to inject your own `http_client` into the Twilio API request pipeline, you could use this technique to add custom HTTP headers and authorization to the requests (perhaps as required by an upstream proxy server). + +You could also implement your own `http_client` to mock the Twilio API responses so your unit and integration tests can run quickly without needing to make a connection to Twilio. In fact, there’s already an example online showing [how to do exactly that with Node.js and Prism](https://www.twilio.com/docs/openapi/mock-api-generation-with-twilio-openapi-spec). + +We can’t wait to see what you build! diff --git a/docs/Makefile b/docs/Makefile deleted file mode 100644 index 7ac5ddf107..0000000000 --- a/docs/Makefile +++ /dev/null @@ -1,131 +0,0 @@ -# Makefile for Sphinx documentation -# - -# You can set these variables from the command line. -SPHINXOPTS = -SPHINXBUILD = sphinx-build -PAPER = -BUILDDIR = _build - -# Internal variables. -PAPEROPT_a4 = -D latex_paper_size=a4 -PAPEROPT_letter = -D latex_paper_size=letter -ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . - -.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest - -help: - @echo "Please use \`make ' where is one of" - @echo " html to make standalone HTML files" - @echo " dirhtml to make HTML files named index.html in directories" - @echo " singlehtml to make a single large HTML file" - @echo " pickle to make pickle files" - @echo " json to make JSON files" - @echo " htmlhelp to make HTML files and a HTML help project" - @echo " qthelp to make HTML files and a qthelp project" - @echo " devhelp to make HTML files and a Devhelp project" - @echo " epub to make an epub" - @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" - @echo " latexpdf to make LaTeX files and run them through pdflatex" - @echo " text to make text files" - @echo " man to make manual pages" - @echo " changes to make an overview of all changed/added/deprecated items" - @echo " linkcheck to check all external links for integrity" - @echo " doctest to run all doctests embedded in the documentation (if enabled)" - -clean: - -rm -rf $(BUILDDIR)/* - -html: - pip install -r ../requirements.txt - $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." - -dirhtml: - $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml - @echo - @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." - -singlehtml: - $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml - @echo - @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." - -pickle: - $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle - @echo - @echo "Build finished; now you can process the pickle files." - -json: - $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json - @echo - @echo "Build finished; now you can process the JSON files." - -htmlhelp: - $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp - @echo - @echo "Build finished; now you can run HTML Help Workshop with the" \ - ".hhp project file in $(BUILDDIR)/htmlhelp." - -qthelp: - $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp - @echo - @echo "Build finished; now you can run "qcollectiongenerator" with the" \ - ".qhcp project file in $(BUILDDIR)/qthelp, like this:" - @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/twilio-python2.qhcp" - @echo "To view the help file:" - @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/twilio-python2.qhc" - -devhelp: - $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp - @echo - @echo "Build finished." - @echo "To view the help file:" - @echo "# mkdir -p $$HOME/.local/share/devhelp/twilio-python2" - @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/twilio-python2" - @echo "# devhelp" - -epub: - $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub - @echo - @echo "Build finished. The epub file is in $(BUILDDIR)/epub." - -latex: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo - @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." - @echo "Run \`make' in that directory to run these through (pdf)latex" \ - "(use \`make latexpdf' here to do that automatically)." - -latexpdf: - $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex - @echo "Running LaTeX files through pdflatex..." - make -C $(BUILDDIR)/latex all-pdf - @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." - -text: - $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text - @echo - @echo "Build finished. The text files are in $(BUILDDIR)/text." - -man: - $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man - @echo - @echo "Build finished. The manual pages are in $(BUILDDIR)/man." - -changes: - $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes - @echo - @echo "The overview file is in $(BUILDDIR)/changes." - -linkcheck: - $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck - @echo - @echo "Link check complete; look for any errors in the above output " \ - "or in $(BUILDDIR)/linkcheck/output.txt." - -doctest: - $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest - @echo "Testing of doctests in the sources finished, look at the " \ - "results in $(BUILDDIR)/doctest/output.txt." diff --git a/docs/_themes/.gitignore b/docs/_themes/.gitignore deleted file mode 100644 index 66b6e4c2f3..0000000000 --- a/docs/_themes/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -*.pyc -*.pyo -.DS_Store diff --git a/docs/_themes/LICENSE b/docs/_themes/LICENSE deleted file mode 100644 index b160a8eeb8..0000000000 --- a/docs/_themes/LICENSE +++ /dev/null @@ -1,45 +0,0 @@ -Modifications: - -Copyright (c) 2011 Kenneth Reitz. - - -Original Project: - -Copyright (c) 2010 by Armin Ronacher. - - -Some rights reserved. - -Redistribution and use in source and binary forms of the theme, with or -without modification, are permitted provided that the following conditions -are met: - -* Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials provided - with the distribution. - -* The names of the contributors may not be used to endorse or - promote products derived from this software without specific - prior written permission. - -We kindly ask you to only use these themes in an unmodified manner just -for Flask and Flask-related products, not for unrelated projects. If you -like the visual style and want to use it for your own projects, please -consider making some larger changes to the themes (such as changing -font faces, sizes, colors or margins). - -THIS THEME IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS THEME, EVEN IF ADVISED OF THE -POSSIBILITY OF SUCH DAMAGE. diff --git a/docs/_themes/README.rst b/docs/_themes/README.rst deleted file mode 100644 index 8648482a31..0000000000 --- a/docs/_themes/README.rst +++ /dev/null @@ -1,25 +0,0 @@ -krTheme Sphinx Style -==================== - -This repository contains sphinx styles Kenneth Reitz uses in most of -his projects. It is a drivative of Mitsuhiko's themes for Flask and Flask related -projects. To use this style in your Sphinx documentation, follow -this guide: - -1. put this folder as _themes into your docs folder. Alternatively - you can also use git submodules to check out the contents there. - -2. add this to your conf.py: :: - - sys.path.append(os.path.abspath('_themes')) - html_theme_path = ['_themes'] - html_theme = 'flask' - -The following themes exist: - -**kr** - the standard flask documentation theme for large projects - -**kr_small** - small one-page theme. Intended to be used by very small addon libraries. - diff --git a/docs/_themes/flask_theme_support.py b/docs/_themes/flask_theme_support.py deleted file mode 100644 index 33f47449c1..0000000000 --- a/docs/_themes/flask_theme_support.py +++ /dev/null @@ -1,86 +0,0 @@ -# flasky extensions. flasky pygments style based on tango style -from pygments.style import Style -from pygments.token import Keyword, Name, Comment, String, Error, \ - Number, Operator, Generic, Whitespace, Punctuation, Other, Literal - - -class FlaskyStyle(Style): - background_color = "#f8f8f8" - default_style = "" - - styles = { - # No corresponding class for the following: - #Text: "", # class: '' - Whitespace: "underline #f8f8f8", # class: 'w' - Error: "#a40000 border:#ef2929", # class: 'err' - Other: "#000000", # class 'x' - - Comment: "italic #8f5902", # class: 'c' - Comment.Preproc: "noitalic", # class: 'cp' - - Keyword: "bold #004461", # class: 'k' - Keyword.Constant: "bold #004461", # class: 'kc' - Keyword.Declaration: "bold #004461", # class: 'kd' - Keyword.Namespace: "bold #004461", # class: 'kn' - Keyword.Pseudo: "bold #004461", # class: 'kp' - Keyword.Reserved: "bold #004461", # class: 'kr' - Keyword.Type: "bold #004461", # class: 'kt' - - Operator: "#582800", # class: 'o' - Operator.Word: "bold #004461", # class: 'ow' - like keywords - - Punctuation: "bold #000000", # class: 'p' - - # because special names such as Name.Class, Name.Function, etc. - # are not recognized as such later in the parsing, we choose them - # to look the same as ordinary variables. - Name: "#000000", # class: 'n' - Name.Attribute: "#c4a000", # class: 'na' - to be revised - Name.Builtin: "#004461", # class: 'nb' - Name.Builtin.Pseudo: "#3465a4", # class: 'bp' - Name.Class: "#000000", # class: 'nc' - to be revised - Name.Constant: "#000000", # class: 'no' - to be revised - Name.Decorator: "#888", # class: 'nd' - to be revised - Name.Entity: "#ce5c00", # class: 'ni' - Name.Exception: "bold #cc0000", # class: 'ne' - Name.Function: "#000000", # class: 'nf' - Name.Property: "#000000", # class: 'py' - Name.Label: "#f57900", # class: 'nl' - Name.Namespace: "#000000", # class: 'nn' - to be revised - Name.Other: "#000000", # class: 'nx' - Name.Tag: "bold #004461", # class: 'nt' - like a keyword - Name.Variable: "#000000", # class: 'nv' - to be revised - Name.Variable.Class: "#000000", # class: 'vc' - to be revised - Name.Variable.Global: "#000000", # class: 'vg' - to be revised - Name.Variable.Instance: "#000000", # class: 'vi' - to be revised - - Number: "#990000", # class: 'm' - - Literal: "#000000", # class: 'l' - Literal.Date: "#000000", # class: 'ld' - - String: "#4e9a06", # class: 's' - String.Backtick: "#4e9a06", # class: 'sb' - String.Char: "#4e9a06", # class: 'sc' - String.Doc: "italic #8f5902", # class: 'sd' - like a comment - String.Double: "#4e9a06", # class: 's2' - String.Escape: "#4e9a06", # class: 'se' - String.Heredoc: "#4e9a06", # class: 'sh' - String.Interpol: "#4e9a06", # class: 'si' - String.Other: "#4e9a06", # class: 'sx' - String.Regex: "#4e9a06", # class: 'sr' - String.Single: "#4e9a06", # class: 's1' - String.Symbol: "#4e9a06", # class: 'ss' - - Generic: "#000000", # class: 'g' - Generic.Deleted: "#a40000", # class: 'gd' - Generic.Emph: "italic #000000", # class: 'ge' - Generic.Error: "#ef2929", # class: 'gr' - Generic.Heading: "bold #000080", # class: 'gh' - Generic.Inserted: "#00A000", # class: 'gi' - Generic.Output: "#888", # class: 'go' - Generic.Prompt: "#745334", # class: 'gp' - Generic.Strong: "bold #000000", # class: 'gs' - Generic.Subheading: "bold #800080", # class: 'gu' - Generic.Traceback: "bold #a40000", # class: 'gt' - } diff --git a/docs/_themes/kr/layout.html b/docs/_themes/kr/layout.html deleted file mode 100644 index 7a60424f6b..0000000000 --- a/docs/_themes/kr/layout.html +++ /dev/null @@ -1,32 +0,0 @@ -{%- extends "basic/layout.html" %} -{%- block extrahead %} - {{ super() }} - {% if theme_touch_icon %} - - {% endif %} - -{% endblock %} -{%- block relbar2 %}{% endblock %} -{%- block footer %} -

- - Fork me on GitHub - - - -{%- endblock %} diff --git a/docs/_themes/kr/relations.html b/docs/_themes/kr/relations.html deleted file mode 100644 index 3bbcde85bb..0000000000 --- a/docs/_themes/kr/relations.html +++ /dev/null @@ -1,19 +0,0 @@ -

Related Topics

- diff --git a/docs/_themes/kr/static/flasky.css_t b/docs/_themes/kr/static/flasky.css_t deleted file mode 100644 index aa3e8ebbd9..0000000000 --- a/docs/_themes/kr/static/flasky.css_t +++ /dev/null @@ -1,469 +0,0 @@ -/* - * flasky.css_t - * ~~~~~~~~~~~~ - * - * :copyright: Copyright 2010 by Armin Ronacher. Modifications by Kenneth Reitz. - * :license: Flask Design License, see LICENSE for details. - */ - -{% set page_width = '940px' %} -{% set sidebar_width = '220px' %} - -@import url("basic.css"); - -/* -- page layout ----------------------------------------------------------- */ - -body { - font-family: 'goudy old style', 'minion pro', 'bell mt', Georgia, 'Hiragino Mincho Pro'; - font-size: 17px; - background-color: white; - color: #000; - margin: 0; - padding: 0; -} - -div.document { - width: {{ page_width }}; - margin: 30px auto 0 auto; -} - -div.documentwrapper { - float: left; - width: 100%; -} - -div.bodywrapper { - margin: 0 0 0 {{ sidebar_width }}; -} - -div.sphinxsidebar { - width: {{ sidebar_width }}; -} - -hr { - border: 1px solid #B1B4B6; -} - -div.body { - background-color: #ffffff; - color: #3E4349; - padding: 0 30px 0 30px; -} - -img.floatingflask { - padding: 0 0 10px 10px; - float: right; -} - -div.footer { - width: {{ page_width }}; - margin: 20px auto 30px auto; - font-size: 14px; - color: #888; - text-align: right; -} - -div.footer a { - color: #888; -} - -div.related { - display: none; -} - -div.sphinxsidebar a { - color: #444; - text-decoration: none; - border-bottom: 1px dotted #999; -} - -div.sphinxsidebar a:hover { - border-bottom: 1px solid #999; -} - -div.sphinxsidebar { - font-size: 14px; - line-height: 1.5; -} - -div.sphinxsidebarwrapper { - padding: 18px 10px; -} - -div.sphinxsidebarwrapper p.logo { - padding: 0; - margin: -10px 0 0 -20px; - text-align: center; -} - -div.sphinxsidebar h3, -div.sphinxsidebar h4 { - font-family: 'Garamond', 'Georgia', serif; - color: #444; - font-size: 24px; - font-weight: normal; - margin: 0 0 5px 0; - padding: 0; -} - -div.sphinxsidebar h4 { - font-size: 20px; -} - -div.sphinxsidebar h3 a { - color: #444; -} - -div.sphinxsidebar p.logo a, -div.sphinxsidebar h3 a, -div.sphinxsidebar p.logo a:hover, -div.sphinxsidebar h3 a:hover { - border: none; -} - -div.sphinxsidebar p { - color: #555; - margin: 10px 0; -} - -div.sphinxsidebar ul { - margin: 10px 0; - padding: 0; - color: #000; -} - -div.sphinxsidebar input { - border: 1px solid #ccc; - font-family: 'Georgia', serif; - font-size: 1em; -} - -/* -- body styles ----------------------------------------------------------- */ - -a { - color: #004B6B; - text-decoration: underline; -} - -a:hover { - color: #6D4100; - text-decoration: underline; -} - -div.body h1, -div.body h2, -div.body h3, -div.body h4, -div.body h5, -div.body h6 { - font-family: 'Garamond', 'Georgia', serif; - font-weight: normal; - margin: 30px 0px 10px 0px; - padding: 0; -} - -div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; } -div.body h2 { font-size: 180%; } -div.body h3 { font-size: 150%; } -div.body h4 { font-size: 130%; } -div.body h5 { font-size: 100%; } -div.body h6 { font-size: 100%; } - -a.headerlink { - color: #ddd; - padding: 0 4px; - text-decoration: none; -} - -a.headerlink:hover { - color: #444; - background: #eaeaea; -} - -div.body p, div.body dd, div.body li { - line-height: 1.4em; -} - -div.admonition { - background: #fafafa; - margin: 20px -30px; - padding: 10px 30px; - border-top: 1px solid #ccc; - border-bottom: 1px solid #ccc; -} - -div.admonition tt.xref, div.admonition a tt { - border-bottom: 1px solid #fafafa; -} - -dd div.admonition { - margin-left: -60px; - padding-left: 60px; -} - -div.admonition p.admonition-title { - font-family: 'Garamond', 'Georgia', serif; - font-weight: normal; - font-size: 24px; - margin: 0 0 10px 0; - padding: 0; - line-height: 1; -} - -div.admonition p.last { - margin-bottom: 0; -} - -div.highlight { - background-color: white; -} - -dt:target, .highlight { - background: #FAF3E8; -} - -div.note { - background-color: #eee; - border: 1px solid #ccc; -} - -div.seealso { - background-color: #ffc; - border: 1px solid #ff6; -} - -div.topic { - background-color: #eee; -} - -p.admonition-title { - display: inline; -} - -p.admonition-title:after { - content: ":"; -} - -pre, tt { - font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace; - font-size: 0.9em; -} - -img.screenshot { -} - -tt.descname, tt.descclassname { - font-size: 0.95em; -} - -tt.descname { - padding-right: 0.08em; -} - -img.screenshot { - -moz-box-shadow: 2px 2px 4px #eee; - -webkit-box-shadow: 2px 2px 4px #eee; - box-shadow: 2px 2px 4px #eee; -} - -table.docutils { - border: 1px solid #888; - -moz-box-shadow: 2px 2px 4px #eee; - -webkit-box-shadow: 2px 2px 4px #eee; - box-shadow: 2px 2px 4px #eee; -} - -table.docutils td, table.docutils th { - border: 1px solid #888; - padding: 0.25em 0.7em; -} - -table.field-list, table.footnote { - border: none; - -moz-box-shadow: none; - -webkit-box-shadow: none; - box-shadow: none; -} - -table.footnote { - margin: 15px 0; - width: 100%; - border: 1px solid #eee; - background: #fdfdfd; - font-size: 0.9em; -} - -table.footnote + table.footnote { - margin-top: -15px; - border-top: none; -} - -table.field-list th { - padding: 0 0.8em 0 0; -} - -table.field-list td { - padding: 0; -} - -table.footnote td.label { - width: 0px; - padding: 0.3em 0 0.3em 0.5em; -} - -table.footnote td { - padding: 0.3em 0.5em; -} - -dl { - margin: 0; - padding: 0; -} - -dl dd { - margin-left: 30px; -} - -blockquote { - margin: 0 0 0 30px; - padding: 0; -} - -ul, ol { - margin: 10px 0 10px 30px; - padding: 0; -} - -pre { - background: #eee; - padding: 7px 30px; - margin: 15px -30px; - line-height: 1.3em; -} - -dl pre, blockquote pre, li pre { - margin-left: -60px; - padding-left: 60px; -} - -dl dl pre { - margin-left: -90px; - padding-left: 90px; -} - -tt { - background-color: #ecf0f3; - color: #222; - /* padding: 1px 2px; */ -} - -tt.xref, a tt { - background-color: #FBFBFB; - border-bottom: 1px solid white; -} - -a.reference { - text-decoration: none; - border-bottom: 1px dotted #004B6B; -} - -a.reference:hover { - border-bottom: 1px solid #6D4100; -} - -a.footnote-reference { - text-decoration: none; - font-size: 0.7em; - vertical-align: top; - border-bottom: 1px dotted #004B6B; -} - -a.footnote-reference:hover { - border-bottom: 1px solid #6D4100; -} - -a:hover tt { - background: #EEE; -} - - -@media screen and (max-width: 600px) { - - div.sphinxsidebar { - display: none; - } - - div.documentwrapper { - margin-left: 0; - margin-top: 0; - margin-right: 0; - margin-bottom: 0; - } - - div.bodywrapper { - margin-top: 0; - margin-right: 0; - margin-bottom: 0; - margin-left: 0; - } - - ul { - margin-left: 0; - } - - .document { - width: auto; - } - - .bodywrapper { - margin: 0; - } - - .footer { - width: auto; - } - - - -} - - -/* scrollbars */ - -::-webkit-scrollbar { - width: 6px; - height: 6px; -} - -::-webkit-scrollbar-button:start:decrement, -::-webkit-scrollbar-button:end:increment { - display: block; - height: 10px; -} - -::-webkit-scrollbar-button:vertical:increment { - background-color: #fff; -} - -::-webkit-scrollbar-track-piece { - background-color: #eee; - -webkit-border-radius: 3px; -} - -::-webkit-scrollbar-thumb:vertical { - height: 50px; - background-color: #ccc; - -webkit-border-radius: 3px; -} - -::-webkit-scrollbar-thumb:horizontal { - width: 50px; - background-color: #ccc; - -webkit-border-radius: 3px; -} - -/* misc. */ - -.revsys-inline { - display: none!important; -} \ No newline at end of file diff --git a/docs/_themes/kr/static/small_flask.css b/docs/_themes/kr/static/small_flask.css deleted file mode 100644 index 1c6df309ed..0000000000 --- a/docs/_themes/kr/static/small_flask.css +++ /dev/null @@ -1,70 +0,0 @@ -/* - * small_flask.css_t - * ~~~~~~~~~~~~~~~~~ - * - * :copyright: Copyright 2010 by Armin Ronacher. - * :license: Flask Design License, see LICENSE for details. - */ - -body { - margin: 0; - padding: 20px 30px; -} - -div.documentwrapper { - float: none; - background: white; -} - -div.sphinxsidebar { - display: block; - float: none; - width: 102.5%; - margin: 50px -30px -20px -30px; - padding: 10px 20px; - background: #333; - color: white; -} - -div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p, -div.sphinxsidebar h3 a { - color: white; -} - -div.sphinxsidebar a { - color: #aaa; -} - -div.sphinxsidebar p.logo { - display: none; -} - -div.document { - width: 100%; - margin: 0; -} - -div.related { - display: block; - margin: 0; - padding: 10px 0 20px 0; -} - -div.related ul, -div.related ul li { - margin: 0; - padding: 0; -} - -div.footer { - display: none; -} - -div.bodywrapper { - margin: 0; -} - -div.body { - min-height: 0; - padding: 0; -} diff --git a/docs/_themes/kr/theme.conf b/docs/_themes/kr/theme.conf deleted file mode 100644 index 307a1f0d65..0000000000 --- a/docs/_themes/kr/theme.conf +++ /dev/null @@ -1,7 +0,0 @@ -[theme] -inherit = basic -stylesheet = flasky.css -pygments_style = flask_theme_support.FlaskyStyle - -[options] -touch_icon = diff --git a/docs/_themes/kr_small/layout.html b/docs/_themes/kr_small/layout.html deleted file mode 100644 index aa1716aaff..0000000000 --- a/docs/_themes/kr_small/layout.html +++ /dev/null @@ -1,22 +0,0 @@ -{% extends "basic/layout.html" %} -{% block header %} - {{ super() }} - {% if pagename == 'index' %} -
- {% endif %} -{% endblock %} -{% block footer %} - {% if pagename == 'index' %} -
- {% endif %} -{% endblock %} -{# do not display relbars #} -{% block relbar1 %}{% endblock %} -{% block relbar2 %} - {% if theme_github_fork %} - Fork me on GitHub - {% endif %} -{% endblock %} -{% block sidebar1 %}{% endblock %} -{% block sidebar2 %}{% endblock %} diff --git a/docs/_themes/kr_small/static/flasky.css_t b/docs/_themes/kr_small/static/flasky.css_t deleted file mode 100644 index fe2141c565..0000000000 --- a/docs/_themes/kr_small/static/flasky.css_t +++ /dev/null @@ -1,287 +0,0 @@ -/* - * flasky.css_t - * ~~~~~~~~~~~~ - * - * Sphinx stylesheet -- flasky theme based on nature theme. - * - * :copyright: Copyright 2007-2010 by the Sphinx team, see AUTHORS. - * :license: BSD, see LICENSE for details. - * - */ - -@import url("basic.css"); - -/* -- page layout ----------------------------------------------------------- */ - -body { - font-family: 'Georgia', serif; - font-size: 17px; - color: #000; - background: white; - margin: 0; - padding: 0; -} - -div.documentwrapper { - float: left; - width: 100%; -} - -div.bodywrapper { - margin: 40px auto 0 auto; - width: 700px; -} - -hr { - border: 1px solid #B1B4B6; -} - -div.body { - background-color: #ffffff; - color: #3E4349; - padding: 0 30px 30px 30px; -} - -img.floatingflask { - padding: 0 0 10px 10px; - float: right; -} - -div.footer { - text-align: right; - color: #888; - padding: 10px; - font-size: 14px; - width: 650px; - margin: 0 auto 40px auto; -} - -div.footer a { - color: #888; - text-decoration: underline; -} - -div.related { - line-height: 32px; - color: #888; -} - -div.related ul { - padding: 0 0 0 10px; -} - -div.related a { - color: #444; -} - -/* -- body styles ----------------------------------------------------------- */ - -a { - color: #004B6B; - text-decoration: underline; -} - -a:hover { - color: #6D4100; - text-decoration: underline; -} - -div.body { - padding-bottom: 40px; /* saved for footer */ -} - -div.body h1, -div.body h2, -div.body h3, -div.body h4, -div.body h5, -div.body h6 { - font-family: 'Garamond', 'Georgia', serif; - font-weight: normal; - margin: 30px 0px 10px 0px; - padding: 0; -} - -{% if theme_index_logo %} -div.indexwrapper h1 { - text-indent: -999999px; - background: url({{ theme_index_logo }}) no-repeat center center; - height: {{ theme_index_logo_height }}; -} -{% endif %} - -div.body h2 { font-size: 180%; } -div.body h3 { font-size: 150%; } -div.body h4 { font-size: 130%; } -div.body h5 { font-size: 100%; } -div.body h6 { font-size: 100%; } - -a.headerlink { - color: white; - padding: 0 4px; - text-decoration: none; -} - -a.headerlink:hover { - color: #444; - background: #eaeaea; -} - -div.body p, div.body dd, div.body li { - line-height: 1.4em; -} - -div.admonition { - background: #fafafa; - margin: 20px -30px; - padding: 10px 30px; - border-top: 1px solid #ccc; - border-bottom: 1px solid #ccc; -} - -div.admonition p.admonition-title { - font-family: 'Garamond', 'Georgia', serif; - font-weight: normal; - font-size: 24px; - margin: 0 0 10px 0; - padding: 0; - line-height: 1; -} - -div.admonition p.last { - margin-bottom: 0; -} - -div.highlight{ - background-color: white; -} - -dt:target, .highlight { - background: #FAF3E8; -} - -div.note { - background-color: #eee; - border: 1px solid #ccc; -} - -div.seealso { - background-color: #ffc; - border: 1px solid #ff6; -} - -div.topic { - background-color: #eee; -} - -div.warning { - background-color: #ffe4e4; - border: 1px solid #f66; -} - -p.admonition-title { - display: inline; -} - -p.admonition-title:after { - content: ":"; -} - -pre, tt { - font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace; - font-size: 0.85em; -} - -img.screenshot { -} - -tt.descname, tt.descclassname { - font-size: 0.95em; -} - -tt.descname { - padding-right: 0.08em; -} - -img.screenshot { - -moz-box-shadow: 2px 2px 4px #eee; - -webkit-box-shadow: 2px 2px 4px #eee; - box-shadow: 2px 2px 4px #eee; -} - -table.docutils { - border: 1px solid #888; - -moz-box-shadow: 2px 2px 4px #eee; - -webkit-box-shadow: 2px 2px 4px #eee; - box-shadow: 2px 2px 4px #eee; -} - -table.docutils td, table.docutils th { - border: 1px solid #888; - padding: 0.25em 0.7em; -} - -table.field-list, table.footnote { - border: none; - -moz-box-shadow: none; - -webkit-box-shadow: none; - box-shadow: none; -} - -table.footnote { - margin: 15px 0; - width: 100%; - border: 1px solid #eee; -} - -table.field-list th { - padding: 0 0.8em 0 0; -} - -table.field-list td { - padding: 0; -} - -table.footnote td { - padding: 0.5em; -} - -dl { - margin: 0; - padding: 0; -} - -dl dd { - margin-left: 30px; -} - -pre { - padding: 0; - margin: 15px -30px; - padding: 8px; - line-height: 1.3em; - padding: 7px 30px; - background: #eee; - border-radius: 2px; - -moz-border-radius: 2px; - -webkit-border-radius: 2px; -} - -dl pre { - margin-left: -60px; - padding-left: 60px; -} - -tt { - background-color: #ecf0f3; - color: #222; - /* padding: 1px 2px; */ -} - -tt.xref, a tt { - background-color: #FBFBFB; -} - -a:hover tt { - background: #EEE; -} diff --git a/docs/_themes/kr_small/theme.conf b/docs/_themes/kr_small/theme.conf deleted file mode 100644 index 542b462515..0000000000 --- a/docs/_themes/kr_small/theme.conf +++ /dev/null @@ -1,10 +0,0 @@ -[theme] -inherit = basic -stylesheet = flasky.css -nosidebar = true -pygments_style = flask_theme_support.FlaskyStyle - -[options] -index_logo = '' -index_logo_height = 120px -github_fork = '' diff --git a/docs/api.rst b/docs/api.rst deleted file mode 100644 index d666b98339..0000000000 --- a/docs/api.rst +++ /dev/null @@ -1,14 +0,0 @@ -================= -API Documentation -================= - -A complete API reference to the :data:`twilio` module. - -.. toctree:: - :maxdepth: 1 - - api/rest/index - api/rest/resources - api/twiml - api/util - diff --git a/docs/api/rest/index.rst b/docs/api/rest/index.rst deleted file mode 100644 index 1da96a859e..0000000000 --- a/docs/api/rest/index.rst +++ /dev/null @@ -1,10 +0,0 @@ -.. module:: twilio.rest - -============================== -:mod:`twilio.rest` -============================== - -.. autoclass:: TwilioRestClient - :members: - :inherited-members: - diff --git a/docs/api/rest/resources.rst b/docs/api/rest/resources.rst deleted file mode 100644 index f58e12a345..0000000000 --- a/docs/api/rest/resources.rst +++ /dev/null @@ -1,952 +0,0 @@ -.. module:: twilio.rest.resources - -============================= -:mod:`twilio.rest.resources` -============================= - -.. autoclass:: ListResource - :members: count, get, iter - -Accounts ->>>>>>>>> - -.. autoclass:: Accounts - :members: - :exclude-members: instance - -.. autoclass:: Account - :members: - - .. attribute:: sid - - A 34 character string that uniquely identifies this account. - - .. attribute:: date_created - - The date that this account was created, in GMT in RFC 2822 format - - .. attribute:: date_updated - - The date that this account was last updated, in GMT in RFC 2822 format. - - .. attribute:: friendly_name - - A human readable description of this account, up to 64 characters long. By default the FriendlyName is your email address. - - .. attribute:: status - - The status of this account. Usually active, but can be suspended if you've been bad, or closed if you've been horrible. - - .. attribute:: auth_token - - The authorization token for this account. This token should be kept a secret, so no sharing. - - -Applications ->>>>>>>>>>>>>>> - -.. autoclass:: Applications - :members: - :exclude-members: instance - -.. autoclass:: Application - :members: - - .. attribute:: sid - - A 34 character string that uniquely identifies this application. - - .. attribute:: date_created - - The date that this application was created, in GMT in RFC 2822 format - - .. attribute:: date_updated - - The date that this application was last updated, in GMT in RFC 2822 format. - - .. attribute:: friendly_name - - A human readable description of this application, up to 64 characters long. By default the FriendlyName is your email address. - - .. attribute:: status - - The status of this account. Usually active, but can be suspended if you've been bad, or closed if you've been horrible. - - .. attribute:: api_version - - Requests to this application will start a new TwiML session with this API version. - - .. attribute:: voice_url - - URL Twilio will request when a phone number assigned to this application receives a call. - - .. attribute:: voice_method - - The HTTP method Twilio will use when requesting the above Url. Either GET or POST. - - .. attribute:: voice_fallback_url - - The URL that Twilio will request if an error occurs retrieving or executing the TwiML requested by Url. - - .. attribute:: voice_fallback_method - - The HTTP method Twilio will use when requesting the VoiceFallbackUrl. Either GET or POST. - - .. attribute:: status_callback - - The URL that Twilio will request to pass status parameters (such as call ended) to your application. - - .. attribute:: status_callback_method - - The HTTP method Twilio will use to make requests to the StatusCallback URL. Either GET or POST. - - .. attribute:: voice_caller_id_lookup - - Look up the caller's caller-ID name from the CNAM database (additional charges apply). Either true or false. - - .. attribute:: sms_url - - The URL Twilio will request when a phone number assigned to this application receives an incoming SMS message. - - .. attribute:: sms_method - - The HTTP method Twilio will use when making requests to the SmsUrl. Either GET or POST. - - .. attribute:: sms_fallback_url - - The URL that Twilio will request if an error occurs retrieving or executing the TwiML from SmsUrl. - - .. attribute:: sms_fallback_method - - The HTTP method Twilio will use when requesting the above URL. Either GET or POST. - - .. attribute:: sms_status_callback - - Twilio will make a POST request to this URL to pass status parameters (such as sent or failed) to your application if you specify this application's Sid as the ApplicationSid on an outgoing SMS request. - - .. attribute:: uri - - The URI for this resource, relative to https://api.twilio.com - - -Calls ->>>>>> - -.. autoclass:: twilio.rest.resources.Calls - :members: - :exclude-members: instance - -.. autoclass:: twilio.rest.resources.Call - :members: - - .. attribute:: sid - - A 34 character string that uniquely identifies this resource. - - .. attribute:: parent_call_sid - - A 34 character string that uniquely identifies the call that created this leg. - - .. attribute:: date_created - - The date that this resource was created, given as GMT in RFC 2822 format. - - .. attribute:: date_updated - - The date that this resource was last updated, given as GMT in RFC 2822 format. - - .. attribute:: account_sid - - The unique id of the Account responsible for creating this call. - - .. attribute:: to - - The phone number that received this call. e.g., +16175551212 (E.164 format) - - .. attribute:: from_ - - The phone number that made this call. e.g., +16175551212 (E.164 format) - - .. attribute:: phone_number_sid - - If the call was inbound, this is the Sid of the IncomingPhoneNumber that received the call. If the call was outbound, it is the Sid of the OutgoingCallerId from which the call was placed. - - .. attribute:: status - - A string representing the status of the call. May be :data:`QUEUED`, :data:`RINGING`, :data:`IN-PROGRESS`, :data:`COMPLETED`, :data:`FAILED`, :data:`BUSY` or :data:`NO_ANSWER`. - - .. attribute:: start_time - - The start time of the call, given as GMT in RFC 2822 format. Empty if the call has not yet been dialed. - - .. attribute:: end_time - - The end time of the call, given as GMT in RFC 2822 format. Empty if the call did not complete successfully. - - .. attribute:: duration - - The length of the call in seconds. This value is empty for busy, failed, unanswered or ongoing calls. - - .. attribute:: price - - The charge for this call in USD. Populated after the call is completed. May not be immediately available. - - .. attribute:: direction - - A string describing the direction of the call. inbound for inbound calls, outbound-api for calls initiated via the REST API or outbound-dial for calls initiated by a verb. - - .. attribute:: answered_by - - If this call was initiated with answering machine detection, either human or machine. Empty otherwise. - - .. attribute:: forwarded_from - - If this call was an incoming call forwarded from another number, the forwarding phone number (depends on carrier supporting forwarding). Empty otherwise. - - .. attribute:: caller_name - - If this call was an incoming call from a phone number with Caller ID Lookup enabled, the caller's name. Empty otherwise. - -Caller Ids ->>>>>>>>>>> - -.. autoclass:: twilio.rest.resources.CallerIds - :members: - :exclude-members: instance - -.. autoclass:: twilio.rest.resources.CallerId - :members: - - .. attribute:: sid - - A 34 character string that uniquely identifies this resource. - - .. attribute:: date_created - - The date that this resource was created, given in RFC 2822 format. - - .. attribute:: date_updated - - The date that this resource was last updated, given in RFC 2822 format. - - .. attribute:: friendly_name - - A human readable descriptive text for this resource, up to 64 characters long. By default, the FriendlyName is a nicely formatted version of the phone number. - - .. attribute:: account_sid - - The unique id of the Account responsible for this Caller Id. - - .. attribute:: phone_number - - The incoming phone number. Formatted with a '+' and country code e.g., +16175551212 (E.164 format). - - .. attribute:: uri - - The URI for this resource, relative to https://api.twilio.com. - -Conferences ->>>>>>>>>>>> - -.. autoclass:: twilio.rest.resources.Conferences - :members: - :exclude-members: instance - -.. autoclass:: twilio.rest.resources.Conference - :members: - - .. attribute:: sid - - A 34 character string that uniquely identifies this conference. - - .. attribute:: friendly_name - - A user provided string that identifies this conference room. - - .. attribute:: status - - A string representing the status of the conference. May be init, in-progress, or completed. - - .. attribute:: date_created - - The date that this conference was created, given as GMT in RFC 2822 format. - - .. attribute:: date_updated - - The date that this conference was last updated, given as GMT in RFC 2822 format. - - .. attribute:: account_sid - - The unique id of the Account responsible for creating this conference. - - .. attribute:: uri - - The URI for this resource, relative to https://api.twilio.com. - - .. attribute:: participants - - The :class:`Participants` resource, listing people currently in this conference - - -Connect Apps ->>>>>>>>>>>>>> - -.. autoclass:: twilio.rest.resources.ConnectApps - :members: - :exclude-members: instance - -.. autoclass:: twilio.rest.resources.ConnectApp - :members: - - .. attribute:: sid - - A 34 character string that uniquely identifies this resource. - - .. attribute:: date_created - - The date that this resource was created, given as GMT in RFC 2822 format. - - .. attribute:: date_updated - - The date that this resource was last updated, given as GMT in RFC 2822 format. - - .. attribute:: account_sid - - The unique id of the Account responsible for creating this call. - - .. attribute:: permissions - - The list of permissions that your ConnectApp requests. - - .. attribute:: friendly_name - - A human readable name for this resource. - - .. attribute:: description - - A more detailed human readable description of this resource. - - .. attribute:: company_name - - The company name set for this Connect App. - - .. attribute:: homepage_url - - The public URL where users can obtain more information about this Connect App. - - .. attribute:: authorize_redirect_url - - The URL the user's browser will redirect to after Twilio authenticates the - user and obtains authorization for this Connect App. - - .. attribute:: deauthorize_callback_url - - The URL to which Twilio will send a request when a user de-authorizes this - Connect App. - - .. attribute:: deauthorize_callback_method - - The HTTP method to be used when making a request to the deauthorize - callback url. - - .. attribute:: uri - - The URI for this resource, relative to https://api.twilio.com. - - -Notifications ->>>>>>>>>>>>>> - -.. autoclass:: twilio.rest.resources.Notifications - :members: - :exclude-members: instance - -.. autoclass:: twilio.rest.resources.Notification - :members: - - .. attribute:: sid - - A 34 character string that uniquely identifies this resource. - - .. attribute:: date_created - - The date that this resource was created, given in RFC 2822 format. - - .. attribute:: date_updated - - The date that this resource was last updated, given in RFC 2822 format. - - .. attribute:: account_sid - - The unique id of the Account responsible for this notification. - - .. attribute:: call_sid - - CallSid is the unique id of the call during which the notification was generated. Empty if the notification was generated by the REST API without regard to a specific phone call. - - .. attribute:: api_version - - The version of the Twilio in use when this notification was generated. - - .. attribute:: log - - An integer log level corresponding to the type of notification: 0 is ERROR, 1 is WARNING. - - .. attribute:: error_code - - A unique error code for the error condition. You can lookup errors, with possible causes and solutions, in our Error Dictionary. - - .. attribute:: more_info - - A URL for more information about the error condition. The URL is a page in our Error Dictionary. - - .. attribute:: message_text - - The text of the notification. - - .. attribute:: message_date - - The date the notification was actually generated, given in RFC 2822 format. Due to buffering, this may be slightly different than the DateCreated date. - - .. attribute:: request_url - - The URL of the resource that generated the notification. If the notification was generated during a phone call: This is the URL of the resource on YOUR SERVER that caused the notification. If the notification was generated by your use of the REST API: This is the URL of the REST resource you were attempting to request on Twilio's servers. - - .. attribute:: request_method - - The HTTP method in use for the request that generated the notification. If the notification was generated during a phone call: The HTTP Method use to request the resource on your server. If the notification was generated by your use of the REST API: This is the HTTP method used in your request to the REST resource on Twilio's servers. - - .. attribute:: request_variables - - The Twilio-generated HTTP GET or POST variables sent to your server. Alternatively, if the notification was generated by the REST API, this field will include any HTTP POST or PUT variables you sent to the REST API. - - .. attribute:: response_headers - - The HTTP headers returned by your server. - - .. attribute:: response_body - - The HTTP body returned by your server. - - .. attribute:: uri - - The URI for this resource, relative to https://api.twilio.com - -Participlants ->>>>>>>>>>>>>> - -.. autoclass:: twilio.rest.resources.Participants - :members: - :exclude-members: instance - -.. autoclass:: twilio.rest.resources.Participant - :members: - - .. attribute:: call_sid - - A 34 character string that uniquely identifies the call that is connected to this conference - - .. attribute:: conference_sid - - A 34 character string that identifies the conference this participant is in - - .. attribute:: date_created - - The date that this resource was created, given in RFC 2822 format. - - .. attribute:: date_updated - - The date that this resource was last updated, given in RFC 2822 format. - - .. attribute:: account_sid - - The unique id of the Account that created this conference - - .. attribute:: muted - - true if this participant is currently muted. false otherwise. - - .. attribute:: start_conference_on_enter - - Was the startConferenceOnEnter attribute set on this participant (true or false)? - - .. attribute:: end_conference_on_exit - - Was the endConferenceOnExit attribute set on this participant (true or false)? - - .. attribute:: uri - - The URI for this resource, relative to https://api.twilio.com. - - -Phone Numbers ->>>>>>>>>>>>>> - -.. autoclass:: twilio.rest.resources.PhoneNumbers - :members: - :exclude-members: instance - -.. autoclass:: twilio.rest.resources.PhoneNumber - :members: - - .. attribute:: sid - - A 34 character string that uniquely idetifies this resource. - - .. attribute:: date_created - - The date that this resource was created, given as GMT RFC 2822 format. - - .. attribute:: date_updated - - The date that this resource was last updated, given as GMT RFC 2822 format. - - .. attribute:: friendly_name - - A human readable descriptive text for this resource, up to 64 characters long. By default, the FriendlyName is a nicely formatted version of the phone number. - - .. attribute:: account_sid - - The unique id of the Account responsible for this phone number. - - .. attribute:: phone_number - - The incoming phone number. e.g., +16175551212 (E.164 format) - - .. attribute:: api_version - - Calls to this phone number will start a new TwiML session with this API version. - - .. attribute:: voice_caller_id_lookup - - Look up the caller's caller-ID name from the CNAM database (additional charges apply). Either true or false. - - .. attribute:: voice_url - - The URL Twilio will request when this phone number receives a call. - - .. attribute:: voice_method - - The HTTP method Twilio will use when requesting the above Url. Either GET or POST. - - .. attribute:: voice_fallback_url - - The URL that Twilio will request if an error occurs retrieving or executing the TwiML requested by Url. - - .. attribute:: voice_fallback_method - - The HTTP method Twilio will use when requesting the VoiceFallbackUrl. Either GET or POST. - - .. attribute:: status_callback - - The URL that Twilio will request to pass status parameters (such as call ended) to your application. - - .. attribute:: status_callback_method - - The HTTP method Twilio will use to make requests to the StatusCallback URL. Either GET or POST. - - .. attribute:: sms_url - - The URL Twilio will request when receiving an incoming SMS message to this number. - - .. attribute:: sms_method - - The HTTP method Twilio will use when making requests to the SmsUrl. Either GET or POST. - - .. attribute:: sms_fallback_url - - The URL that Twilio will request if an error occurs retrieving or executing the TwiML from SmsUrl. - - .. attribute:: sms_fallback_method - - The HTTP method Twilio will use when requesting the above URL. Either GET or POST. - - .. attribute:: uri - - The URI for this resource, relative to https://api.twilio.com. - -.. autoclass:: twilio.rest.resources.AvailablePhoneNumber - :members: - - .. attribute:: friendly_name - - A nicely-formatted version of the phone number. - - .. attribute:: phone_number - - The phone number, in E.164 (i.e. "+1") format. - - .. attribute:: lata - - The LATA of this phone number. - - .. attribute:: rate_center - - The rate center of this phone number. - - .. attribute:: latitude - - The latitude coordinate of this phone number. - - .. attribute:: longitude - - The longitude coordinate of this phone number. - - .. attribute:: region - - The two-letter state or province abbreviation of this phone number. - - .. attribute:: postal_code - - The postal (zip) code of this phone number. - - .. attribute:: iso_country - - -Queues ->>>>>>>>>>> - -.. autoclass:: twilio.rest.resources.Queues - :members: - :exclude-members: instance - -.. autoclass:: twilio.rest.resources.Queue - :members: - - .. attribute:: sid - - A 34 character string that uniquely identifies this queue. - - .. attribute:: friendly_name - - A user-provided string that identifies this queue. - - .. attribute:: current_size - - The count of calls currently in the queue. - - .. attribute:: max_size - - The upper limit of calls allowed to be in the queue. - `unlimited` is an option. The default is 100. - - .. attribute:: average_wait_time - - The average wait time of the members of this queue in seconds. - This is calculated at the time of the request. - - .. attribute:: uri - - The URI for this resource, relative to https://api.twilio.com. - - -Queue Members ->>>>>>>>>>>>>> - -.. autoclass:: twilio.rest.resources.Members - :members: - :exclude-members: instance - -.. autoclass:: twilio.rest.resources.Member - :members: - - .. attribute:: call_sid - - A 34 character string that uniquely identifies the call that is enqueued. - - .. attribute:: date_enqueued - - The date that the member was enqueued, given in RFC 2822 format. - - .. attribute:: wait_time - - The number of seconds the member has been in the queue. - - .. attribute:: position - - This member’s current position in the queue. - - .. attribute:: uri - - The URI for this resource, relative to https://api.twilio.com. - - -Recordings ->>>>>>>>>>> - -.. autoclass:: twilio.rest.resources.Recordings - :members: - :exclude-members: instance - -.. autoclass:: twilio.rest.resources.Recording - :members: - - .. attribute:: sid - - A 34 character string that uniquely identifies this resource. - - .. attribute:: date_created - - The date that this resource was created, given in RFC 2822 format. - - .. attribute:: date_updated - - The date that this resource was last updated, given in RFC 2822 format. - - .. attribute:: account_sid - - The unique id of the Account responsible for this recording. - - .. attribute:: call_sid - - The call during which the recording was made. - - .. attribute:: duration - - The length of the recording, in seconds. - - .. attribute:: api_version - - The version of the API in use during the recording. - - .. attribute:: uri - - The URI for this resource, relative to https://api.twilio.com - - .. attribute:: subresource_uris - - The list of subresources under this account - - .. attribute:: formats - - A dictionary of the audio formats available for this recording - - .. code-block:: python - - { - "wav": "http://www.dailywav.com/0112/noFateButWhatWeMake.wav", - "mp3": "https://api.twilio.com/cowbell.mp3", - } - -Sandbox ->>>>>>>> - -.. autoclass:: twilio.rest.resources.Sandboxes - :members: - :exclude-members: instance - -.. autoclass:: twilio.rest.resources.Sandbox - :members: - - .. attribute:: pin - - An 8 digit number that gives access to this sandbox. - - .. attribute:: account_sid - - The unique id of the Account connected to this sandbox. - - .. attribute:: phone_number - - The phone number of the sandbox. Formatted with a '+' and country code e.g., +16175551212 (E.164 format). - - .. attribute:: voice_url - - The URL Twilio will request when the sandbox number is called. - - .. attribute:: voice_method - - The HTTP method to use when requesting the above URL. Either GET or POST. - - .. attribute:: sms_url - - The URL Twilio will request when receiving an incoming SMS message to the sandbox number. - - .. attribute:: sms_method - - The HTTP method to use when requesting the sms URL. Either GET or POST. - - .. attribute:: date_created - - The date that this resource was created, given in RFC 2822 format. - - .. attribute:: date_updated - - The date that this resource was last updated, given in RFC 2822 format. - - .. attribute:: uri - - The URI for this resource, relative to https://api.twilio.com - - -Short Codes ->>>>>>>>>>>> - -.. autoclass:: twilio.rest.resources.ShortCodes - :members: - -.. autoclass:: twilio.rest.resources.ShortCode - :members: - - .. attribute:: sid - - A 34 character string that uniquely identifies this resource. - - .. attribute:: date_created - - The date that this resource was created, given in RFC 2822 format. - - .. attribute:: date_updated - - The date that this resource was last updated, given in RFC 2822 format. - - .. attribute:: friendly_name - - A human readable descriptive text for this resource, up to 64 characters long. By default, the :attr:`friendly_name` is just the short code. - - .. attribute:: account_sid - - The unique id of the Account that owns this short code. - - .. attribute:: short_code - - The short code. e.g., 894546. - - .. attribute:: api_version - - SMSs to this short code will start a new TwiML session with this API version. - - .. attribute:: sms_url - - The URL Twilio will request when receiving an incoming SMS message to this short code. - - .. attribute:: sms_method - - The HTTP method Twilio will use when making requests to the :attr:`sms_url`. Either GET or POST. - - .. attribute:: sms_fallback_url - - The URL that Twilio will request if an error occurs retrieving or executing the TwiML from :attr:`sms_url`. - - .. attribute:: sms_fallback_method - - The HTTP method Twilio will use when requesting the above URL. Either GET or POST. - - .. attribute:: uri - - The URI for this resource, relative to https://api.twilio.com. - - -SMS Messages ->>>>>>>>>>>> - -.. autoclass:: twilio.rest.resources.SmsMessages - :members: - -.. autoclass:: twilio.rest.resources.SmsMessage - :members: - - .. attribute:: sid - - A 34 character string that uniquely identifies this resource. - - .. attribute:: date_created - - The date that this resource was created, given in RFC 2822 format. - - .. attribute:: date_updated - - The date that this resource was last updated, given in RFC 2822 format. - - .. attribute:: date_sent - - The date that the SMS was sent, given in RFC 2822 format. - - .. attribute:: account_sid - - The unique id of the Account that sent this SMS message. - - .. attribute:: from - - The phone number that initiated the message in E.164 format. For incoming messages, this will be the remote phone. For outgoing messages, this will be one of your Twilio phone numbers. - - .. attribute:: to - - The phone number that received the message in E.164 format. For incoming messages, this will be one of your Twilio phone numbers. For outgoing messages, this will be the remote phone. - - .. attribute:: body - - The text body of the SMS message. Up to 160 characters long. - - .. attribute:: status - - The status of this SMS message. Either queued, sending, sent, or failed. - - .. attribute:: direction - - The direction of this SMS message. incoming for incoming messages, outbound-api for messages initiated via the REST API, outbound-call for messages initiated during a call or outbound-reply for messages initiated in response to an incoming SMS. - - .. attribute:: price - - The amount billed for the message. - - .. attribute:: api_version - - The version of the Twilio API used to process the SMS message. - - .. attribute:: uri - - The URI for this resource, relative to https://api.twilio.com - - -Transcriptions ->>>>>>>>>>>>>>> - -.. autoclass:: twilio.rest.resources.Transcriptions - :members: - :exclude-members: instance - -.. autoclass:: twilio.rest.resources.Transcription - :members: - - .. attribute:: sid - - A 34 character string that uniquely identifies this resource. - - .. attribute:: date_created - - The date that this resource was created, given in RFC 2822 format. - - .. attribute:: date_updated - - The date that this resource was last updated, given in RFC 2822 format. - - .. attribute:: account_sid - - The unique id of the Account responsible for this transcription. - - .. attribute:: status - - A string representing the status of the transcription: in-progress, completed or failed. - - .. attribute:: recording_sid - - The unique id of the Recording this Transcription was made of. - - .. attribute:: duration - - The duration of the transcribed audio, in seconds. - - .. attribute:: transcription_text - - The text content of the transcription. - - .. attribute:: price - - The charge for this transcript in USD. Populated after the transcript is completed. Note, this value may not be immediately available. - - .. attribute:: uri - - The URI for this resource, relative to https://api.twilio.com - - diff --git a/docs/api/twiml.rst b/docs/api/twiml.rst deleted file mode 100644 index 70304283fc..0000000000 --- a/docs/api/twiml.rst +++ /dev/null @@ -1,69 +0,0 @@ -==================== -:mod:`twilio.twiml` -==================== - -.. automodule:: twilio.twiml - -.. autoclass:: twilio.twiml.Response - :members: - - -Primary Verbs -~~~~~~~~~~~~~ - -.. autoclass:: twilio.twiml.Say - :members: - -.. autoclass:: twilio.twiml.Play - :members: - -.. autoclass:: twilio.twiml.Dial - :members: - -.. autoclass:: twilio.twiml.Gather - :members: - -.. autoclass:: twilio.twiml.Record - :members: - - -Secondary Verbs -~~~~~~~~~~~~~~~ - -.. autoclass:: twilio.twiml.Hangup - :members: - -.. autoclass:: twilio.twiml.Redirect - :members: - -.. autoclass:: twilio.twiml.Reject - :members: - -.. autoclass:: twilio.twiml.Pause - :members: - -.. autoclass:: twilio.twiml.Sms - :members: - -.. autoclass:: twilio.twiml.Enqueue - :members: - -.. autoclass:: twilio.twiml.Leave - :members: - - -Nouns -~~~~~~ - -.. autoclass:: twilio.twiml.Conference - :members: - -.. autoclass:: twilio.twiml.Number - :members: - -.. autoclass:: twilio.twiml.Client - :members: - -.. autoclass:: twilio.twiml.Queue - :members: - diff --git a/docs/api/util.rst b/docs/api/util.rst deleted file mode 100644 index 0dbbb501fe..0000000000 --- a/docs/api/util.rst +++ /dev/null @@ -1,13 +0,0 @@ -==================== -:mod:`twilio.util` -==================== - -.. automodule:: twilio.util - -.. autoclass:: twilio.util.RequestValidator - :members: - -.. autoclass:: twilio.util.TwilioCapability - :members: allow_client_incoming, allow_client_outgoing, generate - - diff --git a/docs/appengine.rst b/docs/appengine.rst deleted file mode 100644 index 0cdf9db9c8..0000000000 --- a/docs/appengine.rst +++ /dev/null @@ -1,114 +0,0 @@ -============================== -Deploying to Google App Engine -============================== - -Adding the `twilio-python` library to a Google App Engine project is a little -tricky. Let's walk you through one way to do it. - - -Laying Out Your Project ------------------------ - -The key is to lay out your project in a way that makes sense. - -#. Create a project folder called ``twilio-demo``. You can name the - folder anything you like, but for the rest of this tutorial, we'll assume - it's named ``twilio-demo``. At the command line, add a `virtualenv - `_ inside of that folder, by running: - - .. code-block:: bash - - mkdir twilio-demo # Creates a new twilio-demo folder - cd twilio-demo # Move into that folder - virtualenv . # Create a new virtual environment - - You should now have a directory structure that looks like this: - - .. code-block:: bash - - twilio-demo - ├── bin - ├── include - └── lib - - We'll get to the Google App Engine part in a few steps. - -#. Now let's install the ``twilio-python`` library in our Virtualenv. If your - current working directory is ``twilio-demo``, we want to source the - ``activate`` file in the ``bin`` folder, then install the library with - ``pip``. - - .. code-block:: bash - - source bin/activate # Activate our virtual environment - pip install twilio # Install the twilio-python library - -#. Now let's add a new folder called ``src``. This is the folder that contains - your ``app.yaml`` and your other Google App Engine files. You can add this - at the command line. If your current directory is ``twilio-demo``: - - .. code-block:: bash - - mkdir src - -#. Create a basic ``app.yaml`` file in your ``src`` directory, per the - instructions Google App Engine provides. Your folder structure should now - look something like this: - - .. code-block:: bash - - twilio-demo - ├── bin - │   ├── activate - │   └── ... about 20 files - ├── include - │   └── python2.7 -> /path/to/system/python-2.7 - ├── lib - │   └── python2.7 # This folder contains a bunch of files - └── src - ├── app.yaml - └── helloworld.py - -#. Link the twilio-python library into your ``src`` directory. We are going - to use a symbolic link. Google will pick this up and import the library into - the correct place. In the terminal, run these three commands from the ``src`` - directory inside ``twilio-demo``: - - .. code-block:: bash - - ln -s ../lib/python2.7/site-packages/twilio . - ln -s ../lib/python2.7/site-packages/httplib2 . - ln -s ../lib/python2.7/site-packages/six.py . - - This should create a symbolic link inside the src directory to the - ``twilio-python`` module. You can test the link as follows. Inside the - ``twilio-demo/src`` folder, create a file called ``helloworld.py`` and put - this inside it: - - .. code-block:: python - - import webapp2 - import twilio - - class MainPage(webapp2.RequestHandler): - def get(self): - self.response.headers['Content-Type'] = 'text/plain' - self.response.write("The twilio version is " + twilio.__version__) - - app = webapp2.WSGIApplication([('/', MainPage)], - debug=True) - -#. Finally, configure your app in Google App Engine and deploy it. Here are - the settings you want in Google App Engine - Note the folder path ends with - ``twilio-demo/src``. - - .. image:: https://www.evernote.com/shard/s265/sh/1b9407b0-c89b-464d-b352-dbf8fc7a7f41/f536b8e79747f43220fc12e0e0026ee2/res/5b2f83af-8a7f-451f-afba-db092c55aa44/skitch.png - - Once App Engine is running locally, in your browser, you should be able to - navigate to ``http://localhost`` + the provided Port and view the twilio - library version number, as well as deploy your app to Google. Once you have - this set up, adding more complicated actions using the ``twilio`` library - should be a snap. - - Hope that helps! If you have questions, we're always listening at - `help@twilio.com `_. diff --git a/docs/changelog.rst b/docs/changelog.rst deleted file mode 100644 index d6c5f48c79..0000000000 --- a/docs/changelog.rst +++ /dev/null @@ -1 +0,0 @@ -.. include:: ../CHANGES diff --git a/docs/conf.py b/docs/conf.py index 06a13021ba..017b358093 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,266 +1,206 @@ # -*- coding: utf-8 -*- # -# twilio-python2 documentation build configuration file, created by -# sphinx-quickstart on Mon Dec 13 16:47:32 2010. +# Configuration file for the Sphinx documentation builder. # -# This file is execfile()d with the current directory set to its containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. -# -# All configuration values have a default; values that are commented out -# serve to show the default. +# This file does only contain a selection of the most common options. For a +# full list see the documentation: +# http://www.sphinx-doc.org/en/master/config -import sys, os -from datetime import datetime + +# -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. -#sys.path.insert(0, os.path.abspath('.')) +# +import os +import sys -# -- General configuration ----------------------------------------------------- +sys.path.insert(0, os.path.abspath("..")) +from twilio import __version__ -# If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' -# Add any Sphinx extension module names here, as strings. They can be extensions -# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = [ - 'sphinx.ext.autodoc', -] +# -- Project information ----------------------------------------------------- -# Load the source for autodoc -sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), '..'))) +project = "twilio-python" +copyright = "2023, Twilio" +author = "Twilio" +# The short X.Y version +version = __version__ +# The full version, including alpha/beta/rc tags +release = __version__ -# Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] -# The suffix of source filenames. -source_suffix = '.rst' +# -- General configuration --------------------------------------------------- -# The encoding of source files. -#source_encoding = 'utf-8-sig' +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' -# The master toctree document. -master_doc = 'index' +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.doctest", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.ifconfig", + "sphinx.ext.viewcode", + "recommonmark", +] -# General information about the project. -project = u'twilio-python' -copyright = unicode(datetime.utcnow().year) + u', Twilio Inc' +# Add any paths that contain templates here, relative to this directory. +templates_path = ["source/_templates"] -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: # -# The short X.Y version. -version = '3.4' -# The full version, including alpha/beta/rc tags. -release = '3.4.5' +source_suffix = { + ".rst": "restructuredtext", + ".md": "markdown", +} + +# The master toctree document. +master_doc = "index" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. -#language = None - -# There are two options for replacing |today|: either, you set today to some -# non-false value, then it is used: -#today = '' -# Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ['_build'] - -# The reST default role (used for this markup: `text`) to use for all documents. -#default_role = None - -# If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True - -# If true, the current module name will be prepended to all description -# unit titles (such as .. function::). -#add_module_names = True - -# If true, sectionauthor and moduleauthor directives will be shown in the -# output. They are ignored by default. -#show_authors = False +# This pattern also affects html_static_path and html_extra_path . +exclude_patterns = [] # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" -# A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] -# -- Options for HTML output --------------------------------------------------- +# -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. - -sys.path.append(os.path.abspath('_themes')) -html_theme_path = ['_themes'] -html_theme = 'kr' - +# +html_theme = "alabaster" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. -#html_theme_options = {} - -# Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] - -# The name for this set of Sphinx documents. If None, it defaults to -# " v documentation". -#html_title = None - -# A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -#html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -#html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -#html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -#html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -#html_additional_pages = {} - -# If false, no module index is generated. -#html_domain_indices = True - -# If false, no index is generated. -#html_use_index = True - -# If true, the index is split into individual pages for each letter. -#html_split_index = False - -# If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True +# +# html_theme_options = {} -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True +html_static_path = ["source/_static"] -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True +# Custom sidebar templates, must be a dictionary that maps document names +# to template names. +# +# The default sidebars (for documents that don't match any pattern) are +# defined by theme itself. Builtin themes are using these templates by +# default: ``['localtoc.html', 'relations.html', 'sourcelink.html', +# 'searchbox.html']``. +# +html_sidebars = { + "**": [ + "sidebarintro.html", + "localtoc.html", + "relations.html", + "sourcelink.html", + "searchbox.html", + ] +} -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -#html_use_opensearch = '' -# This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None +# -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. -htmlhelp_basename = 'twilio-pythondoc' - - -# -- Options for LaTeX output -------------------------------------------------- - -# The paper size ('letter' or 'a4'). -#latex_paper_size = 'letter' - -# The font size ('10pt', '11pt' or '12pt'). -#latex_font_size = '10pt' +htmlhelp_basename = "twilio-pythondoc" + + +# -- Options for LaTeX output ------------------------------------------------ + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} # Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, author, documentclass [howto/manual]). +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). latex_documents = [ - ('index', 'twilio-python.tex', u'twilio-python Documentation', - u'Twilio Inc.', 'manual'), + ( + master_doc, + "twilio-python.tex", + "twilio-python Documentation", + "Twilio", + "manual", + ), ] -# The name of an image file (relative to this directory) to place at the top of -# the title page. -#latex_logo = None - -# For "manual" documents, if this is true, then toplevel headings are parts, -# not chapters. -#latex_use_parts = False - -# If true, show page references after internal links. -#latex_show_pagerefs = False - -# If true, show URL addresses after external links. -#latex_show_urls = False - -# Additional stuff for the LaTeX preamble. -#latex_preamble = '' - -# Documents to append as an appendix to all manuals. -#latex_appendices = [] - -# If false, no module index is generated. -#latex_domain_indices = True - -# -- Options for manual page output -------------------------------------------- +# -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). -man_pages = [ - ('index', 'twilio-python', u'twilio-python Documentation', - [u'Twilio Inc.'], 1) +man_pages = [(master_doc, "twilio-python", "twilio-python Documentation", [author], 1)] + + +# -- Options for Texinfo output ---------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "twilio-python", + "twilio-python Documentation", + author, + "twilio-python", + "One line description of project.", + "Miscellaneous", + ), ] -# -- Options for Epub output --------------------------------------------------- +# -- Options for Epub output ------------------------------------------------- # Bibliographic Dublin Core info. -epub_title = u'twilio-python' -epub_author = u'kyle@twilio.com' -epub_publisher = u'Twilio Inc.' -epub_copyright = u'2010, Twilio Inc.' - -# The language of the text. It defaults to the language option -# or en if the language is not set. -#epub_language = '' - -# The scheme of the identifier. Typical schemes are ISBN or URL. -#epub_scheme = '' +epub_title = project +epub_author = author +epub_publisher = author +epub_copyright = copyright # The unique identifier of the text. This can be a ISBN number # or the project homepage. -#epub_identifier = '' +# +# epub_identifier = '' # A unique identification for the text. -#epub_uid = '' +# +# epub_uid = '' -# HTML files that should be inserted before the pages created by sphinx. -# The format is a list of tuples containing the path and title. -#epub_pre_files = [] +# A list of files that should not be packed into the epub file. +epub_exclude_files = ["search.html"] -# HTML files shat should be inserted after the pages created by sphinx. -# The format is a list of tuples containing the path and title. -#epub_post_files = [] -# A list of files that should not be packed into the epub file. -#epub_exclude_files = [] +# -- Extension configuration ------------------------------------------------- -# The depth of the table of contents in toc.ncx. -#epub_tocdepth = 3 +# -- Options for intersphinx extension --------------------------------------- -# Allow duplicate toc entries. -#epub_tocdup = True +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = {"python": ("https://docs.python.org/3", None)} diff --git a/docs/faq.rst b/docs/faq.rst deleted file mode 100644 index aee50801fc..0000000000 --- a/docs/faq.rst +++ /dev/null @@ -1,112 +0,0 @@ -========================== -Frequently Asked Questions -========================== - -Hopefully you can find an answer here to one of your questions. If not, please -contact `help@twilio.com `_. - - -ImportError messages --------------------- - -If you get an error that looks like this: - -.. code-block:: python - - Traceback (most recent call last): - File "twilio.py", line 1, in - from twilio.rest import TwilioRestClient - File "/.../twilio-python/docs/twilio.py", line 1, in - from twilio.rest import TwilioRestClient - ImportError: No module named rest - -Check to make sure that you don't have a file named ``twilio.py``; -Python will try to load the Twilio library from your ``twilio.py`` file -instead of from the Twilio library. - -If you get an error that looks like this: - -.. code-block:: python - - Traceback (most recent call last): - File "test.py", line 1, in - import twilio.rest - ImportError: No module named twilio.rest - -Your Python installation cannot find the library. - -Check which versions of ``pip`` and Python you are running with this command in -the Terminal: - -.. code-block:: bash - - which -a python - which -a pip - -``pip`` needs to install the Twilio library to a path that your Python -executable can read from. Sometimes there will be more than one version of pip, -like pip-2.5, pip-2.7 etc. You can find all of them by running ``compgen -c | -grep pip`` (works with Bash on \*nix machines). There can also be more than one -version of Python, especially if you have Macports or homebrew. - -You also may be using an outdated version of the twilio-python library, which -did not use a ``twilio.rest.TwilioRestClient`` object. Check which version of -the twilio library you have installed by running this command: - -.. code-block:: bash - - $ pip freeze | grep twilio # Or pip-2.7 freeze etc. - -The latest version (as of January 2012) is 3.3. If you are running an outdated -version, you can upgrade with this command: - -.. code-block:: bash - - $ pip install --upgrade twilio - -Note that if you have code that uses the older version of the library, it may -break when you upgrade your site. - - -Formatting phone numbers ------------------------- - -Twilio always returns phone numbers that are formatted in the `E.164 format -`_, like this: ``+12125551234``. However -your users may enter them like this: ``(212) 555-1234``. This can lead to -problems when, for example, Twilio makes a POST request to your server with the -``From`` phone number as ``+12125551234``, but you stored the phone number in -your database as ``(212) 555-1234``, causing a database lookup to fail. - -We suggest that you convert the number to E.164 format -before you store it in the database. The `phonenumbers -`_ library is excellent -for this purpose. Install it like this: - -.. code-block:: bash - - $ pip install phonenumbers - -Then you can convert user input to phone numbers like this: - -.. code-block:: python - - import phonenumbers - - def convert_to_e164(raw_phone): - if not raw_phone: - return - - if raw_phone[0] == '+': - # Phone number may already be in E.164 format. - parse_type = None - else: - # If no country code information present, assume it's a US number - parse_type = "US" - - phone_representation = phonenumbers.parse(raw_phone, parse_type) - return phonenumbers.format_number(phone_representation, - phonenumbers.PhoneNumberFormat.E164) - - print convert_to_e164('212 555 1234') # prints +12125551234 - diff --git a/docs/getting-started.rst b/docs/getting-started.rst deleted file mode 100644 index aeca3b7e36..0000000000 --- a/docs/getting-started.rst +++ /dev/null @@ -1,72 +0,0 @@ -=========== -Quickstart -=========== - -Getting started with the Twilio API couldn't be easier. Create a Twilio REST -client to get started. For example, the following code makes a call using the -Twilio REST API. - - -Make a Call -=============== - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - call = client.calls.create(to="9991231234", from_="9991231234", - url="http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient") - print call.length - print call.sid - - -Send an SMS -================ - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - account = "ACXXXXXXXXXXXXXXXXX" - token = "YYYYYYYYYYYYYYYYYY" - client = TwilioRestClient(account, token) - - message = client.sms.messages.create(to="+12316851234", - from_="+15555555555", - body="Hello there!") - - -Generating TwiML -================= - -To control phone calls, your application needs to output `TwiML -`_. Use :class:`twilio.twiml.Response` -to easily create such responses. - -.. code-block:: python - - from twilio import twiml - - r = twiml.Response() - r.play("https://api.twilio.com/cowbell.mp3", loop=5) - print str(r) - -.. code-block:: xml - - - - https://api.twilio.com/cowbell.mp3 - - - -Digging Deeper -======================== - -The full power of the Twilio API is at your fingertips. The :ref:`user-guide` -explains all the awesome features available to use. - diff --git a/docs/index.rst b/docs/index.rst deleted file mode 100644 index 0c3119533b..0000000000 --- a/docs/index.rst +++ /dev/null @@ -1,159 +0,0 @@ -============================= -Twilio Python Helper Library -============================= - -.. _installation: - -Installation -================ - -Install from PyPi using `pip `_, a -package manager for Python. - -.. code-block:: bash - - $ pip install twilio - -Don't have pip installed? Try installing it, by running this from the command -line: - -.. code-block:: bash - - $ curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python - -Or, install the library by downloading -`the source `_, -installing :data:`setuptools`, -navigating in the Terminal to the folder containing the **twilio-python** -library, and then running: - -.. code-block:: bash - - $ python setup.py install - - -Getting Started -================ - -The :doc:`/getting-started` will get you up and running in a few quick minutes. -This guide assumes you understand the core concepts of Twilio. -If you've never used Twilio before, don't fret! Just read -`about how Twilio works `_ and then jump in! - - -.. _user-guide: - -User Guide -================== - -Functionality is split over three different sub-packages within -**twilio-python**. Below are in-depth guides to specific portions of the -library. - - -REST API ----------- - -Query the Twilio REST API to create phone calls, send SMS messages and more! - -.. toctree:: - :maxdepth: 1 - - usage/basics - usage/phone-calls - usage/phone-numbers - usage/messages - usage/accounts - usage/conferences - usage/applications - usage/notifications - usage/recordings - usage/transcriptions - usage/caller-ids - usage/queues - - -TwiML ---------- - -Generates valid TwiML for controlling and manipulating phone calls. - -.. toctree:: - :maxdepth: 2 - - usage/twiml - - -Utilities ----------- - -Small functions useful for validating requests are coming from Twilio - -.. toctree:: - :maxdepth: 1 - - usage/validation - usage/token-generation - - -Upgrade Plan -================== - -`twilio-python` 3.0 introduced backwards-incompatible changes to the API. See -the :doc:`/upgrade-guide` for step-by-step instructions for migrating to 3.0. -In many cases, the same methods are still offered, just in different locations. - - -API Reference -================== - -A complete guide to all public APIs found in `twilio-python`. Auto-generated, -so only use when you really need to dive deep into the library. - -.. toctree:: - :maxdepth: 2 - - api - - -Deploying to Google App Engine -============================== - -Want to run your app on Google App Engine? We've got a full guide to getting -started here: - -.. toctree:: - :maxdepth: 1 - - appengine - -Frequently Asked Questions -========================== - -What to do if you get an ``ImportError``, and some advice about how to format -phone numbers. - -.. toctree:: - :maxdepth: 2 - - faq - - -Support and Development -========================== -All development occurs over on -`Github `_. To checkout the source, - -.. code-block:: bash - - $ git clone git@github.com:twilio/twilio-python.git - - -Report bugs using the Github -`issue tracker `_. - -If you have questions that aren't answered by this documentation, -ask the `#twilio IRC channel `_ - -See the :doc:`/changelog` for version history. - diff --git a/docs/make.bat b/docs/make.bat deleted file mode 100644 index 8ae1277a3c..0000000000 --- a/docs/make.bat +++ /dev/null @@ -1,170 +0,0 @@ -@ECHO OFF - -REM Command file for Sphinx documentation - -if "%SPHINXBUILD%" == "" ( - set SPHINXBUILD=sphinx-build -) -set BUILDDIR=_build -set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . -if NOT "%PAPER%" == "" ( - set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% -) - -if "%1" == "" goto help - -if "%1" == "help" ( - :help - echo.Please use `make ^` where ^ is one of - echo. html to make standalone HTML files - echo. dirhtml to make HTML files named index.html in directories - echo. singlehtml to make a single large HTML file - echo. pickle to make pickle files - echo. json to make JSON files - echo. htmlhelp to make HTML files and a HTML help project - echo. qthelp to make HTML files and a qthelp project - echo. devhelp to make HTML files and a Devhelp project - echo. epub to make an epub - echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter - echo. text to make text files - echo. man to make manual pages - echo. changes to make an overview over all changed/added/deprecated items - echo. linkcheck to check all external links for integrity - echo. doctest to run all doctests embedded in the documentation if enabled - goto end -) - -if "%1" == "clean" ( - for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i - del /q /s %BUILDDIR%\* - goto end -) - -if "%1" == "html" ( - %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/html. - goto end -) - -if "%1" == "dirhtml" ( - %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. - goto end -) - -if "%1" == "singlehtml" ( - %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. - goto end -) - -if "%1" == "pickle" ( - %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can process the pickle files. - goto end -) - -if "%1" == "json" ( - %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can process the JSON files. - goto end -) - -if "%1" == "htmlhelp" ( - %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can run HTML Help Workshop with the ^ -.hhp project file in %BUILDDIR%/htmlhelp. - goto end -) - -if "%1" == "qthelp" ( - %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; now you can run "qcollectiongenerator" with the ^ -.qhcp project file in %BUILDDIR%/qthelp, like this: - echo.^> qcollectiongenerator %BUILDDIR%\qthelp\twilio-python2.qhcp - echo.To view the help file: - echo.^> assistant -collectionFile %BUILDDIR%\qthelp\twilio-python2.ghc - goto end -) - -if "%1" == "devhelp" ( - %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. - goto end -) - -if "%1" == "epub" ( - %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The epub file is in %BUILDDIR%/epub. - goto end -) - -if "%1" == "latex" ( - %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex - if errorlevel 1 exit /b 1 - echo. - echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. - goto end -) - -if "%1" == "text" ( - %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The text files are in %BUILDDIR%/text. - goto end -) - -if "%1" == "man" ( - %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man - if errorlevel 1 exit /b 1 - echo. - echo.Build finished. The manual pages are in %BUILDDIR%/man. - goto end -) - -if "%1" == "changes" ( - %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes - if errorlevel 1 exit /b 1 - echo. - echo.The overview file is in %BUILDDIR%/changes. - goto end -) - -if "%1" == "linkcheck" ( - %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck - if errorlevel 1 exit /b 1 - echo. - echo.Link check complete; look for any errors in the above output ^ -or in %BUILDDIR%/linkcheck/output.txt. - goto end -) - -if "%1" == "doctest" ( - %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest - if errorlevel 1 exit /b 1 - echo. - echo.Testing of doctests in the sources finished, look at the ^ -results in %BUILDDIR%/doctest/output.txt. - goto end -) - -:end diff --git a/docs/source/_templates/sidebarintro.html b/docs/source/_templates/sidebarintro.html new file mode 100644 index 0000000000..9acc1e0e23 --- /dev/null +++ b/docs/source/_templates/sidebarintro.html @@ -0,0 +1,13 @@ +

About twilio-python

+

+ A Python module for communicating with the Twilio API and generating + TwiML. +

+ +

Useful Links

+ diff --git a/docs/src/pip-delete-this-directory.txt b/docs/src/pip-delete-this-directory.txt deleted file mode 100644 index c8883ea99f..0000000000 --- a/docs/src/pip-delete-this-directory.txt +++ /dev/null @@ -1,5 +0,0 @@ -This file is placed here by pip to indicate the source was put -here by pip. - -Once this package is successfully installed this source code will be -deleted (unless you remove this file). diff --git a/docs/upgrade-guide.rst b/docs/upgrade-guide.rst deleted file mode 100644 index e92a0c8406..0000000000 --- a/docs/upgrade-guide.rst +++ /dev/null @@ -1,190 +0,0 @@ -============== -Upgrade Guide -============== - -Porting your application from **twilio-python** 2.0 to 3.0 is straightforward. -All the same methods are still offered. Only their location has changed. - - -Making API Requests -==================== - -:class:`twilio.Account` has been moved to -:class:`twilio.rest.TwilioRestClient`. -The rest client offers a greatly improved API; -however, the old :meth:`request` method still exists (in a deprecated state). -We suggest you migrate your code to use the new API. - -Here is how you would place an outgoing call with the older version. - -.. code-block:: python - - import twilio - - # Twilio REST API version - API_VERSION = '2010-04-01' - - # Twilio AccountSid and AuthToken - ACCOUNT_SID = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' - ACCOUNT_TOKEN = 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY' - - # Outgoing Caller ID previously validated with Twilio - CALLER_ID = 'NNNNNNNNNN'; - - # Create a Twilio REST account object using your account ID and token - account = twilio.Account(ACCOUNT_SID, ACCOUNT_TOKEN) - - d = { - 'From': CALLER_ID, - 'To': '415-555-1212', - 'Url': 'http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient', - } - - print account.request('/%s/Accounts/%s/Calls' % - (API_VERSION, ACCOUNT_SID), 'POST', d) - -The same code, updated to work with the new version -(albeit using deprecated methods). - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - API_VERSION = '2010-04-01' - ACCOUNT_SID = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' - ACCOUNT_TOKEN = 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY' - CALLER_ID = 'NNNNNNNNNN'; - - client = TwilioRestClient(ACCOUNT_SID, ACCOUNT_TOKEN) - - d = { - 'From': CALLER_ID, - 'To': '415-555-1212', - 'Url': 'http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient', - } - - print client.request('/%s/Accounts/%s/Calls' % - (API_VERSION, ACCOUNT_SID), 'POST', d) - -A final version using the new interface. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - ACCOUNT_SID = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' - ACCOUNT_TOKEN = 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY' - - client = TwilioRestClient(ACCOUNT_SID, ACCOUNT_TOKEN) - call = client.calls.create(from_='NNNNNNNNNN', to='415-555-1212', - url='http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient') - - print call - - -Generating TwiML -================= - -:class:`Response` has moved into the :mod:`twiml` module. The `add*` methods -have also been deprecated in favor of method names without the 'add' prefix (as -shown below). - -Here is how you would craft a response using the old library. - -.. code-block:: python - - import twilio - - r = twilio.Response() - r.addSay("Hello World", voice=twilio.Say.MAN, language=twilio.Say.FRENCH, - loop=10) - r.addDial("4155551212", timeLimit=45) - r.addPlay("https://api.twilio.com/cowbell.mp3") - print r - -To use the new version, just change the import at the top. - -.. code-block:: python - - from twilio import twiml - - r = twiml.Response() - r.addSay("Hello World", voice=twiml.Say.MAN, language=twiml.Say.FRENCH, - loop=10) - r.addDial("4155551212", timeLimit=45) - r.addPlay("https://api.twilio.com/cowbell.mp3") - print str(r) - -The add methods are deprecated and undocumented, so please change them to the -new methods. For example, `r.addSay` would become `r.say`. - -.. code-block:: python - - from twilio import twiml - - r = twiml.Response() - - r.say("Hello World", voice=twiml.Say.MAN, language=twiml.Say.FRENCH, - loop=10) - r.dial("4155551212", timeLimit=45) - r.play("https://api.twilio.com/cowbell.mp3") - - print str(r) - - -Checking Signatures -===================== - -The :class:`Utils` class has been renamed to :class:`TwilioValidation` in the -:mod:`twilio.util` module and the :meth:`validateRequest` method has been -renamed :meth:`validate`. - -A sample using the old version of **twilio-python**. - -.. code-block:: python - - import twilio - - ACCOUNT_SID = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' - ACCOUNT_TOKEN = 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY' - - utils = twilio.Utils(ACCOUNT_SID, ACCOUNT_TOKEN) - - # the callback URL you provided to Twilio for the phone number/app - url = "http://UUUUUUUUUUUUUUUUUU" - - the POST variables attached to the request (e.g. "From", "To") - post_vars = {} - - # X-Twilio-Signature header value - signature = "HpS7PBa1Agvt4OtO+wZp75IuQa0=" # will look something like that - - if utils.validateRequest(url, post_vars, signature): - print "was confirmed to have come from Twilio." - else: - print "was NOT VALID. It might have been spoofed!" - -The same sample, converted to use the new version. - -.. code-block:: python - - from twilio import util - - ACCOUNT_TOKEN = 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY' - - utils = util.RequestValidator(ACCOUNT_TOKEN) - - # the callback URL you provided to Twilio - url = "http://www.example.com/my/callback/url.xml" - - # the POST variables attached to the request (eg "From", "To") - post_vars = {} - - # X-Twilio-Signature header value - signature = "HpS7PBa1Agvt4OtO+wZp75IuQa0=" # will look something like that - - if utils.validate(url, post_vars, signature): - print "was confirmed to have come from Twilio." - else: - print "was NOT VALID. It might have been spoofed!" - diff --git a/docs/usage/accounts.rst b/docs/usage/accounts.rst deleted file mode 100644 index 244433dfb4..0000000000 --- a/docs/usage/accounts.rst +++ /dev/null @@ -1,89 +0,0 @@ -.. module:: twilio.rest - -=========== -Accounts -=========== - -Managing Twilio accounts is straightforward. -Update your own account information or create and manage multiple subaccounts. - -For more information, see the -`Account REST Resource `_ -documentation. - - -Updating Account Information ----------------------------- - -Use the :meth:`Account.update` to modify one of your accounts. -Right now the only valid attribute is `FriendlyName`. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - account = client.accounts.get(ACCOUNT_SID) - account.update(friendly_name="My Awesome Account") - - -Creating Subaccounts ----------------------- - -Subaccounts are easy to make. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - subaccount = client.accounts.create(name="My Awesome SubAccount") - - -Managing Subaccounts -------------------------- - -Say you have a subaccount for Client X with an account sid `AC123` - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - - # Client X's subaccount - subaccount = client.accounts.get('AC123') - -Client X hasn't paid you recently, so let's suspend their account. - -.. code-block:: python - - subaccount.suspend() - -If it was just a misunderstanding, reenable their account. - -.. code-block:: python - - subaccount.activate() - -Otherwise, close their account permanently. - -.. code-block:: python - - subaccount.close() - -.. warning:: - This action can't be undone. - diff --git a/docs/usage/applications.rst b/docs/usage/applications.rst deleted file mode 100644 index e78effe57d..0000000000 --- a/docs/usage/applications.rst +++ /dev/null @@ -1,101 +0,0 @@ -.. module:: twilio.rest.resources - -================= -Applications -================= - -An application inside of Twilio is just a set of URLs and other configuration -data that tells Twilio how to behave when one of your Twilio numbers receives -a call or SMS message. - -For more information, see the `Application REST Resource -`_ documentation. - - -Listing Your Applications --------------------------- - -The following code will print out the :attr:`friendly_name` for each :class:`Application`. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - for app in client.applications.list(): - print app.friendly_name - - -Filtering Applications ---------------------------- - -You can filter applications by FriendlyName - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - for app in client.applications.list(friendly_name="FOO"): - print app.sid - - -Creating an Application -------------------------- - -When creating an application, no fields are required. We create an application -with only a :attr:`friendly_name`. The :meth:`Applications.create()` method -accepts many other arguments for url configuration. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - application = client.applications.create(friendly_name="My New App") - - -Updating an Application ------------------------- - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - url = "http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient" - app_sid = 'AP123' # the app you'd like to update - application = client.applications.update(app_sid, voice_url=url) - - -Deleting an Application -------------------------- - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - app_sid = 'AP123' # the app you'd like to delete - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - client.applications.delete(app_sid) - diff --git a/docs/usage/basics.rst b/docs/usage/basics.rst deleted file mode 100644 index 14caeac815..0000000000 --- a/docs/usage/basics.rst +++ /dev/null @@ -1,117 +0,0 @@ -.. module:: twilio.rest - -========================= -Accessing REST Resources -========================= - -To access Twilio REST resources, you'll first need to instantiate a -:class:`TwilioRestClient`. - -Authentication --------------------------- - -The :class:`TwilioRestClient` needs your Twilio credentials. While these can be -passed in directly to the constructor, we suggest storing your credentials as -environment variables. Why? You'll never have to worry about committing your -credentials and accidentally posting them somewhere public. - -The :class:`TwilioRestClient` looks for :const:`TWILIO_ACCOUNT_SID` and -:const:`TWILIO_AUTH_TOKEN` inside the current environment. - -With those two values set, create a new :class:`TwilioClient`. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - conn = TwilioRestClient() - -If you'd rather not use environment variables, pass your account credentials -directly to the the constructor. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - ACCOUNT_SID = "AXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - - -Listing Resources -------------------- - -The :class:`TwilioRestClient` gives you access to various list resources. -:meth:`ListResource.list`, by default, returns the most recent 50 instance -resources. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - resources = client.calls.list() - -:meth:`resource.ListResource.list` accepts paging arguments. -The following will return page 3 with page size of 25. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - resources = client.calls.list(page=3, page_size=25) - - -Listing All Resources -^^^^^^^^^^^^^^^^^^^^^^^ - -Sometimes you'd like to retrieve all records from a list resource. -Instead of manually paging over the resource, -the :class:`resources.ListResource.iter` method returns a generator. -After exhausting the current page, -the generator will request the next page of results. - -.. warning:: Accessing all your records can be slow. We suggest only doing so when you absolutely need all the records. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - for number in client.phone_numbers.iter(): - print number.friendly_name - - -Get an Individual Resource ------------------------------ - -To get an individual instance resource, use -:meth:`resources.ListResource.get`. -Provide the :attr:`sid` of the resource you'd like to get. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - - call = client.calls.get("CA123") - print call.to - diff --git a/docs/usage/caller-ids.rst b/docs/usage/caller-ids.rst deleted file mode 100644 index abea22fb60..0000000000 --- a/docs/usage/caller-ids.rst +++ /dev/null @@ -1,44 +0,0 @@ -.. module:: twilio.rest.resources - -================= -Caller Ids -================= - - -Validate a Phone Number ------------------------ - -Validating a phone number is quick and easy. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - response = client.caller_ids.validate("+44 9876543212") - print response.validation_code - -Twilio will call the provided number and wait for the validation code to be -entered. - -Delete a Phone Number ---------------------- - -Deleting a phone number is quick and easy. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - account = "ACXXXXXXXXXXXXXXXXX" - token = "YYYYYYYYYYYYYYYYYY" - client = TwilioRestClient(account, token) - - response = client.caller_ids.list(phone_number="+15555555555") - callerid = response[0] - callerid.delete() diff --git a/docs/usage/conferences.rst b/docs/usage/conferences.rst deleted file mode 100644 index 9cb8f09c1e..0000000000 --- a/docs/usage/conferences.rst +++ /dev/null @@ -1,102 +0,0 @@ -.. module:: twilio.rest.resources - -============================== -Conferences and Participants -============================== - -For more information, see the `Conference REST Resource `_ and `Participant REST Resource `_ documentation. - - -Listing Conferences ------------------------ - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - conferences = client.conferences.list() - - for conference in conferences: - print conference.sid - - -Filtering Conferences ------------------------ - -The :meth:`Conferences.list` method supports filtering on :attr:`status`, :attr:`date_updated`, :attr:`date_created` and :attr:`friendly_name`. The following code will return a list of all in-progress conferences and print their friendly name. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - conferences = client.conferences.list(status="in-progress") - - for conference in conferences: - print conference.friendly_name - - -Listing Participants ----------------------- - -Each :class:`Conference` has a :attr:`participants` instance which represents all current users in the conference - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - conference = client.conferences.get("CF123") - - for participant in conference.participants.list(): - print participant.sid - -:class:`Conferences` and :class:`Participants` are subclasses of :class:`ListResource`. -Therefore, their instances have the inherited methods such as :meth:`count`. - - -Managing Participants ----------------------- - -Each :class:`Conference` has a :attr:`participants` function that returns a -:class:`Participants` instance. This behavior differs from other list resources -because :class:`Participants` needs a participant sid AND a conference sid to -access the participants resource. - -Participants can be either muted or kicked out of the conference. The following -code kicks out the first participant and mutes the rest. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - participants = client.participants("CF123").list() - - if len(participants) == 0: - return - - # Kick the first person out - participants.pop().kick() - - # And mute the rest - for participant in participants: - participant.mute() - diff --git a/docs/usage/messages.rst b/docs/usage/messages.rst deleted file mode 100644 index 27e12f4232..0000000000 --- a/docs/usage/messages.rst +++ /dev/null @@ -1,79 +0,0 @@ -.. module:: twilio.rest.resources.sms_messages - -============ -SMS Messages -============ - -For more information, see the -`SMS Message REST Resource `_ -documentation. - - -Sending a Text Message ----------------------- - -Send a text message in only a few lines of code. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - - message = client.sms.messages.create(to="+13216851234", - from_="+15555555555", - body="Hello!") - - -.. note:: The message body must be less than 160 characters in length - -If you want to send a message from a `short code -`_ on Twilio, just set :attr:`from_` -to your short code's number. - - -Retrieving Sent Messages -------------------------- - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - - for message in client.sms.messages.list(): - print message.body - - -Filtering Your Messages -------------------------- - -The :meth:`list` methods supports filtering on :attr:`to`, :attr:`from_`, -and :attr:`date_sent`. -The following will only show messages to "+5466758723" on January 1st, 2011. - -.. code-block:: python - - from datetime import date - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - - messages = client.sms.messages.list(to="+5466758723", - date_sent=date(2011,1,1)) - - for message in messages: - print message.body - diff --git a/docs/usage/notifications.rst b/docs/usage/notifications.rst deleted file mode 100644 index c4d3bcea61..0000000000 --- a/docs/usage/notifications.rst +++ /dev/null @@ -1,69 +0,0 @@ -.. module:: twilio.rest.resources - -==================== -Notifications -==================== - -For more information, see the `Notifications REST Resource -`_ documentation. - - -Listing Your Notifications ----------------------------- - -The following code will print out additional information about each of your -current :class:`Notification` resources. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - for notification in client.notifications.list(): - print notification.more_info - -You can filter transcriptions by :attr:`log` and :attr:`message_date`. -The :attr:`log` value is 0 for `ERROR` and 1 for `WARNING`. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - - ERROR = 0 - - for notification in client.notifications.list(log=ERROR): - print notification.error_code - -.. note:: Due to the potentially voluminous amount of data in a notification, - the full HTTP request and response data is only returned in the - :class:`Notification` instance resource representation. - - -Deleting Notifications ------------------------- - -Your account can sometimes generate an inordinate amount of -:class:`Notification` resources. The :class:`Notifications` resource allows -you to delete unnecessary notifications. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - client.notifications.delete("NO123") - diff --git a/docs/usage/phone-calls.rst b/docs/usage/phone-calls.rst deleted file mode 100644 index 600a14ece2..0000000000 --- a/docs/usage/phone-calls.rst +++ /dev/null @@ -1,165 +0,0 @@ -.. module:: twilio.rest - -===================== -Phone Calls -===================== - -The :class:`Calls` resource manages all interaction with Twilio phone calls, -including the creation and termination of phone calls. - - -Making a Phone Call -------------------- - -The :class:`Calls` resource allows you to make outgoing calls. Before a call -can be successfully started, you'll need a to set up a url endpoint which -outputs valid `TwiML `_. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - call = client.calls.create(to="9991231234", from_="9991231234", - url="http://foo.com/call.xml") - print call.length - print call.sid - - -Retrieve a Call Record -------------------------- - -If you already have a :class:`Call` sid, -you can use the client to retrieve that record. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - sid = "CA12341234" - call = client.calls.get(sid) - - -Accessing Specific Call Resources -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Each :class:`Call` resource also has access to its `notifications`, -`recordings`, and `transcriptions`. -These attributes are :class:`ListResources`, -just like the :class:`Calls` resource itself. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - sid = "CA12341234" - call = client.calls.get(sid) - - print call.notifications.list() - print call.recordings.list() - print call.transcriptions.list() - -However, what if you only have a `CallSid`, and not the actual -:class:`Resource`? No worries, as :meth:`list` can be filter based on a given -`CallSid`. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - sid = "CA24234" - print client.notifications.list(call=sid) - print client.recordings.list(call=sid) - print client.transcriptions.list(call=sid) - - -Modifying Live Calls --------------------- - -The :class:`Call` resource makes it easy to find current live calls and -redirect them as necessary - -.. code-block:: python - - from twilio.rest import TwilioRestClient - from twilio.rest.resources import Call - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - calls = client.calls.list(status=Call.IN_PROGRESS) - for c in calls: - c.route( - "http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient", - method="POST" - ) - -Ending all live calls is also possible - -.. code-block:: python - - from twilio.rest import TwilioRestClient - from twilio.rest.resources import Call - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - calls = client.calls.list(status=Call.IN_PROGRESS) - for c in calls: - c.hangup() - -Note that :meth:`hangup` will also cancel calls currently queued. - -If you already have a :class:`Call` sid, you can use the :class:`Calls` -resource to update the record without having to use :meth:`get` first. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - sid = "CA12341234" - client.calls.update(sid, method="POST", - url="http://twimlets.com/holdmusic?Bucket=com.twilio.music.ambient") - -Hanging up the call also works. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - sid = "CA12341234" - client.calls.hangup(sid) - diff --git a/docs/usage/phone-numbers.rst b/docs/usage/phone-numbers.rst deleted file mode 100644 index 91b4cccf69..0000000000 --- a/docs/usage/phone-numbers.rst +++ /dev/null @@ -1,159 +0,0 @@ -.. module:: twilio.rest.resources - -================= -Phone Numbers -================= - -With Twilio you can search and buy real phone numbers, just using the API. - -For more information, see the -`IncomingPhoneNumbers REST Resource -`_ documentation. - - -Searching and Buying a Number --------------------------------- - -Finding numbers to buy couldn't be easier. -We first search for a number in area code 530. -Once we find one, we'll purchase it for our account. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - numbers = client.phone_numbers.search(area_code=530) - - if numbers: - numbers[0].purchase() - else: - print "No numbers in 530 available" - - -Toll Free Numbers -^^^^^^^^^^^^^^^^^^^^^^^^ - -By default, :meth:`PhoneNumbers.search` looks for local phone numbers. Add a -:data:`type` : ``tollfree`` parameter to search toll-free numbers instead. - -.. code-block:: python - - numbers = client.phone_numbers.search(type="tollfree") - - -Numbers Containing Words -^^^^^^^^^^^^^^^^^^^^^^^^^^ - -Phone number search also supports looking for words inside phone numbers. -The following example will find any phone number with "FOO" in it. - -.. code-block:: python - - numbers = client.phone_numbers.search(contains="FOO") - -You can use the ''*'' wildcard to match any character. The following example finds any phone number that matches the pattern ''D*D''. - -.. code-block:: python - - numbers = client.phone_numbers.search(contains="D*D") - - -International Numbers -^^^^^^^^^^^^^^^^^^^^^^^^^^ - -By default, the client library will look for US numbers. Set the -:data:`country` keyword to a country code of your choice to search for -international numbers. - -.. code-block:: python - - numbers = client.phone_numbers.search(country="FR") - - -:meth:`PhoneNumbers.search` method has plenty of other options to augment your search : - -- :data:`region`: When searching the US, show numbers in this state -- :data:`postal_code`: Only show numbers in this area code -- :data:`rate_center`: US only. -- :data:`near_lat_long`: Find numbers near this latitude and longitude. -- :data:`distance`: Search radius for a Near- query in miles. - -The `AvailablePhoneNumbers REST Resource -`_ documentation -has more information on the various search options. - - -Buying a Number ---------------- - -If you've found a phone number you want, you can purchase the number. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - number = client.phone_numbers.purchase(phone_number="+15305431234") - -However, it's easier to purchase numbers after finding them using search (as -shown in the first example). - - -Updating Properties on a Number -------------------------------- - -To update the properties on a phone number, call :meth:`update` -on the phone number object, with any of the parameters -listed in the `IncomingPhoneNumbers Resource documentation -`_ - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - for number in client.phone_numbers.list(api_version="2010-04-01"): - number.update(voice_url="http://twimlets.com/holdmusic?" + - "Bucket=com.twilio.music.ambient", - status_callback="http://example.com/callback") - - -Changing Applications ----------------------- - -An :class:`Application` encapsulates all necessary URLs for use with phone numbers. Update an application on a phone number using :meth:`update`. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - phone_sid = "PNXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - number = client.phone_numbers.update(phone_sid, sms_application_sid="AP123") - -See :doc:`/usage/applications` for instructions on updating and maintaining Applications. - - -Validate a Phone Number ------------------------ - -See validation instructions here: :doc:`/usage/caller-ids`: - diff --git a/docs/usage/queues.rst b/docs/usage/queues.rst deleted file mode 100644 index 59413855da..0000000000 --- a/docs/usage/queues.rst +++ /dev/null @@ -1,106 +0,0 @@ -.. module:: twilio.rest.resources - -============================== -Queues and Members -============================== - -For more information, see the -`Queue REST Resource `_ -and `Member REST Resource `_ -documentation. - - -Listing Queues ------------------------ - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - queues = client.queues.list() - - for queue in queues: - print queue.sid - - -Listing Queue Members ----------------------- - -Each :class:`Queue` has a :attr:`queue_members` instance which -represents all current calls in the queue. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - queue = client.queues.get("QU123") - - for member in queue.queue_members.list(): - print member.call_sid - - -Getting a specific Queue Member -------------------------------- - -To retrieve information about a specific member in the queue, each -:class:`Members` has a :attr:`get` method. :attr:`get` accepts one -argument. The argument can either be a `call_sid` thats in the queue, -in which case :attr:`get` will return a :class:`Member` instance -representing that call, or the argument can be 'Front', in which case -:attr:`Get` will return a :class:`Member` instance representing the -first call in the queue. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - QUEUE_SID = "QUaaaaaaaaaaaaa" - CALL_SID = "CAxxxxxxxxxxxxxx" - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - members = client.queues.get(QUEUE_SID).queue_members - - # Get the first call in the queue - print members.get('Front').date_enqueued - - # Get the call with the given call sid in the queue - print members.get(CALL_SID).current_position - - -Dequeueing Queue Members ------------------------- - -To dequeue a specific member from the queue, each -:class:`Members` has a :attr:`dequeue` method. :attr:`dequeue` accepts an -argument and two optional keyword arguments. The first argument is the -url of the twiml document to be executed when the member is -dequeued. The other two are :attr:`call_sid` and :attr:`method`, their -default values are 'Front' and 'GET' - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - QUEUE_SID = "QUaaaaaaaaaaaaa" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - members = client.queues.get(QUEUE_SID).queue_members - - # Dequeue the first call in the queue - print members.dequeue('http://www.twilio.com/welcome/call') - diff --git a/docs/usage/recordings.rst b/docs/usage/recordings.rst deleted file mode 100644 index 54fa72ce7c..0000000000 --- a/docs/usage/recordings.rst +++ /dev/null @@ -1,101 +0,0 @@ -.. module:: twilio.rest.resources - -================ -Recordings -================ - -For more information, see the -`Recordings REST Resource `_ -documentation. - - -Audio Formats ------------------ - -Each :class:`Recording` has a :attr:`formats` dictionary which lists the audio -formats available for each recording. -Below is an example :attr:`formats` dictionary. - -.. code-block:: python - - { - "mp3": "https://api.twilio.com/cowbell.mp3", - "wav": "http://www.dailywav.com/0112/noFateButWhatWeMake.wav", - } - - -Listing Your Recordings ----------------------------- - -The following code will print out the :attr:`duration` -for each :class:`Recording`. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - for recording in client.recordings.list(): - print recording.duration - -You can filter recordings by CallSid by passing the Sid as :attr:`call`. -Filter recordings using :attr:`before` and :attr:`after` dates. - -The following will only show recordings made before January 1, 2011. - -.. code-block:: python - - from datetime import date - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - for recording in client.recordings.list(before=date(2011,1,1)): - print recording.duration - - -Deleting Recordings ---------------------- - -The :class:`Recordings` resource allows you to delete unnecessary recordings. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - client.recordings.delete("RC123") - - -Accessing Related Transcptions -------------------------------- - -The :class:`Recordings` allows you to retrieve associated transcriptions. -The following prints out the text for each of the transcriptions associated -with this recording. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - recording = client.recordings.get("RC123") - - for transcription in recording.transcriptions.list(): - print transcription.transcription_text - diff --git a/docs/usage/token-generation.rst b/docs/usage/token-generation.rst deleted file mode 100644 index 5a578a6785..0000000000 --- a/docs/usage/token-generation.rst +++ /dev/null @@ -1,81 +0,0 @@ -.. module:: twilio.util - -=========================== -Generate Capability Tokens -=========================== - -`Twilio Client `_ allows you to make and -receive connections in the browser. -You can place a call to a phone on the PSTN network, -all without leaving your browser. See the `Twilio Client Quickstart -`_ to get up and running with -Twilio Client. - -Capability tokens are used by `Twilio Client -`_ to provide connection -security and authorization. The `Capability Token documentation -`_ explains in depth the purpose and -features of these tokens. - -:class:`TwilioCapability` is responsible for the creation of these capability -tokens. You'll need your Twilio AccountSid and AuthToken. - -.. code-block:: python - - from twilio.util import TwilioCapability - - # Find these values at twilio.com/user/account - account_sid = "AC123123" - auth_token = "secret" - - capability = TwilioCapability(account_sid, auth_token) - - -Allow Incoming Connections -============================== - -Before a device running `Twilio Client `_ -can recieve incoming connections, the instance must first register a name -(such as "Alice" or "Bob"). -The :meth:`allow_client_incoming` method adds the client name to the -capability token. - -.. code-block:: python - - capability.allow_client_incoming("Alice") - - -Allow Outgoing Connections -============================== - -To make an outgoing connection from a -`Twilio Client `_ device, -you'll need to choose a -`Twilio Application `_ -to handle TwiML URLs. A Twilio Application is a collection of URLs responsible -for outputting valid TwiML to control phone calls and SMS. - -.. code-block:: python - - # Twilio Application Sid - application_sid = "APabe7650f654fc34655fc81ae71caa3ff" - capability.allow_client_outgoing(application_sid) - - -Generate a Token -================== - -.. code-block:: python - - token = capability.generate() - -By default, this token will expire in one hour. If you'd like to change the -token expiration, :meth:`generate` takes an optional :attr:`expires` argument. - -.. code-block:: python - - token = capability.generate(expires=600) - -This token will now expire in 10 minutes. If you haven't guessed already, -:attr:`expires` is expressed in seconds. - diff --git a/docs/usage/transcriptions.rst b/docs/usage/transcriptions.rst deleted file mode 100644 index 7f85db5175..0000000000 --- a/docs/usage/transcriptions.rst +++ /dev/null @@ -1,31 +0,0 @@ -.. module:: twilio.rest.resources - -================ -Transcriptions -================ - -Transcriptions are generated from recordings via the -`TwiML verb `_. -Using the API, you can only read your transcription records. - -For more information, see the `Transcriptions REST Resource -`_ documentation. - - -Listing Your Transcriptions ----------------------------- - -The following code will print out the length of each :class:`Transcription`. - -.. code-block:: python - - from twilio.rest import TwilioRestClient - - # To find these visit https://www.twilio.com/user/account - ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXX" - AUTH_TOKEN = "YYYYYYYYYYYYYYYYYY" - - client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN) - for transcription in client.transcriptions.list(): - print transcription.duration - diff --git a/docs/usage/twiml.rst b/docs/usage/twiml.rst deleted file mode 100644 index 38892de20f..0000000000 --- a/docs/usage/twiml.rst +++ /dev/null @@ -1,90 +0,0 @@ -.. _usage-twiml: - -.. module:: twilio.twiml - -============== -TwiML Creation -============== - -TwiML creation begins with the :class:`Response` verb. -Each successive verb is created by calling various methods on the response, -such as :meth:`say` or :meth:`play`. -These methods return the verbs they create to ease creation of nested TwiML. -To finish, call the :meth:`toxml` method on the :class:`Response`, -which returns raw TwiML. - -.. code-block:: python - - from twilio import twiml - - r = twiml.Response() - r.say("Hello") - print str(r) - -.. code-block:: xml - - - Hello - -The verb methods (outlined in the :doc:`complete reference `) -take the body (only text) of the verb as the first argument. -All attributes are keyword arguments. - -.. code-block:: python - - from twilio import twiml - - r = twiml.Response() - r.play("https://api.twilio.com/cowbell.mp3", loop=5) - print str(r) - -.. code-block:: xml - - - - https://api.twilio.com/cowbell.mp3 - - -Python 2.6+ added the :const:`with` statement for context management. -Using :const:`with`, the module can *almost* emulate Ruby blocks. - -.. code-block:: python - - from twilio import twiml - - r = twiml.Response() - r.say("hello") - with r.gather(finishOnKey=4) as g: - g.say("world") - print str(r) - -which returns the following - -.. code-block:: xml - - - - Hello - World - - -If you don't want the XML declaration in your output, -use the :meth:`toxml` method - -.. code-block:: python - - from twilio import twiml - - r = twiml.Response() - r.say("hello") - with r.gather(finishOnKey=4) as g: - g.say("world") - print r.toxml(xml_declaration=False) - -.. code-block:: xml - - - Hello - World - - diff --git a/docs/usage/validation.rst b/docs/usage/validation.rst deleted file mode 100644 index 5030547c01..0000000000 --- a/docs/usage/validation.rst +++ /dev/null @@ -1,70 +0,0 @@ -.. module:: twilio.util - -=========================== -Validate Incoming Requests -=========================== - -Twilio requires that your TwiML-serving web server be open to the public. This -is necessary so that Twilio can retrieve TwiML from urls and POST data back to -your server. - -However, there may be people out there trying to spoof the Twilio service. -Luckily, there's an easy way to validate that incoming requests are from Twilio -and Twilio alone. - -An in-depth guide to our security features can be `found in our online -documentation `_. - -Before you can validate requests, you'll need four pieces of information: - -* your Twilio Auth Token (found in your `Dashboard - `_) -* the POST data for the request -* the requested URL -* the X-Twilio-Signature header value - -Obtaining the last three pieces of information depends on the framework you are -using to process requests. The below example assumes that you have the POST -data as a dictionary and the url and X-Twilio-Signature as strings. - -The below example will print out a confirmation message if the request is -actually from Twilio. - -.. code-block:: python - - from twilio.util import RequestValidator - - AUTH_TOKEN = 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY' - - validator = RequestValidator(AUTH_TOKEN) - - # the callback URL you provided to Twilio - url = "http://www.example.com/my/callback/url.xml" - - # the POST variables attached to the request (eg "From", "To") - post_vars = {} - - # X-Twilio-Signature header value - signature = "HpS7PBa1Agvt4OtO+wZp75IuQa0=" # will look something like that - - if validator.validate(url, post_vars, signature): - print "Confirmed to have come from Twilio." - else: - print "NOT VALID. It might have been spoofed!" - - -Trailing Slashes -================== - -If your URL uses an "index" page, such as index.php or index.html to handle -the request, such as: https://mycompany.com/twilio where the real page -is served from https://mycompany.com/twilio/index.php, then Apache or -PHP may rewrite that URL a little bit so it's got a trailing slash, such as -https://mycompany.com/twilio/ for example. - -Using the code above, or similar code in another language, you could -end up with an incorrect hash because Twilio built the hash using -https://mycompany.com/twilio and you may have built the hash using -https://mycompany.com/twilio/. More information can be found in our -documentation on validating requests. - diff --git a/examples/basic_usage.py b/examples/basic_usage.py new file mode 100644 index 0000000000..a1ad25b0f2 --- /dev/null +++ b/examples/basic_usage.py @@ -0,0 +1,45 @@ +import os + +from twilio.rest import Client +from twilio.twiml.voice_response import VoiceResponse + +ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID") +AUTH_TOKEN = os.environ.get("TWILIO_AUTH_TOKEN") + + +def example(): + """ + Some example usage of different twilio resources. + """ + client = Client(ACCOUNT_SID, AUTH_TOKEN) + + # Get all messages + all_messages = client.messages.list() + print("There are {} messages in your account.".format(len(all_messages))) + + # Get only last 10 messages... + some_messages = client.messages.list(limit=10) + print("Here are the last 10 messages in your account:") + for m in some_messages: + print(m) + + # Get messages in smaller pages... + all_messages = client.messages.list(page_size=10) + print("There are {} messages in your account.".format(len(all_messages))) + + print("Sending a message...") + new_message = client.messages.create(to="XXXX", from_="YYYY", body="Twilio rocks!") + + print("Making a call...") + new_call = client.calls.create(to="XXXX", from_="YYYY", method="GET") + + print("Serving TwiML") + twiml_response = VoiceResponse() + twiml_response.say("Hello!") + twiml_response.hangup() + twiml_xml = twiml_response.to_xml() + print("Generated twiml: {}".format(twiml_xml)) + + +if __name__ == "__main__": + example() diff --git a/examples/client_validation.py b/examples/client_validation.py new file mode 100644 index 0000000000..a7bc08e81a --- /dev/null +++ b/examples/client_validation.py @@ -0,0 +1,73 @@ +import os + +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.hazmat.primitives.serialization import ( + Encoding, + PublicFormat, + PrivateFormat, + NoEncryption, +) + +from twilio.http.validation_client import ValidationClient +from twilio.rest import Client + + +ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID") +AUTH_TOKEN = os.environ.get("TWILIO_AUTH_TOKEN") + + +def example(): + """ + Example of using the ValidationClient for signed requests to Twilio. + This is only available to enterprise customers. + + This will walkthrough creating an API Key, generating an RSA keypair, setting up a + ValidationClient with these values and making requests with the client. + """ + client = Client(ACCOUNT_SID, AUTH_TOKEN) + + # Using Client Validation requires using API Keys for auth + # First create an API key using the standard account sid, auth token client + print("Creating new api key...") + api_key = client.new_keys.create(friendly_name="ClientValidationApiKey") + + # Generate a new RSA Keypair + print("Generating RSA key pair...") + key_pair = rsa.generate_private_key( + public_exponent=65537, key_size=2048, backend=default_backend() + ) + public_key = key_pair.public_key().public_bytes( + Encoding.PEM, PublicFormat.SubjectPublicKeyInfo + ) + private_key = key_pair.private_bytes( + Encoding.PEM, PrivateFormat.PKCS8, NoEncryption() + ) + + # Register the public key with Twilio + print("Registering public key with Twilio...") + credential = client.accounts.credentials.public_key.create( + public_key, friendly_name="ClientValidationPublicKey" + ) + + # Create a new ValidationClient with the keys we created + validation_client = ValidationClient( + ACCOUNT_SID, api_key.sid, credential.sid, private_key + ) + + # Create a REST Client using the validation_client + client = Client( + api_key.sid, api_key.secret, ACCOUNT_SID, http_client=validation_client + ) + + # Use the library as usual + print("Trying out client validation...") + messages = client.messages.list(limit=10) + for m in messages: + print("Message {}".format(m.sid)) + + print("Client validation works!") + + +if __name__ == "__main__": + example() diff --git a/examples/organization_api.py b/examples/organization_api.py new file mode 100644 index 0000000000..0d653c12a4 --- /dev/null +++ b/examples/organization_api.py @@ -0,0 +1,32 @@ +import os + +from twilio.rest import Client +from twilio.credential.orgs_credential_provider import OrgsCredentialProvider + +ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID") +API_KEY = os.environ.get("TWILIO_API_KEY") +API_SECRET = os.environ.get("TWILIO_API_SECRET") + +CLIENT_ID = os.environ.get("TWILIO_CLIENT_ID") +CLIENT_SECRET = os.environ.get("CLIENT_SECRET") +ORGS_SID = os.environ.get("ORGS_SID") + + +def example(): + """ + Some example usage of using organization resources + """ + client = Client( + account_sid=ACCOUNT_SID, + credential_provider=OrgsCredentialProvider(CLIENT_ID, CLIENT_SECRET), + ) + + accounts = client.preview_iam.organization( + organization_sid=ORGS_SID + ).accounts.stream() + for record in accounts: + print(record) + + +if __name__ == "__main__": + example() diff --git a/examples/public_oauth.py b/examples/public_oauth.py new file mode 100644 index 0000000000..41eb589c37 --- /dev/null +++ b/examples/public_oauth.py @@ -0,0 +1,31 @@ +import os + +from twilio.rest import Client +from twilio.credential.client_credential_provider import ClientCredentialProvider + +ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID") +API_KEY = os.environ.get("TWILIO_API_KEY") +API_SECRET = os.environ.get("TWILIO_API_SECRET") +FROM_NUMBER = os.environ.get("TWILIO_FROM_NUMBER") +TO_NUMBER = os.environ.get("TWILIO_TO_NUMBER") + +CLIENT_ID = os.environ.get("TWILIO_CLIENT_ID") +CLIENT_SECRET = os.environ.get("CLIENT_SECRET") + + +def example(): + """ + Some example usage of message resources. + """ + client = Client( + account_sid=ACCOUNT_SID, + credential_provider=ClientCredentialProvider(CLIENT_ID, CLIENT_SECRET), + ) + + msg = client.messages.create( + to=self.to_number, from_=self.from_number, body="hello world" + ) + + +if __name__ == "__main__": + example() diff --git a/index.rst b/index.rst new file mode 100644 index 0000000000..90e5c3df2e --- /dev/null +++ b/index.rst @@ -0,0 +1,37 @@ +.. twilio-python documentation master file, created by + sphinx-quickstart on Fri Jul 27 12:54:05 2018. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + + +Welcome to twilio-python's documentation! +========================================= + +Release v\ |version|. + +.. toctree:: + :maxdepth: 2 + + README.md + + +API auto-generated documentation +================================ + +If you are looking for information on a specific function, class or +method, this part of the documentation is for you. + +.. toctree:: + :maxdepth: 1 + :glob: + + docs/source/_rst/modules.rst + + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` + diff --git a/requirements.txt b/requirements.txt index a802f33139..7bc9e41806 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,8 @@ -six -httplib2 +pygments>=2.7.4 # not directly required, pinned by Snyk to avoid a vulnerability +requests>=2.32.2 +PyJWT>=2.0.0, <3.0.0 +aiohttp>=3.10.2 +aiohttp-retry==2.8.3 +certifi>=2023.7.22 # not directly required, pinned by Snyk to avoid a vulnerability +urllib3>=2.2.2 # not directly required, pinned by Snyk to avoid a vulnerability +zipp>=3.19.1 # not directly required, pinned by Snyk to avoid a vulnerability diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000000..4c18756789 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,13 @@ +[bdist_wheel] +universal = 1 + +[metadata] +long_description = file: README.md +license = MIT + +[flake8] +exclude = ./twilio/rest,./twilio/twiml,./tests/integration + +[coverage:run] +omit = twilio/rest/* +relative_files = True diff --git a/setup.py b/setup.py old mode 100755 new mode 100644 index 2af23a8509..97004e4a02 --- a/setup.py +++ b/setup.py @@ -1,7 +1,8 @@ -import sys -from twilio import __version__ from setuptools import setup, find_packages +with open("README.md") as f: + long_description = f.read() + # To install the twilio-python library, open a Terminal shell, then run this # file by typing: # @@ -9,46 +10,41 @@ # # You need to have the setuptools module installed. Try reading the setuptools # documentation: http://pypi.python.org/pypi/setuptools -REQUIRES = ["httplib2 >= 0.7", "six"] - -if sys.version_info < (2, 6): - REQUIRES.append('simplejson') -if sys.version_info >= (3,0): - REQUIRES.append('unittest2py3k') -else: - REQUIRES.append('unittest2') setup( - name = "twilio", - version = __version__, - description = "Twilio API client and TwiML generator", - author = "Twilio", - author_email = "help@twilio.com", - url = "http://github.com/twilio/twilio-python/", - keywords = ["twilio","twiml"], - install_requires = REQUIRES, - packages = find_packages(), - classifiers = [ + name="twilio", + version="9.6.3", + description="Twilio API client and TwiML generator", + author="Twilio", + help_center="https://www.twilio.com/help/contact", + url="https://github.com/twilio/twilio-python/", + keywords=["twilio", "twiml"], + python_requires=">=3.7.0", + install_requires=[ + "requests >= 2.0.0", + "PyJWT >= 2.0.0, < 3.0.0", + "aiohttp>=3.8.4", + "aiohttp-retry>=2.8.3", + ], + packages=find_packages(exclude=["tests", "tests.*"]), + include_package_data=True, + classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", - "Programming Language :: Python :: 2.5", - "Programming Language :: Python :: 2.6", - "Programming Language :: Python :: 2.7", - "Programming Language :: Python :: 3.2", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: Implementation :: CPython", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Communications :: Telephony", - ], - long_description = """\ - Python Twilio Helper Library - ---------------------------- - - DESCRIPTION - The Twilio REST SDK simplifies the process of makes calls to the Twilio REST. - The Twilio REST API lets to you initiate outgoing calls, list previous calls, - and much more. See http://www.github.com/twilio/twilio-python for more information. - - LICENSE The Twilio Python Helper Library is distributed under the MIT - License """ ) + ], + long_description=long_description, + long_description_content_type="text/markdown", +) diff --git a/sonar-project.properties b/sonar-project.properties new file mode 100644 index 0000000000..600f5485b1 --- /dev/null +++ b/sonar-project.properties @@ -0,0 +1,16 @@ +sonar.projectKey=twilio_twilio-python +sonar.projectName=twilio-python +sonar.organization=twilio + +sonar.sources=twilio/ +# Exclude any auto-generated source code +sonar.exclusions=twilio/rest/**/* +sonar.tests=tests/ +# Exclude any auto-generated integration tests +sonar.test.exclusions=tests/integration/**/test_*.py + +# For Code Coverage analysis +sonar.python.coverage.reportPaths=coverage.xml +# Exclude auto-generated code from coverage analysis +sonar.coverage.exclusions=twilio/rest/**/* +sonar.python.version=3 diff --git a/tests/README.md b/tests/README.md deleted file mode 100644 index ae9b0311fb..0000000000 --- a/tests/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# twilio-python unit tests - -## Setup - -From the root directory of this repository: - - $ python setup.py develop - $ pip install -r tests/requirements.txt - -## Running the tests - -Again, from the root directory of this repository: - - $ nosetests tests/ diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000..8a15535503 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,17 @@ +import unittest + +from tests.holodeck import Holodeck +from twilio.rest import Client + + +class IntegrationTestCase(unittest.TestCase): + def setUp(self): + super(IntegrationTestCase, self).setUp() + self.account_sid = "AC" + "a" * 32 + self.auth_token = "AUTHTOKEN" + self.holodeck = Holodeck() + self.client = Client( + username=self.account_sid, + password=self.auth_token, + http_client=self.holodeck, + ) diff --git a/tests/cluster/test_cluster.py b/tests/cluster/test_cluster.py new file mode 100644 index 0000000000..0c18428d15 --- /dev/null +++ b/tests/cluster/test_cluster.py @@ -0,0 +1,84 @@ +import os +import unittest + +from twilio.rest import Client +from twilio.twiml.voice_response import VoiceResponse + + +class ClusterTest(unittest.TestCase): + def setUp(self): + self.from_number = os.environ["TWILIO_FROM_NUMBER"] + self.to_number = os.environ["TWILIO_TO_NUMBER"] + self.api_key = os.environ["TWILIO_API_KEY"] + self.api_secret = os.environ["TWILIO_API_SECRET"] + self.account_sid = os.environ["TWILIO_ACCOUNT_SID"] + self.assistant_id = os.environ["ASSISTANT_ID"] + self.client = Client( + username=self.api_key, + password=self.api_secret, + account_sid=self.account_sid, + ) + self.voice_twiml = VoiceResponse() + + def test_send_text_message(self): + msg = self.client.messages.create( + to=self.to_number, from_=self.from_number, body="hello world" + ) + self.assertEqual(msg.to, self.to_number) + self.assertEqual(msg.from_, self.from_number) + self.assertEqual(msg.body, "hello world") + self.assertIsNotNone(msg.sid) + + def test_list_incoming_numbers(self): + incoming_phone_numbers = self.client.incoming_phone_numbers.list() + self.assertIsNotNone(incoming_phone_numbers) + self.assertGreaterEqual(len(incoming_phone_numbers), 2) + + def test_list_an_incoming_number(self): + incoming_phone_numbers = self.client.incoming_phone_numbers.list(limit=1) + self.assertIsNotNone(incoming_phone_numbers) + self.assertEqual(len(incoming_phone_numbers), 1) + + def test_allow_special_characters_for_friendly_and_identity_name(self): + friendly_name = "service|friendly&name" + identity_name = "user|identity&string" + conversation = self.client.conversations.v1.conversations.create( + friendly_name=friendly_name + ) + participant = self.client.conversations.v1.conversations( + conversation.sid + ).participants.create(identity=identity_name) + + self.assertIsNotNone(conversation) + self.assertIsNotNone(participant) + self.assertEqual(conversation.friendly_name, friendly_name) + self.assertEqual(participant.identity, identity_name) + + remove_conversation = self.client.conversations.v1.conversations( + conversation.sid + ).delete() + self.assertIsNotNone(remove_conversation) + + def test_list_available_numbers(self): + toll_free_numbers = self.client.available_phone_numbers("US").toll_free.list( + limit=2 + ) + self.assertIsNotNone(toll_free_numbers) + self.assertEqual(len(toll_free_numbers), 2) + + def test_fetch_assistant(self): + assistant = self.client.assistants.v1.assistants(self.assistant_id).fetch() + self.assertIsNotNone(assistant) + self.assertEqual(assistant.account_sid, self.account_sid) + + def test_calling_twiml_string(self): + call = self.client.calls.create( + to=self.to_number, from_=self.from_number, twiml=str(self.voice_twiml) + ) + self.assertIsNotNone(call.sid) + + def test_calling_twiml_object(self): + call = self.client.calls.create( + to=self.to_number, from_=self.from_number, twiml=self.voice_twiml + ) + self.assertIsNotNone(call.sid) diff --git a/tests/cluster/test_webhook.py b/tests/cluster/test_webhook.py new file mode 100644 index 0000000000..307cf3d397 --- /dev/null +++ b/tests/cluster/test_webhook.py @@ -0,0 +1,109 @@ +import os + +from http.server import BaseHTTPRequestHandler +from twilio.request_validator import RequestValidator + + +class RequestHandler(BaseHTTPRequestHandler): + is_request_valid = False + validator = RequestValidator(os.environ["TWILIO_AUTH_TOKEN"]) + + def do_GET(self): + self.process_request() + + def do_POST(self): + self.process_request() + + def process_request(self): + self.signature_header = self.headers.get("x-twilio-signature") + self.url = ( + self.headers.get("x-forwarded-proto") + + "://" + + self.headers.get("host") + + self.path + ) + self.send_response(200) + self.end_headers() + RequestHandler.is_request_valid = RequestHandler.validator.validate( + uri=self.url, params=None, signature=self.signature_header + ) + + +# class WebhookTest(unittest.TestCase): +# def setUp(self): +# api_key = os.environ["TWILIO_API_KEY"] +# api_secret = os.environ["TWILIO_API_SECRET"] +# account_sid = os.environ["TWILIO_ACCOUNT_SID"] +# self.client = Client(api_key, api_secret, account_sid) +# +# portNumber = 7777 +# self.validation_server = HTTPServer(("", portNumber), RequestHandler) +# self.tunnel = ngrok.connect(portNumber) +# self.flow_sid = "" +# _thread.start_new_thread(self.start_http_server, ()) +# +# def start_http_server(self): +# self.validation_server.serve_forever() +# +# def tearDown(self): +# self.client.studio.v2.flows(self.flow_sid).delete() +# ngrok.kill() +# self.validation_server.shutdown() +# self.validation_server.server_close() +# +# def create_studio_flow(self, url, method): +# flow = self.client.studio.v2.flows.create( +# friendly_name="Python Cluster Test Flow", +# status="published", +# definition={ +# "description": "Studio Flow", +# "states": [ +# { +# "name": "Trigger", +# "type": "trigger", +# "transitions": [ +# { +# "next": "httpRequest", +# "event": "incomingRequest", +# }, +# ], +# "properties": {}, +# }, +# { +# "name": "httpRequest", +# "type": "make-http-request", +# "transitions": [], +# "properties": { +# "method": method, +# "content_type": "application/x-www-form-urlencoded;charset=utf-8", +# "url": url, +# }, +# }, +# ], +# "initial_state": "Trigger", +# "flags": { +# "allow_concurrent_calls": True, +# }, +# }, +# ) +# return flow +# +# def validate(self, method): +# flow = self.create_studio_flow(url=self.tunnel.public_url, method=method) +# self.flow_sid = flow.sid +# time.sleep(5) +# self.client.studio.v2.flows(self.flow_sid).executions.create( +# to="to", from_="from" +# ) +# +# def test_get(self): +# time.sleep(5) +# self.validate("GET") +# time.sleep(5) +# self.assertEqual(RequestHandler.is_request_valid, True) +# +# def test_post(self): +# time.sleep(5) +# self.validate("POST") +# time.sleep(5) +# self.assertEqual(RequestHandler.is_request_valid, True) diff --git a/tests/holodeck.py b/tests/holodeck.py new file mode 100644 index 0000000000..8f71514314 --- /dev/null +++ b/tests/holodeck.py @@ -0,0 +1,89 @@ +from twilio.base.exceptions import TwilioRestException +from twilio.http import HttpClient +from twilio.http.request import Request +import platform +from twilio import __version__ + + +class Hologram(object): + def __init__(self, request, response): + self.request = request + self.response = response + + +class Holodeck(HttpClient): + def __init__(self): + self._holograms = [] + self._requests = [] + + def mock(self, response, request=None): + request = request or Request() + self._holograms.append(Hologram(request, response)) + + @property + def requests(self): + return self._requests + + def add_standard_headers(self, request): + standard_headers = { + "User-Agent": "twilio-python/{} ({} {}) Python/{}".format( + __version__, + platform.system(), + platform.machine(), + platform.python_version(), + ), + "X-Twilio-Client": "python-{}".format(__version__), + "Accept": "application/json", + "Accept-Charset": "utf-8", + } + + if request.method == "POST" and "Content-Type" not in standard_headers: + standard_headers["Content-Type"] = "application/x-www-form-urlencoded" + + standard_headers.update(request.headers) + request.headers = standard_headers + return request + + def assert_has_request(self, request): + for req in self.requests: + if req == request or req == self.add_standard_headers(request): + return + + message = "\nHolodeck never received a request matching: \n + {}\n".format( + request + ) + if self._requests: + message += "Requests received:\n" + message += "\n".join(" * {}".format(r) for r in self.requests) + else: + message += "No Requests received" + + raise AssertionError(message) + + def request( + self, + method, + url, + params=None, + data=None, + headers=None, + auth=None, + timeout=None, + allow_redirects=False, + ): + request = Request(method, url, auth, params, data, headers) + + self._requests.append(request) + + for hologram in self._holograms: + if hologram.request == request: + return hologram.response + + message = "\nHolodeck has no hologram for: {}\n".format(request) + if self._holograms: + message += "Holograms loaded:\n" + message += "\n".join(" - {}".format(h.request) for h in self._holograms) + else: + message += "No Holograms loaded" + + raise TwilioRestException(404, url, message, method=method) diff --git a/tests/requirements.txt b/tests/requirements.txt index 8e9f8fbe9b..679f8e13d0 100644 --- a/tests/requirements.txt +++ b/tests/requirements.txt @@ -1,6 +1,14 @@ -sphinx -mock==0.8.0 -nose -coverage -nosexcover +Sphinx>=1.8.0 +mock +pytest +pytest-cov +aiounittest flake8 +wheel>=0.22.0 +cryptography +recommonmark +django +multidict +pyngrok +black +autoflake diff --git a/tests/resources/accounts_instance.json b/tests/resources/accounts_instance.json deleted file mode 100644 index 405f30d283..0000000000 --- a/tests/resources/accounts_instance.json +++ /dev/null @@ -1 +0,0 @@ -{"sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","friendly_name":"kyle.j.conroy@gmail.com's Account","status":"active","date_created":"Sun, 15 Mar 2009 02:08:47 +0000","date_updated":"Wed, 25 Aug 2010 01:30:09 +0000","auth_token":"AUTHTOKEN","type":"Full","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28.json","subresource_uris":{"available_phone_numbers":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/AvailablePhoneNumbers.json","calls":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls.json","conferences":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Conferences.json","incoming_phone_numbers":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/IncomingPhoneNumbers.json","notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications.json","outgoing_caller_ids":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/OutgoingCallerIds.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings.json","sandbox":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Sandbox.json","sms_messages":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages.json","transcriptions":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions.json"}} diff --git a/tests/resources/accounts_list.json b/tests/resources/accounts_list.json deleted file mode 100644 index 0172f47b7c..0000000000 --- a/tests/resources/accounts_list.json +++ /dev/null @@ -1 +0,0 @@ -{"page":0,"num_pages":1,"page_size":50,"total":4,"start":0,"end":3,"uri":"\/2010-04-01\/Accounts.json","first_page_uri":"\/2010-04-01\/Accounts.json?Page=0&PageSize=50","previous_page_uri":null,"next_page_uri":null,"last_page_uri":"\/2010-04-01\/Accounts.json?Page=0&PageSize=50","accounts":[{"sid":"ACea9234fced59a5733d2c1c1c69a83a28","friendly_name":"ChangeName","status":"active","auth_token":"AUTHTOKEN","date_created":"Thu, 17 Feb 2011 18:27:56 +0000","date_updated":"Thu, 17 Feb 2011 18:31:43 +0000","type":"Full","uri":"\/2010-04-01\/Accounts\/ACea9234fced59a5733d2c1c1c69a83a28.json","subresource_uris":{"available_phone_numbers":"\/2010-04-01\/Accounts\/ACea9234fced59a5733d2c1c1c69a83a28\/AvailablePhoneNumbers.json","calls":"\/2010-04-01\/Accounts\/ACea9234fced59a5733d2c1c1c69a83a28\/Calls.json","conferences":"\/2010-04-01\/Accounts\/ACea9234fced59a5733d2c1c1c69a83a28\/Conferences.json","incoming_phone_numbers":"\/2010-04-01\/Accounts\/ACea9234fced59a5733d2c1c1c69a83a28\/IncomingPhoneNumbers.json","notifications":"\/2010-04-01\/Accounts\/ACea9234fced59a5733d2c1c1c69a83a28\/Notifications.json","outgoing_caller_ids":"\/2010-04-01\/Accounts\/ACea9234fced59a5733d2c1c1c69a83a28\/OutgoingCallerIds.json","recordings":"\/2010-04-01\/Accounts\/ACea9234fced59a5733d2c1c1c69a83a28\/Recordings.json","sandbox":"\/2010-04-01\/Accounts\/ACea9234fced59a5733d2c1c1c69a83a28\/Sandbox.json","sms_messages":"\/2010-04-01\/Accounts\/ACea9234fced59a5733d2c1c1c69a83a28\/SMS\/Messages.json","transcriptions":"\/2010-04-01\/Accounts\/ACea9234fced59a5733d2c1c1c69a83a28\/Transcriptions.json"}},{"sid":"ACc4d3e1b7ed59a5733d2c1c1c69a83a28","friendly_name":"HEY","status":"active","auth_token":"AUTHTOKEN","date_created":"Fri, 11 Feb 2011 03:43:04 +0000","date_updated":"Fri, 11 Feb 2011 03:43:04 +0000","type":"Full","uri":"\/2010-04-01\/Accounts\/ACc4d3e1b7ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"available_phone_numbers":"\/2010-04-01\/Accounts\/ACc4d3e1b7ed59a5733d2c1c1c69a83a28\/AvailablePhoneNumbers.json","calls":"\/2010-04-01\/Accounts\/ACc4d3e1b7ed59a5733d2c1c1c69a83a28\/Calls.json","conferences":"\/2010-04-01\/Accounts\/ACc4d3e1b7ed59a5733d2c1c1c69a83a28\/Conferences.json","incoming_phone_numbers":"\/2010-04-01\/Accounts\/ACc4d3e1b7ed59a5733d2c1c1c69a83a28\/IncomingPhoneNumbers.json","notifications":"\/2010-04-01\/Accounts\/ACc4d3e1b7ed59a5733d2c1c1c69a83a28\/Notifications.json","outgoing_caller_ids":"\/2010-04-01\/Accounts\/ACc4d3e1b7ed59a5733d2c1c1c69a83a28\/OutgoingCallerIds.json","recordings":"\/2010-04-01\/Accounts\/ACc4d3e1b7ed59a5733d2c1c1c69a83a28\/Recordings.json","sandbox":"\/2010-04-01\/Accounts\/ACc4d3e1b7ed59a5733d2c1c1c69a83a28\/Sandbox.json","sms_messages":"\/2010-04-01\/Accounts\/ACc4d3e1b7ed59a5733d2c1c1c69a83a28\/SMS\/Messages.json","transcriptions":"\/2010-04-01\/Accounts\/ACc4d3e1b7ed59a5733d2c1c1c69a83a28\/Transcriptions.json"}},{"sid":"AC2c016433ed59a5733d2c1c1c69a83a28","friendly_name":"SubAccount Created at(415) 867-5309:19 pm","status":"active","auth_token":"AUTHTOKEN","date_created":"Fri, 11 Feb 2011 00:19:37 +0000","date_updated":"Fri, 11 Feb 2011 00:19:37 +0000","type":"Full","uri":"\/2010-04-01\/Accounts\/AC2c016433ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"available_phone_numbers":"\/2010-04-01\/Accounts\/AC2c016433ed59a5733d2c1c1c69a83a28\/AvailablePhoneNumbers.json","calls":"\/2010-04-01\/Accounts\/AC2c016433ed59a5733d2c1c1c69a83a28\/Calls.json","conferences":"\/2010-04-01\/Accounts\/AC2c016433ed59a5733d2c1c1c69a83a28\/Conferences.json","incoming_phone_numbers":"\/2010-04-01\/Accounts\/AC2c016433ed59a5733d2c1c1c69a83a28\/IncomingPhoneNumbers.json","notifications":"\/2010-04-01\/Accounts\/AC2c016433ed59a5733d2c1c1c69a83a28\/Notifications.json","outgoing_caller_ids":"\/2010-04-01\/Accounts\/AC2c016433ed59a5733d2c1c1c69a83a28\/OutgoingCallerIds.json","recordings":"\/2010-04-01\/Accounts\/AC2c016433ed59a5733d2c1c1c69a83a28\/Recordings.json","sandbox":"\/2010-04-01\/Accounts\/AC2c016433ed59a5733d2c1c1c69a83a28\/Sandbox.json","sms_messages":"\/2010-04-01\/Accounts\/AC2c016433ed59a5733d2c1c1c69a83a28\/SMS\/Messages.json","transcriptions":"\/2010-04-01\/Accounts\/AC2c016433ed59a5733d2c1c1c69a83a28\/Transcriptions.json"}},{"sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","friendly_name":"kyle.j.conroy@gmail.com's Account","status":"active","auth_token":"AUTHTOKEN","date_created":"Sun, 15 Mar 2009 02:08:47 +0000","date_updated":"Wed, 25 Aug 2010 01:30:09 +0000","type":"Full","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28.json","subresource_uris":{"available_phone_numbers":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/AvailablePhoneNumbers.json","calls":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls.json","conferences":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Conferences.json","incoming_phone_numbers":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/IncomingPhoneNumbers.json","notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications.json","outgoing_caller_ids":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/OutgoingCallerIds.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings.json","sandbox":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Sandbox.json","sms_messages":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages.json","transcriptions":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions.json"}}]} diff --git a/tests/resources/authorized_connect_apps.json b/tests/resources/authorized_connect_apps.json deleted file mode 100644 index 68e0263e44..0000000000 --- a/tests/resources/authorized_connect_apps.json +++ /dev/null @@ -1 +0,0 @@ -{"authorized_connect_apps":[{"connect_app_sid":"CN962cd12498b740a2a4c65d0e0774c2a9","account_sid":"AC8dfe2f2358cf421cb6134cf6f217c6a3","permissions":["get-all"],"connect_app_friendly_name":"YOUR MOM","connect_app_description":"alksjdfl;ajseifj;alsijfl;ajself;jasjfjas;lejflj","connect_app_company_name":"YOUR OTHER MOM","connect_app_homepage_url":"http:\/\/www.google.com","uri":"\/2010-04-01\/Accounts\/AC8dfe2f2358cf421cb6134cf6f217c6a3\/AuthorizedConnectApps\/CN962cd12498b740a2a4c65d0e0774c2a9.json"}],"page":0,"num_pages":1,"page_size":50,"total":1,"start":0,"end":0,"uri":"\/2010-04-01\/Accounts\/AC0a652c7f2c545a4f1fccc9b02d61b58b\/AuthorizedConnectApps.json","first_page_uri":"\/2010-04-01\/Accounts\/AC0a652c7f2c545a4f1fccc9b02d61b58b\/AuthorizedConnectApps.json?Page=0&PageSize=50","previous_page_uri":null,"next_page_uri":null,"last_page_uri":"\/2010-04-01\/Accounts\/AC0a652c7f2c545a4f1fccc9b02d61b58b\/AuthorizedConnectApps.json?Page=0&PageSize=50"} diff --git a/tests/resources/available_phone_numbers_ca_local.json b/tests/resources/available_phone_numbers_ca_local.json deleted file mode 100644 index 12c3e0a69c..0000000000 --- a/tests/resources/available_phone_numbers_ca_local.json +++ /dev/null @@ -1 +0,0 @@ -{"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/AvailablePhoneNumbers\/CA\/Local.json","available_phone_numbers":[{"friendly_name":"(415) 867-5309","phone_number":"+141586753097","lata":"888","rate_center":"VANCOUVER","latitude":"49.280000","longitude":"-123.110000","region":"BC","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753095","lata":"888","rate_center":"EDMONTON","latitude":"53.525000","longitude":"-113.458110","region":"AB","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753097","lata":null,"rate_center":null,"latitude":null,"longitude":null,"region":"Toronto (Ontario)","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753090","lata":"888","rate_center":"OTTAWA","latitude":"45.420560","longitude":"-75.692860","region":"ON","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753094","lata":"888","rate_center":"OTTAWA","latitude":"45.420000","longitude":"-75.690000","region":"ON","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753092","lata":"888","rate_center":"KANATA STITTSVILLE","latitude":"45.339170","longitude":"-75.899860","region":"ON","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753095","lata":"888","rate_center":"BORDEN ANGUS","latitude":"44.413060","longitude":"-79.682440","region":"ON","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753093","lata":"888","rate_center":"BORDEN ANGUS","latitude":"44.413060","longitude":"-79.682440","region":"ON","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753096","lata":"888","rate_center":"CALGARY","latitude":"50.980560","longitude":"-114.077570","region":"AB","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753097","lata":null,"rate_center":null,"latitude":null,"longitude":null,"region":"Toronto (Ontario)","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753099","lata":"888","rate_center":"HAMILTON","latitude":"43.000280","longitude":"-79.348060","region":"ON","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753096","lata":"888","rate_center":"HAMILTON","latitude":"43.250000","longitude":"-79.870000","region":"ON","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753095","lata":null,"rate_center":null,"latitude":null,"longitude":null,"region":"Toronto (Ontario)","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753090","lata":"888","rate_center":"LONDON","latitude":"42.984720","longitude":"-81.241380","region":"ON","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753098","lata":"888","rate_center":"HAMILTON","latitude":"43.250000","longitude":"-79.870000","region":"ON","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753095","lata":"888","rate_center":"HAMILTON","latitude":"43.250000","longitude":"-79.870000","region":"ON","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753099","lata":"888","rate_center":"HAMILTON","latitude":"43.250000","longitude":"-79.870000","region":"ON","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753094","lata":"888","rate_center":"HAMILTON","latitude":"43.250000","longitude":"-79.870000","region":"ON","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753095","lata":"888","rate_center":"WINNIPEG","latitude":"49.868610","longitude":"-97.150250","region":"MB","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753090","lata":"888","rate_center":"WINNIPEG","latitude":"49.868610","longitude":"-97.150250","region":"MB","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753091","lata":"888","rate_center":"MONTREAL","latitude":"45.502500","longitude":"-73.568050","region":"QC","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753094","lata":"888","rate_center":"HAMILTON","latitude":"43.250000","longitude":"-79.870000","region":"ON","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753094","lata":"888","rate_center":"MONTREAL","latitude":"45.502500","longitude":"-73.568050","region":"QC","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753097","lata":"888","rate_center":"WINNIPEG","latitude":"49.868610","longitude":"-97.150250","region":"MB","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753093","lata":"888","rate_center":"WINNIPEG","latitude":"49.868610","longitude":"-97.150250","region":"MB","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753096","lata":"888","rate_center":"WINNIPEG","latitude":"49.868610","longitude":"-97.150250","region":"MB","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753093","lata":"888","rate_center":"WINNIPEG","latitude":"49.868610","longitude":"-97.150250","region":"MB","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753094","lata":"888","rate_center":"HAMILTON","latitude":"43.250000","longitude":"-79.870000","region":"ON","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753091","lata":"888","rate_center":"WINNIPEG","latitude":"49.868610","longitude":"-97.150250","region":"MB","postal_code":null,"iso_country":"CA"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753097","lata":"888","rate_center":"MONTREAL","latitude":"45.502500","longitude":"-73.568050","region":"QC","postal_code":null,"iso_country":"CA"}]} diff --git a/tests/resources/available_phone_numbers_us_local.json b/tests/resources/available_phone_numbers_us_local.json deleted file mode 100644 index 29b895ed64..0000000000 --- a/tests/resources/available_phone_numbers_us_local.json +++ /dev/null @@ -1 +0,0 @@ -{"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/AvailablePhoneNumbers\/US\/Local.json?AreaCode=530","available_phone_numbers":[{"friendly_name":"(415) 867-5309","phone_number":"+141586753092","lata":"726","rate_center":"SMARTSVL","latitude":"39.210000","longitude":"-121.290000","region":"CA","postal_code":"95977","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753090","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753092","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753094","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753097","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753096","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753090","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753097","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753098","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753099","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753091","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753090","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753092","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753097","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753093","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753099","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753091","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753090","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753094","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753096","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753091","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753098","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753092","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753097","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753095","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753098","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753092","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753096","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753090","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753090","lata":"726","rate_center":"WOODLAND","latitude":"38.670000","longitude":"-121.760000","region":"CA","postal_code":"95695","iso_country":"US"}]} diff --git a/tests/resources/available_phone_numbers_us_tollfree.json b/tests/resources/available_phone_numbers_us_tollfree.json deleted file mode 100644 index f79628c073..0000000000 --- a/tests/resources/available_phone_numbers_us_tollfree.json +++ /dev/null @@ -1 +0,0 @@ -{"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/AvailablePhoneNumbers\/US\/TollFree.json","available_phone_numbers":[{"friendly_name":"(415) 867-5309","phone_number":"+141586753092","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753094","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753099","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753094","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753095","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753093","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753092","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753094","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753095","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753096","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753092","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753091","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753092","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753091","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753091","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753090","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753095","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753091","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753097","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753097","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753091","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753092","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753096","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753091","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753091","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753090","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753097","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753099","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753097","iso_country":"US"},{"friendly_name":"(415) 867-5309","phone_number":"+141586753094","iso_country":"US"}]} diff --git a/tests/resources/calls_instance.json b/tests/resources/calls_instance.json deleted file mode 100644 index 87ba4773ca..0000000000 --- a/tests/resources/calls_instance.json +++ /dev/null @@ -1 +0,0 @@ -{"sid":"CA47e13748ed59a5733d2c1c1c69a83a28","date_created":"Tue, 31 Aug 2010 20:36:28 +0000","date_updated":"Tue, 31 Aug 2010 20:36:44 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753091","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Tue, 31 Aug 2010 20:36:29 +0000","end_time":"Tue, 31 Aug 2010 20:36:44 +0000","duration":"15","price":"-0.03000","direction":"inbound","answered_by":null,"api_version":"2010-04-01","annotation":null,"forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA47e13748ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA47e13748ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA47e13748ed59a5733d2c1c1c69a83a28\/Recordings.json"}} diff --git a/tests/resources/calls_list.json b/tests/resources/calls_list.json deleted file mode 100644 index e32e1a92bf..0000000000 --- a/tests/resources/calls_list.json +++ /dev/null @@ -1 +0,0 @@ -{"page":0,"num_pages":11,"page_size":50,"total":509,"start":0,"end":49,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls.json","first_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls.json?Page=0&PageSize=50","previous_page_uri":null,"next_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls.json?Page=1&PageSize=50","last_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls.json?Page=10&PageSize=50","calls":[{"sid":"CA24388be8ed59a5733d2c1c1c69a83a28","date_created":"Tue, 15 Feb 2011 04:21:00 +0000","date_updated":"Tue, 15 Feb 2011 04:22:42 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753093","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Tue, 15 Feb 2011 04:21:00 +0000","end_time":"Tue, 15 Feb 2011 04:22:42 +0000","duration":"102","price":"-0.02000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA24388be8ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA24388be8ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA24388be8ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA7e3e8c74ed59a5733d2c1c1c69a83a28","date_created":"Sun, 13 Feb 2011 02:11:01 +0000","date_updated":"Sun, 13 Feb 2011 02:12:48 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753092","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Sun, 13 Feb 2011 02:11:02 +0000","end_time":"Sun, 13 Feb 2011 02:12:48 +0000","duration":"106","price":"-0.02000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA7e3e8c74ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA7e3e8c74ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA7e3e8c74ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CAfd85b7a9ed59a5733d2c1c1c69a83a28","date_created":"Sat, 12 Feb 2011 22:50:04 +0000","date_updated":"Sat, 12 Feb 2011 22:53:06 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753092","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Sat, 12 Feb 2011 22:50:05 +0000","end_time":"Sat, 12 Feb 2011 22:53:06 +0000","duration":"181","price":"-0.04000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAfd85b7a9ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAfd85b7a9ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAfd85b7a9ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CAde1bbe97ed59a5733d2c1c1c69a83a28","date_created":"Mon, 07 Feb 2011 18:37:20 +0000","date_updated":"Mon, 07 Feb 2011 18:37:43 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753092","from":"+141586753091","phone_number_sid":"PNd2ae06cced59a5733d2c1c1c69a83a28","status":"completed","start_time":"Mon, 07 Feb 2011 18:37:20 +0000","end_time":"Mon, 07 Feb 2011 18:37:43 +0000","duration":"23","price":"-0.03000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2008-08-01","forwarded_from":"+141586753092","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAde1bbe97ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAde1bbe97ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAde1bbe97ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA0cd446a4ed59a5733d2c1c1c69a83a28","date_created":"Thu, 03 Feb 2011 16:43:18 +0000","date_updated":"Thu, 03 Feb 2011 16:45:16 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753093","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Thu, 03 Feb 2011 16:43:19 +0000","end_time":"Thu, 03 Feb 2011 16:45:16 +0000","duration":"117","price":"-0.02000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA0cd446a4ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA0cd446a4ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA0cd446a4ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA1352817bed59a5733d2c1c1c69a83a28","date_created":"Sat, 29 Jan 2011 17:16:23 +0000","date_updated":"Sat, 29 Jan 2011 17:16:28 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753092","from":"+141586753095","phone_number_sid":"PNd2ae06cced59a5733d2c1c1c69a83a28","status":"completed","start_time":"Sat, 29 Jan 2011 17:16:23 +0000","end_time":"Sat, 29 Jan 2011 17:16:28 +0000","duration":"5","price":"-0.03000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2008-08-01","forwarded_from":"+141586753092","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA1352817bed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA1352817bed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA1352817bed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA5a1f0a21ed59a5733d2c1c1c69a83a28","date_created":"Sat, 18 Dec 2010 22:39:55 +0000","date_updated":"Sat, 18 Dec 2010 22:42:12 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753095","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Sat, 18 Dec 2010 22:39:56 +0000","end_time":"Sat, 18 Dec 2010 22:42:12 +0000","duration":"136","price":"-0.03000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA5a1f0a21ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA5a1f0a21ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA5a1f0a21ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA7e3a2fc4ed59a5733d2c1c1c69a83a28","date_created":"Sat, 18 Dec 2010 02:30:26 +0000","date_updated":"Sat, 18 Dec 2010 02:31:20 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753099","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Sat, 18 Dec 2010 02:30:26 +0000","end_time":"Sat, 18 Dec 2010 02:31:20 +0000","duration":"54","price":"-0.01000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA7e3a2fc4ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA7e3a2fc4ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA7e3a2fc4ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CAb109331eed59a5733d2c1c1c69a83a28","date_created":"Fri, 17 Dec 2010 23:59:51 +0000","date_updated":"Fri, 17 Dec 2010 23:59:53 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753096","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Fri, 17 Dec 2010 23:59:52 +0000","end_time":"Fri, 17 Dec 2010 23:59:53 +0000","duration":"1","price":"-0.01000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAb109331eed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAb109331eed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAb109331eed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA0645767bed59a5733d2c1c1c69a83a28","date_created":"Sun, 05 Dec 2010 21:00:25 +0000","date_updated":"Sun, 05 Dec 2010 21:01:48 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753098","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Sun, 05 Dec 2010 21:00:25 +0000","end_time":"Sun, 05 Dec 2010 21:01:48 +0000","duration":"83","price":"-0.02000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA0645767bed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA0645767bed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA0645767bed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA43b8dc82ed59a5733d2c1c1c69a83a28","date_created":"Sat, 20 Nov 2010 21:51:53 +0000","date_updated":"Sat, 20 Nov 2010 21:52:08 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753093","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Sat, 20 Nov 2010 21:51:54 +0000","end_time":"Sat, 20 Nov 2010 21:52:08 +0000","duration":"14","price":"-0.01000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA43b8dc82ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA43b8dc82ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA43b8dc82ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA7a05f642ed59a5733d2c1c1c69a83a28","date_created":"Fri, 19 Nov 2010 23:21:16 +0000","date_updated":"Fri, 19 Nov 2010 23:22:00 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753097","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Fri, 19 Nov 2010 23:21:19 +0000","end_time":"Fri, 19 Nov 2010 23:22:00 +0000","duration":"41","price":"-0.01000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA7a05f642ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA7a05f642ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA7a05f642ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA41e7078eed59a5733d2c1c1c69a83a28","date_created":"Thu, 11 Nov 2010 04:13:52 +0000","date_updated":"Thu, 11 Nov 2010 04:16:14 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753093","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Thu, 11 Nov 2010 04:13:53 +0000","end_time":"Thu, 11 Nov 2010 04:16:14 +0000","duration":"141","price":"-0.03000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA41e7078eed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA41e7078eed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA41e7078eed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA162c8b53ed59a5733d2c1c1c69a83a28","date_created":"Thu, 04 Nov 2010 21:00:19 +0000","date_updated":"Thu, 04 Nov 2010 21:01:13 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753092","from":"+141586753094","phone_number_sid":"PNd2ae06cced59a5733d2c1c1c69a83a28","status":"completed","start_time":"Thu, 04 Nov 2010 21:00:19 +0000","end_time":"Thu, 04 Nov 2010 21:01:13 +0000","duration":"54","price":"-0.03000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2008-08-01","forwarded_from":"+141586753092","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA162c8b53ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA162c8b53ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA162c8b53ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA5c0de550ed59a5733d2c1c1c69a83a28","date_created":"Thu, 28 Oct 2010 11:55:59 +0000","date_updated":"Thu, 28 Oct 2010 11:58:23 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753093","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Thu, 28 Oct 2010 11:56:00 +0000","end_time":"Thu, 28 Oct 2010 11:58:23 +0000","duration":"143","price":"-0.03000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA5c0de550ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA5c0de550ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA5c0de550ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CAee5e9f61ed59a5733d2c1c1c69a83a28","date_created":"Sat, 16 Oct 2010 05:25:49 +0000","date_updated":"Sat, 16 Oct 2010 05:27:44 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753091","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Sat, 16 Oct 2010 05:25:49 +0000","end_time":"Sat, 16 Oct 2010 05:27:44 +0000","duration":"115","price":"-0.02000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAee5e9f61ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAee5e9f61ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAee5e9f61ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA70ba7140ed59a5733d2c1c1c69a83a28","date_created":"Wed, 06 Oct 2010 18:27:45 +0000","date_updated":"Wed, 06 Oct 2010 18:29:07 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753090","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Wed, 06 Oct 2010 18:27:45 +0000","end_time":"Wed, 06 Oct 2010 18:29:07 +0000","duration":"82","price":"-0.02000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA70ba7140ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA70ba7140ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA70ba7140ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CAb381aeaded59a5733d2c1c1c69a83a28","date_created":"Wed, 06 Oct 2010 16:51:06 +0000","date_updated":"Wed, 06 Oct 2010 16:53:24 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753090","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Wed, 06 Oct 2010 16:51:07 +0000","end_time":"Wed, 06 Oct 2010 16:53:24 +0000","duration":"137","price":"-0.03000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAb381aeaded59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAb381aeaded59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAb381aeaded59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA475e55a5ed59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Oct 2010 02:28:12 +0000","date_updated":"Mon, 04 Oct 2010 02:30:48 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753098","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Mon, 04 Oct 2010 02:28:12 +0000","end_time":"Mon, 04 Oct 2010 02:30:48 +0000","duration":"156","price":"-0.03000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA475e55a5ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA475e55a5ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA475e55a5ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CAef36592ded59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Oct 2010 02:25:03 +0000","date_updated":"Mon, 04 Oct 2010 02:26:39 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753098","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Mon, 04 Oct 2010 02:25:03 +0000","end_time":"Mon, 04 Oct 2010 02:26:39 +0000","duration":"96","price":"-0.02000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAef36592ded59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAef36592ded59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAef36592ded59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA7c3fe40aed59a5733d2c1c1c69a83a28","date_created":"Wed, 22 Sep 2010 21:23:54 +0000","date_updated":"Wed, 22 Sep 2010 21:24:24 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753091","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Wed, 22 Sep 2010 21:23:55 +0000","end_time":"Wed, 22 Sep 2010 21:24:24 +0000","duration":"29","price":"-0.01000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA7c3fe40aed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA7c3fe40aed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA7c3fe40aed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA49972ebaed59a5733d2c1c1c69a83a28","date_created":"Wed, 22 Sep 2010 12:41:06 +0000","date_updated":"Wed, 22 Sep 2010 12:42:25 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753092","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Wed, 22 Sep 2010 12:41:07 +0000","end_time":"Wed, 22 Sep 2010 12:42:25 +0000","duration":"78","price":"-0.02000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA49972ebaed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA49972ebaed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA49972ebaed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA77ddc8d5ed59a5733d2c1c1c69a83a28","date_created":"Tue, 21 Sep 2010 14:46:33 +0000","date_updated":"Tue, 21 Sep 2010 14:48:11 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753090","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Tue, 21 Sep 2010 14:46:34 +0000","end_time":"Tue, 21 Sep 2010 14:48:11 +0000","duration":"97","price":"-0.02000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA77ddc8d5ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA77ddc8d5ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA77ddc8d5ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA75e5238aed59a5733d2c1c1c69a83a28","date_created":"Mon, 20 Sep 2010 23:52:57 +0000","date_updated":"Mon, 20 Sep 2010 23:54:20 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753097","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Mon, 20 Sep 2010 23:52:57 +0000","end_time":"Mon, 20 Sep 2010 23:54:20 +0000","duration":"83","price":"-0.02000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA75e5238aed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA75e5238aed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA75e5238aed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA59b1f84ded59a5733d2c1c1c69a83a28","date_created":"Mon, 20 Sep 2010 23:25:54 +0000","date_updated":"Mon, 20 Sep 2010 23:26:42 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753098","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Mon, 20 Sep 2010 23:25:55 +0000","end_time":"Mon, 20 Sep 2010 23:26:42 +0000","duration":"47","price":"-0.01000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA59b1f84ded59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA59b1f84ded59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA59b1f84ded59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CAd9918e25ed59a5733d2c1c1c69a83a28","date_created":"Sun, 19 Sep 2010 02:34:05 +0000","date_updated":"Sun, 19 Sep 2010 02:35:54 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753096","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Sun, 19 Sep 2010 02:34:09 +0000","end_time":"Sun, 19 Sep 2010 02:35:54 +0000","duration":"105","price":"-0.02000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAd9918e25ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAd9918e25ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAd9918e25ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA39218e45ed59a5733d2c1c1c69a83a28","date_created":"Sat, 18 Sep 2010 02:43:46 +0000","date_updated":"Sat, 18 Sep 2010 02:46:17 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753098","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Sat, 18 Sep 2010 02:43:46 +0000","end_time":"Sat, 18 Sep 2010 02:46:17 +0000","duration":"151","price":"-0.03000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA39218e45ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA39218e45ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA39218e45ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CAa26452b2ed59a5733d2c1c1c69a83a28","date_created":"Fri, 17 Sep 2010 12:06:11 +0000","date_updated":"Fri, 17 Sep 2010 12:07:55 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753092","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Fri, 17 Sep 2010 12:06:11 +0000","end_time":"Fri, 17 Sep 2010 12:07:55 +0000","duration":"104","price":"-0.02000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAa26452b2ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAa26452b2ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAa26452b2ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CAcffd776ced59a5733d2c1c1c69a83a28","date_created":"Mon, 13 Sep 2010 20:14:56 +0000","date_updated":"Mon, 13 Sep 2010 20:18:23 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753093","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Mon, 13 Sep 2010 20:14:57 +0000","end_time":"Mon, 13 Sep 2010 20:18:23 +0000","duration":"206","price":"-0.12000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAcffd776ced59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAcffd776ced59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAcffd776ced59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA105cb7b2ed59a5733d2c1c1c69a83a28","date_created":"Mon, 13 Sep 2010 20:05:31 +0000","date_updated":"Mon, 13 Sep 2010 20:06:56 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753093","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Mon, 13 Sep 2010 20:05:32 +0000","end_time":"Mon, 13 Sep 2010 20:06:56 +0000","duration":"84","price":"-0.06000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA105cb7b2ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA105cb7b2ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA105cb7b2ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA40f819aaed59a5733d2c1c1c69a83a28","date_created":"Mon, 13 Sep 2010 20:01:29 +0000","date_updated":"Mon, 13 Sep 2010 20:02:05 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753093","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Mon, 13 Sep 2010 20:01:30 +0000","end_time":"Mon, 13 Sep 2010 20:02:05 +0000","duration":"35","price":"-0.03000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA40f819aaed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA40f819aaed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA40f819aaed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA1b79cdcaed59a5733d2c1c1c69a83a28","date_created":"Mon, 13 Sep 2010 19:20:14 +0000","date_updated":"Mon, 13 Sep 2010 19:22:15 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753093","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Mon, 13 Sep 2010 19:20:15 +0000","end_time":"Mon, 13 Sep 2010 19:22:15 +0000","duration":"120","price":"-0.06000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA1b79cdcaed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA1b79cdcaed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA1b79cdcaed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA708b76b6ed59a5733d2c1c1c69a83a28","date_created":"Mon, 13 Sep 2010 19:15:32 +0000","date_updated":"Mon, 13 Sep 2010 19:16:48 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753093","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Mon, 13 Sep 2010 19:15:33 +0000","end_time":"Mon, 13 Sep 2010 19:16:48 +0000","duration":"75","price":"-0.06000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA708b76b6ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA708b76b6ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA708b76b6ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CAc17624f4ed59a5733d2c1c1c69a83a28","date_created":"Mon, 13 Sep 2010 18:59:42 +0000","date_updated":"Mon, 13 Sep 2010 19:00:30 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753093","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Mon, 13 Sep 2010 18:59:43 +0000","end_time":"Mon, 13 Sep 2010 19:00:30 +0000","duration":"47","price":"-0.03000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAc17624f4ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAc17624f4ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAc17624f4ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA00c95feced59a5733d2c1c1c69a83a28","date_created":"Mon, 06 Sep 2010 19:41:04 +0000","date_updated":"Mon, 06 Sep 2010 19:41:38 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753092","from":"+141586753097","phone_number_sid":"PNd2ae06cced59a5733d2c1c1c69a83a28","status":"completed","start_time":"Mon, 06 Sep 2010 19:41:04 +0000","end_time":"Mon, 06 Sep 2010 19:41:38 +0000","duration":"34","price":"-0.05000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2008-08-01","forwarded_from":"+141586753092","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA00c95feced59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA00c95feced59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA00c95feced59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA3608545aed59a5733d2c1c1c69a83a28","date_created":"Mon, 06 Sep 2010 03:39:31 +0000","date_updated":"Mon, 06 Sep 2010 03:40:22 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753095","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Mon, 06 Sep 2010 03:39:31 +0000","end_time":"Mon, 06 Sep 2010 03:40:22 +0000","duration":"51","price":"-0.03000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA3608545aed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA3608545aed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA3608545aed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA3683c083ed59a5733d2c1c1c69a83a28","date_created":"Sat, 04 Sep 2010 15:33:10 +0000","date_updated":"Sat, 04 Sep 2010 15:33:40 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753096","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Sat, 04 Sep 2010 15:33:11 +0000","end_time":"Sat, 04 Sep 2010 15:33:40 +0000","duration":"29","price":"-0.03000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA3683c083ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA3683c083ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA3683c083ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA057f0582ed59a5733d2c1c1c69a83a28","date_created":"Thu, 02 Sep 2010 13:34:21 +0000","date_updated":"Thu, 02 Sep 2010 13:36:27 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753091","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Thu, 02 Sep 2010 13:34:21 +0000","end_time":"Thu, 02 Sep 2010 13:36:27 +0000","duration":"126","price":"-0.09000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA057f0582ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA057f0582ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA057f0582ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA73e8db19ed59a5733d2c1c1c69a83a28","date_created":"Thu, 02 Sep 2010 07:12:34 +0000","date_updated":"Thu, 02 Sep 2010 07:13:21 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753093","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Thu, 02 Sep 2010 07:12:35 +0000","end_time":"Thu, 02 Sep 2010 07:13:21 +0000","duration":"46","price":"-0.03000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA73e8db19ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA73e8db19ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA73e8db19ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA323dc489ed59a5733d2c1c1c69a83a28","date_created":"Thu, 02 Sep 2010 01:02:58 +0000","date_updated":"Thu, 02 Sep 2010 01:04:11 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753097","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Thu, 02 Sep 2010 01:02:58 +0000","end_time":"Thu, 02 Sep 2010 01:04:11 +0000","duration":"73","price":"-0.06000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA323dc489ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA323dc489ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA323dc489ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA4ab28a55ed59a5733d2c1c1c69a83a28","date_created":"Thu, 02 Sep 2010 00:21:35 +0000","date_updated":"Thu, 02 Sep 2010 00:22:57 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753097","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Thu, 02 Sep 2010 00:21:36 +0000","end_time":"Thu, 02 Sep 2010 00:22:57 +0000","duration":"81","price":"-0.06000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA4ab28a55ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA4ab28a55ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA4ab28a55ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CAcb7e6575ed59a5733d2c1c1c69a83a28","date_created":"Wed, 01 Sep 2010 16:43:18 +0000","date_updated":"Wed, 01 Sep 2010 16:44:02 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753091","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Wed, 01 Sep 2010 16:43:18 +0000","end_time":"Wed, 01 Sep 2010 16:44:02 +0000","duration":"44","price":"-0.03000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAcb7e6575ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAcb7e6575ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAcb7e6575ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CAbe6cf023ed59a5733d2c1c1c69a83a28","date_created":"Wed, 01 Sep 2010 16:37:30 +0000","date_updated":"Wed, 01 Sep 2010 16:40:15 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753098","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Wed, 01 Sep 2010 16:37:30 +0000","end_time":"Wed, 01 Sep 2010 16:40:15 +0000","duration":"165","price":"-0.09000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAbe6cf023ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAbe6cf023ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAbe6cf023ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA31fd3b90ed59a5733d2c1c1c69a83a28","date_created":"Wed, 01 Sep 2010 15:15:20 +0000","date_updated":"Wed, 01 Sep 2010 15:16:14 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753098","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Wed, 01 Sep 2010 15:15:21 +0000","end_time":"Wed, 01 Sep 2010 15:16:14 +0000","duration":"53","price":"-0.03000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA31fd3b90ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA31fd3b90ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA31fd3b90ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CAb2eff601ed59a5733d2c1c1c69a83a28","date_created":"Wed, 01 Sep 2010 14:55:56 +0000","date_updated":"Wed, 01 Sep 2010 14:56:24 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753090","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Wed, 01 Sep 2010 14:55:56 +0000","end_time":"Wed, 01 Sep 2010 14:56:24 +0000","duration":"28","price":"-0.03000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAb2eff601ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAb2eff601ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAb2eff601ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CAc1a4a131ed59a5733d2c1c1c69a83a28","date_created":"Wed, 01 Sep 2010 02:18:43 +0000","date_updated":"Wed, 01 Sep 2010 02:21:59 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753096","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Wed, 01 Sep 2010 02:18:44 +0000","end_time":"Wed, 01 Sep 2010 02:21:59 +0000","duration":"195","price":"-0.12000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAc1a4a131ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAc1a4a131ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAc1a4a131ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA375c9b86ed59a5733d2c1c1c69a83a28","date_created":"Tue, 31 Aug 2010 21:53:52 +0000","date_updated":"Tue, 31 Aug 2010 21:55:54 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753093","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Tue, 31 Aug 2010 21:53:52 +0000","end_time":"Tue, 31 Aug 2010 21:55:54 +0000","duration":"122","price":"-0.09000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA375c9b86ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA375c9b86ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA375c9b86ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CAb2c5127ced59a5733d2c1c1c69a83a28","date_created":"Tue, 31 Aug 2010 20:55:34 +0000","date_updated":"Tue, 31 Aug 2010 20:56:30 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753094","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Tue, 31 Aug 2010 20:55:35 +0000","end_time":"Tue, 31 Aug 2010 20:56:30 +0000","duration":"55","price":"-0.03000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAb2c5127ced59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAb2c5127ced59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CAb2c5127ced59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA7eb54ab5ed59a5733d2c1c1c69a83a28","date_created":"Tue, 31 Aug 2010 20:49:54 +0000","date_updated":"Tue, 31 Aug 2010 20:51:15 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753098","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Tue, 31 Aug 2010 20:49:54 +0000","end_time":"Tue, 31 Aug 2010 20:51:15 +0000","duration":"81","price":"-0.06000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA7eb54ab5ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA7eb54ab5ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA7eb54ab5ed59a5733d2c1c1c69a83a28\/Recordings.json"}},{"sid":"CA47e13748ed59a5733d2c1c1c69a83a28","date_created":"Tue, 31 Aug 2010 20:36:28 +0000","date_updated":"Tue, 31 Aug 2010 20:36:44 +0000","parent_call_sid":null,"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753091","phone_number_sid":"PN995e2937ed59a5733d2c1c1c69a83a28","status":"completed","start_time":"Tue, 31 Aug 2010 20:36:29 +0000","end_time":"Tue, 31 Aug 2010 20:36:44 +0000","duration":"15","price":"-0.03000","direction":"inbound","answered_by":null,"annotation":null,"api_version":"2010-04-01","forwarded_from":"+141586753093","group_sid":null,"caller_name":null,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA47e13748ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"notifications":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA47e13748ed59a5733d2c1c1c69a83a28\/Notifications.json","recordings":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls\/CA47e13748ed59a5733d2c1c1c69a83a28\/Recordings.json"}}]} diff --git a/tests/resources/conferences_instance.json b/tests/resources/conferences_instance.json deleted file mode 100644 index 445d7edb08..0000000000 --- a/tests/resources/conferences_instance.json +++ /dev/null @@ -1 +0,0 @@ -{"sid":"CFe3bb5bfbed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","friendly_name":"AHH YEAH","status":"completed","date_created":"Fri, 18 Feb 2011 19:26:50 +0000","api_version":"2008-08-01","date_updated":"Fri, 18 Feb 2011 19:27:33 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Conferences\/CFe3bb5bfbed59a5733d2c1c1c69a83a28.json","subresource_uris":{"participants":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Conferences\/CFe3bb5bfbed59a5733d2c1c1c69a83a28\/Participants.json"}} diff --git a/tests/resources/conferences_list.json b/tests/resources/conferences_list.json deleted file mode 100644 index 7898253007..0000000000 --- a/tests/resources/conferences_list.json +++ /dev/null @@ -1 +0,0 @@ -{"page":0,"num_pages":1,"page_size":50,"total":3,"start":0,"end":2,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Conferences.json","first_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Conferences.json?Page=0&PageSize=50","previous_page_uri":null,"next_page_uri":null,"last_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Conferences.json?Page=0&PageSize=50","conferences":[{"sid":"CFf2fe8498ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","friendly_name":"AHH YEAH","status":"in-progress","date_created":"Fri, 18 Feb 2011 21:07:19 +0000","api_version":"2008-08-01","date_updated":"Fri, 18 Feb 2011 21:07:20 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Conferences\/CFf2fe8498ed59a5733d2c1c1c69a83a28.json","subresource_uris":{"participants":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Conferences\/CFf2fe8498ed59a5733d2c1c1c69a83a28\/Participants.json"}},{"sid":"CFefb79a9aed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","friendly_name":"AHH YEAH","status":"completed","date_created":"Fri, 18 Feb 2011 20:29:34 +0000","api_version":"2008-08-01","date_updated":"Fri, 18 Feb 2011 21:02:17 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Conferences\/CFefb79a9aed59a5733d2c1c1c69a83a28.json","subresource_uris":{"participants":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Conferences\/CFefb79a9aed59a5733d2c1c1c69a83a28\/Participants.json"}},{"sid":"CFe3bb5bfbed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","friendly_name":"AHH YEAH","status":"completed","date_created":"Fri, 18 Feb 2011 19:26:50 +0000","api_version":"2008-08-01","date_updated":"Fri, 18 Feb 2011 19:27:33 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Conferences\/CFe3bb5bfbed59a5733d2c1c1c69a83a28.json","subresource_uris":{"participants":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Conferences\/CFe3bb5bfbed59a5733d2c1c1c69a83a28\/Participants.json"}}]} diff --git a/tests/resources/incoming_phone_numbers_instance.json b/tests/resources/incoming_phone_numbers_instance.json deleted file mode 100644 index e107d3ed52..0000000000 --- a/tests/resources/incoming_phone_numbers_instance.json +++ /dev/null @@ -1 +0,0 @@ -{"sid":"PNd2ae06cced59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","friendly_name":"An example Twilio Application","phone_number":"+141586753092","voice_url":"http:\/\/apps.dev.twilio.com\/~kjconroy\/mobilemusical\/index.php","voice_method":"POST","voice_fallback_url":"","voice_fallback_method":null,"voice_caller_id_lookup":false,"date_created":"Sat, 13 Jun 2009 01:00:39 +0000","date_updated":"Tue, 04 May 2010 09:33:02 +0000","sms_url":"","sms_method":null,"sms_fallback_url":"","sms_fallback_method":null,"capabilities":{"voice":true,"sms":false},"status_callback":null,"status_callback_method":null,"api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/IncomingPhoneNumbers\/PNd2ae06cced59a5733d2c1c1c69a83a28.json"} diff --git a/tests/resources/incoming_phone_numbers_list.json b/tests/resources/incoming_phone_numbers_list.json deleted file mode 100644 index 6c51f41006..0000000000 --- a/tests/resources/incoming_phone_numbers_list.json +++ /dev/null @@ -1 +0,0 @@ -{"page":0,"num_pages":1,"page_size":50,"total":3,"start":0,"end":2,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/IncomingPhoneNumbers.json","first_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/IncomingPhoneNumbers.json?Page=0&PageSize=50","previous_page_uri":null,"next_page_uri":null,"last_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/IncomingPhoneNumbers.json?Page=0&PageSize=50","incoming_phone_numbers":[{"sid":"PN81d4ed70ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","friendly_name":"(415) 867-5309","phone_number":"+141586753096","voice_url":"","voice_method":"POST","voice_fallback_url":"","voice_fallback_method":"POST","voice_caller_id_lookup":true,"date_created":"Tue, 15 Feb 2011 01:04:42 +0000","date_updated":"Tue, 15 Feb 2011 01:36:01 +0000","sms_url":"","sms_method":"POST","sms_fallback_url":"","sms_fallback_method":"POST","capabilities":{"voice":true,"sms":true},"status_callback":null,"status_callback_method":null,"api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/IncomingPhoneNumbers\/PN81d4ed70ed59a5733d2c1c1c69a83a28.json"},{"sid":"PN995e2937ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","friendly_name":"The Twilio Welcome Demo","phone_number":"+141586753093","voice_url":"http:\/\/voiceforms4000.appspot.com\/twiml","voice_method":"GET","voice_fallback_url":"","voice_fallback_method":"POST","voice_caller_id_lookup":false,"date_created":"Mon, 28 Dec 2009 22:40:21 +0000","date_updated":"Tue, 31 Aug 2010 12:52:42 +0000","sms_url":"http:\/\/apps.dev.twilio.com\/~kjconroy\/sms\/sms-conversation.php","sms_method":"GET","sms_fallback_url":"","sms_fallback_method":"GET","capabilities":{"voice":true,"sms":true},"status_callback":"","status_callback_method":"POST","api_version":"2010-04-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/IncomingPhoneNumbers\/PN995e2937ed59a5733d2c1c1c69a83a28.json"},{"sid":"PNd2ae06cced59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","friendly_name":"An example Twilio Application","phone_number":"+141586753092","voice_url":"http:\/\/apps.dev.twilio.com\/~kjconroy\/mobilemusical\/index.php","voice_method":"POST","voice_fallback_url":"","voice_fallback_method":null,"voice_caller_id_lookup":false,"date_created":"Sat, 13 Jun 2009 01:00:39 +0000","date_updated":"Tue, 04 May 2010 09:33:02 +0000","sms_url":"","sms_method":null,"sms_fallback_url":"","sms_fallback_method":null,"capabilities":{"voice":true,"sms":false},"status_callback":null,"status_callback_method":null,"api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/IncomingPhoneNumbers\/PNd2ae06cced59a5733d2c1c1c69a83a28.json"}]} diff --git a/tests/resources/members_instance.json b/tests/resources/members_instance.json deleted file mode 100644 index d98b38e0c4..0000000000 --- a/tests/resources/members_instance.json +++ /dev/null @@ -1 +0,0 @@ -{"call_sid": "CAaaf2e9ded94aba3e57c42a3d55be6ff2", "date_enqueued": "Tue, 07 Aug 2012 22:57:41 +0000", "wait_time": 143, "current_position": 1, "uri": "/2010-04-01/Accounts/ACf5af0ea0c9955b67b39c52fb11ee6e69/Queues/QUe675e1913214346f48a9d2296a8d3788/Members/CAaaf2e9ded94aba3e57c42a3d55be6ff2.json"} diff --git a/tests/resources/members_list.json b/tests/resources/members_list.json deleted file mode 100644 index 2e6e249f48..0000000000 --- a/tests/resources/members_list.json +++ /dev/null @@ -1 +0,0 @@ -{"first_page_uri": "/2010-04-01/Accounts/ACf5af0ea0c9955b67b39c52fb11ee6e69/Queues/QUe675e1913214346f48a9d2296a8d3788/Members.json?Page=0&PageSize=50", "num_pages": 1, "previous_page_uri": null, "last_page_uri": "/2010-04-01/Accounts/ACf5af0ea0c9955b67b39c52fb11ee6e69/Queues/QUe675e1913214346f48a9d2296a8d3788/Members.json?Page=0&PageSize=50", "uri": "/2010-04-01/Accounts/ACf5af0ea0c9955b67b39c52fb11ee6e69/Queues/QUe675e1913214346f48a9d2296a8d3788/Members.json", "page_size": 50, "start": 0, "next_page_uri": null, "end": 0, "total": 1, "queue_members": [{"call_sid": "CAaaf2e9ded94aba3e57c42a3d55be6ff2", "date_enqueued": "Tue, 07 Aug 2012 22:57:41 +0000", "wait_time": 124, "current_position": 1, "uri": "/2010-04-01/Accounts/ACf5af0ea0c9955b67b39c52fb11ee6e69/Queues/QUe675e1913214346f48a9d2296a8d3788/Members/CAaaf2e9ded94aba3e57c42a3d55be6ff2.json"}], "page": 0} diff --git a/tests/resources/notifications_instance.json b/tests/resources/notifications_instance.json deleted file mode 100644 index 166a0275c0..0000000000 --- a/tests/resources/notifications_instance.json +++ /dev/null @@ -1 +0,0 @@ -{"sid":"NO9329e5a4ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA40f819aaed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fvoiceforms4000.appspot.com%2Ftwiml","message_date":"Mon, 13 Sep 2010 20:02:00 +0000","response_body":"\n\n\n500 Server Error<\/title>\n<\/head>\n<body text=#000000 bgcolor=#ffffff>\n<h1>Error: Server Error<\/h1>\n<h2>The server encountered an error and could not complete your request.<p>If the problem persists, please <A HREF=\"http:\/\/code.google.com\/appengine\/community.html\">report<\/A> your problem and mention this error message and the query that caused it.<\/h2>\n<h2><\/h2>\n<\/body><\/html>\n","request_method":"get","request_url":"https:\/\/voiceforms4000.appspot.com\/twiml\/9436\/question\/0","request_variables":"AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&ToZip=94937&ToCity=INVERNESS&ToState=CA&Called=%2B14156694923&To=%2B14156694923&ToCountry=US&CalledZip=94937&Direction=inbound&ApiVersion=2010-04-01&Caller=%2B17378742833&CalledCity=INVERNESS&CalledCountry=US&CallSid=CA40f819aaed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B17378742833","response_headers":"Date=Mon%2C+13+Sep+2010+20%3A02%3A00+GMT&Content-Length=466&Connection=close&Content-Type=text%2Fhtml%3B+charset%3DUTF-8&Server=Google+Frontend","date_created":"Mon, 13 Sep 2010 20:02:01 +0000","api_version":"2008-08-01","date_updated":"Mon, 13 Sep 2010 20:02:01 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO9329e5a4ed59a5733d2c1c1c69a83a28.json"} diff --git a/tests/resources/notifications_list.json b/tests/resources/notifications_list.json deleted file mode 100644 index 0c9e6dd6e0..0000000000 --- a/tests/resources/notifications_list.json +++ /dev/null @@ -1 +0,0 @@ -{"page":0,"num_pages":4,"page_size":50,"total":156,"start":0,"end":49,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications.json","first_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications.json?Page=0&PageSize=50","previous_page_uri":null,"next_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications.json?Page=1&PageSize=50","last_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications.json?Page=3&PageSize=50","notifications":[{"sid":"NOf43946e6ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA475e55a5ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=414&ErrorCode=11200&url=http%3A%2F%2Fvoiceforms4000.appspot.com%2Ftwiml","message_date":"Mon, 04 Oct 2010 02:30:48 +0000","request_method":"get","request_url":"https:\/\/voiceforms4000.appspot.com\/twiml\/1468\/question\/8?AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&ToZip=94937&FromState=CA&Called=%2B14156694923&FromCountry=US&CallerCountry=US&CalledZip=94937&Direction=inbound&FromCity=ESCONDIDO&CalledCountry=US&CallerState=CA&CallSid=CA475e55a5ed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B17607058888&CallerZip=92029&FromZip=92029&CallStatus=in-progress&ToCity=INVERNESS&ToState=CA&To=%2B14156694923&ToCountry=US&CallerCity=ESCONDIDO&ApiVersion=2010-04-01&Caller=%2B17607058888&CalledCity=INVERNESS&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&ToZip=94937&FromState=CA&Called=%2B14156694923&FromCountry=US&CallerCountry=US&CalledZip=94937&Direction=inbound&FromCity=ESCONDIDO&CalledCountry=US&CallerState=CA&CallSid=CA475e55a5ed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B17607058888&CallerZip=92029&FromZip=92029&CallStatus=in-progress&ToCity=INVERNESS&ToState=CA&To=%2B14156694923&ToCountry=US&CallerCity=ESCONDIDO&ApiVersion=2010-04-01&Caller=%2B17607058888&CalledCity=INVERNESS&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&ToZip=94937&FromState=CA&Called=%2B14156694923&FromCountry=US&CallerCountry=US&CalledZip=94937&Direction=inbound&FromCity=ESCONDIDO&CalledCountry=US&CallerState=CA&CallSid=CA475e55a5ed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B17607058888&CallerZip=92029&FromZip=92029&CallStatus=in-progress&ToCity=INVERNESS&ToState=CA&To=%2B14156694923&ToCountry=US&CallerCity=ESCONDIDO&ApiVersion=2010-04-01&Caller=%2B17607058888&CalledCity=INVERNESS&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&ToZip=94937&FromState=CA&Called=%2B14156694923&FromCountry=US&CallerCountry=US&CalledZip=94937&Direction=inbound&FromCity=ESCONDIDO&CalledCountry=US&CallerState=CA&CallSid=CA475e55a5ed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B17607058888&CallerZip=92029&FromZip=92029&CallStatus=in-progress&ToCity=INVERNESS&ToState=CA&To=%2B14156694923&ToCountry=US&CallerCity=ESCONDIDO&ApiVersion=2010-04-01&Caller=%2B17607058888&CalledCity=INVERNESS","date_created":"Mon, 04 Oct 2010 02:30:48 +0000","api_version":"2008-08-01","date_updated":"Mon, 04 Oct 2010 02:30:48 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NOf43946e6ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO9329e5a4ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA40f819aaed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fvoiceforms4000.appspot.com%2Ftwiml","message_date":"Mon, 13 Sep 2010 20:02:00 +0000","request_method":"get","request_url":"https:\/\/voiceforms4000.appspot.com\/twiml\/9436\/question\/0","date_created":"Mon, 13 Sep 2010 20:02:01 +0000","api_version":"2008-08-01","date_updated":"Mon, 13 Sep 2010 20:02:01 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO9329e5a4ed59a5733d2c1c1c69a83a28.json"},{"sid":"NObbb6efe3ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA1b79cdcaed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=414&ErrorCode=11200&url=http%3A%2F%2Fvoiceforms4000.appspot.com%2Ftwiml","message_date":"Mon, 13 Sep 2010 19:22:11 +0000","request_method":"get","request_url":"https:\/\/voiceforms4000.appspot.com\/twiml?AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&ToZip=94937&ToCity=INVERNESS&ToState=CA&Called=%2B14156694923&To=%2B14156694923&ToCountry=US&CalledZip=94937&Direction=inbound&ApiVersion=2010-04-01&Caller=%2B17378742833&CalledCity=INVERNESS&CalledCountry=US&CallSid=CA1b79cdcaed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B17378742833&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&ToZip=94937&ToCity=INVERNESS&ToState=CA&Called=%2B14156694923&To=%2B14156694923&ToCountry=US&CalledZip=94937&Direction=inbound&ApiVersion=2010-04-01&Caller=%2B17378742833&CalledCity=INVERNESS&CalledCountry=US&CallSid=CA1b79cdcaed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B17378742833&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&ToZip=94937&ToCity=INVERNESS&ToState=CA&Called=%2B14156694923&To=%2B14156694923&ToCountry=US&CalledZip=94937&Direction=inbound&ApiVersion=2010-04-01&Caller=%2B17378742833&CalledCity=INVERNESS&CalledCountry=US&CallSid=CA1b79cdcaed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B17378742833&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&ToZip=94937&ToCity=INVERNESS&ToState=CA&Called=%2B14156694923&To=%2B14156694923&ToCountry=US&CalledZip=94937&Direction=inbound&ApiVersion=2010-04-01&Caller=%2B17378742833&CalledCity=INVERNESS&CalledCountry=US&CallSid=CA1b79cdcaed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B17378742833&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&ToZip=94937&ToCity=INVERNESS&ToState=CA&Called=%2B14156694923&To=%2B14156694923&ToCountry=US&CalledZip=94937&Direction=inbound&ApiVersion=2010-04-01&Caller=%2B17378742833&CalledCity=INVERNESS&CalledCountry=US&CallSid=CA1b79cdcaed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B17378742833","date_created":"Mon, 13 Sep 2010 19:22:11 +0000","api_version":"2008-08-01","date_updated":"Mon, 13 Sep 2010 19:22:11 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NObbb6efe3ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO8fae61f6ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAc17624f4ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=414&ErrorCode=11200&url=http%3A%2F%2Fvoiceforms4000.appspot.com%2Ftwiml","message_date":"Mon, 13 Sep 2010 19:00:26 +0000","request_method":"get","request_url":"https:\/\/voiceforms4000.appspot.com\/twiml?AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=ringing&ToZip=94937&ToCity=INVERNESS&ToState=CA&Called=%2B14156694923&To=%2B14156694923&ToCountry=US&CalledZip=94937&Direction=inbound&ApiVersion=2010-04-01&Caller=%2B17378742833&CalledCity=INVERNESS&CalledCountry=US&CallSid=CAc17624f4ed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B17378742833&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=ringing&ToZip=94937&ToCity=INVERNESS&ToState=CA&Called=%2B14156694923&To=%2B14156694923&ToCountry=US&CalledZip=94937&Direction=inbound&ApiVersion=2010-04-01&Caller=%2B17378742833&CalledCity=INVERNESS&CalledCountry=US&CallSid=CAc17624f4ed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B17378742833&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&ToZip=94937&ToCity=INVERNESS&ToState=CA&Called=%2B14156694923&To=%2B14156694923&ToCountry=US&CalledZip=94937&Direction=inbound&ApiVersion=2010-04-01&Caller=%2B17378742833&CalledCity=INVERNESS&CalledCountry=US&CallSid=CAc17624f4ed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B17378742833&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&ToZip=94937&ToCity=INVERNESS&ToState=CA&Called=%2B14156694923&To=%2B14156694923&ToCountry=US&CalledZip=94937&Direction=inbound&ApiVersion=2010-04-01&Caller=%2B17378742833&CalledCity=INVERNESS&CalledCountry=US&CallSid=CAc17624f4ed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B17378742833&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&ToZip=94937&ToCity=INVERNESS&ToState=CA&Called=%2B14156694923&To=%2B14156694923&ToCountry=US&CalledZip=94937&Direction=inbound&ApiVersion=2010-04-01&Caller=%2B17378742833&CalledCity=INVERNESS&CalledCountry=US&CallSid=CAc17624f4ed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B17378742833","date_created":"Mon, 13 Sep 2010 19:00:26 +0000","api_version":"2008-08-01","date_updated":"Mon, 13 Sep 2010 19:00:26 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO8fae61f6ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO45c4d5aaed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA73e8db19ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=414&ErrorCode=11200&url=http%3A%2F%2Fvoiceforms4000.appspot.com%2Ftwiml","message_date":"Thu, 02 Sep 2010 07:13:17 +0000","request_method":"get","request_url":"https:\/\/voiceforms4000.appspot.com\/twiml?AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=ringing&ToZip=94937&ToCity=INVERNESS&ToState=CA&Called=%2B14156694923&To=%2B14156694923&ToCountry=US&CalledZip=94937&Direction=inbound&ApiVersion=2010-04-01&Caller=%2B17378742833&CalledCity=INVERNESS&CalledCountry=US&CallSid=CA73e8db19ed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B17378742833&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=ringing&ToZip=94937&ToCity=INVERNESS&ToState=CA&Called=%2B14156694923&To=%2B14156694923&ToCountry=US&CalledZip=94937&Direction=inbound&ApiVersion=2010-04-01&Caller=%2B17378742833&CalledCity=INVERNESS&CalledCountry=US&CallSid=CA73e8db19ed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B17378742833&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&ToZip=94937&ToCity=INVERNESS&ToState=CA&Called=%2B14156694923&To=%2B14156694923&ToCountry=US&CalledZip=94937&Direction=inbound&ApiVersion=2010-04-01&Caller=%2B17378742833&CalledCity=INVERNESS&CalledCountry=US&CallSid=CA73e8db19ed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B17378742833&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&ToZip=94937&ToCity=INVERNESS&ToState=CA&Called=%2B14156694923&To=%2B14156694923&ToCountry=US&CalledZip=94937&Direction=inbound&ApiVersion=2010-04-01&Caller=%2B17378742833&CalledCity=INVERNESS&CalledCountry=US&CallSid=CA73e8db19ed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B17378742833&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&ToZip=94937&ToCity=INVERNESS&ToState=CA&Called=%2B14156694923&To=%2B14156694923&ToCountry=US&CalledZip=94937&Direction=inbound&ApiVersion=2010-04-01&Caller=%2B17378742833&CalledCity=INVERNESS&CalledCountry=US&CallSid=CA73e8db19ed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B17378742833","date_created":"Thu, 02 Sep 2010 07:13:17 +0000","api_version":"2008-08-01","date_updated":"Thu, 02 Sep 2010 07:13:17 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO45c4d5aaed59a5733d2c1c1c69a83a28.json"},{"sid":"NO3f5d27a0ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAb2c5127ced59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fvoiceforms4000.appspot.com%2Ftwiml","message_date":"Tue, 31 Aug 2010 20:56:26 +0000","request_method":"get","request_url":"https:\/\/voiceforms4000.appspot.com\/twiml\/7992\/question\/1?AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&ToZip=94937&FromState=NC&Called=%2B14156694923&FromCountry=US&CallerCountry=US&CalledZip=94937&Direction=inbound&FromCity=CHAPEL+HILL&CalledCountry=US&CallerState=NC&CallSid=CAb2c5127ced59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B19199233044&CallerZip=27517&FromZip=27517&CallStatus=in-progress&ToCity=INVERNESS&ToState=CA&To=%2B14156694923&ToCountry=US&CallerCity=CHAPEL+HILL&ApiVersion=2010-04-01&Caller=%2B19199233044&CalledCity=INVERNESS","date_created":"Tue, 31 Aug 2010 20:56:26 +0000","api_version":"2008-08-01","date_updated":"Tue, 31 Aug 2010 20:56:26 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO3f5d27a0ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO31705342ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA47e13748ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fvoiceforms4000.appspot.com%2Ftwiml","message_date":"Tue, 31 Aug 2010 20:36:41 +0000","request_method":"get","request_url":"https:\/\/voiceforms4000.appspot.com\/twiml\/9436","date_created":"Tue, 31 Aug 2010 20:36:41 +0000","api_version":"2008-08-01","date_updated":"Tue, 31 Aug 2010 20:36:41 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO31705342ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO79b05ac4ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA297e726bed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fvoiceforms4000.appspot.com%2Ftwiml","message_date":"Tue, 31 Aug 2010 20:26:21 +0000","request_method":"get","request_url":"https:\/\/voiceforms4000.appspot.com\/twiml\/9436\/question\/2?AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&ToZip=94937&FromState=CA&Called=%2B14156694923&FromCountry=US&CallerCountry=US&CalledZip=94937&Direction=inbound&FromCity=SAN+FRANCISCO&CalledCountry=US&CallerState=CA&CallSid=CA297e726bed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B14152529607&CallerZip=94107&FromZip=94107&CallStatus=in-progress&ToCity=INVERNESS&ToState=CA&To=%2B14156694923&ToCountry=US&CallerCity=SAN+FRANCISCO&ApiVersion=2010-04-01&Caller=%2B14152529607&CalledCity=INVERNESS","date_created":"Tue, 31 Aug 2010 20:26:21 +0000","api_version":"2008-08-01","date_updated":"Tue, 31 Aug 2010 20:26:21 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO79b05ac4ed59a5733d2c1c1c69a83a28.json"},{"sid":"NOe814f9e3ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA5f19eec7ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fvoiceforms4000.appspot.com%2Ftwiml","message_date":"Tue, 31 Aug 2010 20:21:21 +0000","request_method":"get","request_url":"https:\/\/voiceforms4000.appspot.com\/twiml\/2042\/question\/2","date_created":"Tue, 31 Aug 2010 20:21:21 +0000","api_version":"2008-08-01","date_updated":"Tue, 31 Aug 2010 20:21:21 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NOe814f9e3ed59a5733d2c1c1c69a83a28.json"},{"sid":"NOdd2283a4ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAd2a6cbcbed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fvoiceforms4000.appspot.com%2Ftwiml","message_date":"Tue, 31 Aug 2010 20:20:04 +0000","request_method":"get","request_url":"https:\/\/voiceforms4000.appspot.com\/twiml\/9436","date_created":"Tue, 31 Aug 2010 20:20:04 +0000","api_version":"2008-08-01","date_updated":"Tue, 31 Aug 2010 20:20:04 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NOdd2283a4ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO94aa6de1ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA47c01c40ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fvoiceforms4000.appspot.com%2Ftwiml","message_date":"Tue, 31 Aug 2010 19:19:09 +0000","request_method":"get","request_url":"https:\/\/voiceforms4000.appspot.com\/twiml\/7992\/question\/0","date_created":"Tue, 31 Aug 2010 19:19:09 +0000","api_version":"2008-08-01","date_updated":"Tue, 31 Aug 2010 19:19:09 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO94aa6de1ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO051559b8ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA715b85a2ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fvoiceforms4000.appspot.com%2Ftwiml","message_date":"Tue, 31 Aug 2010 18:42:43 +0000","request_method":"get","request_url":"https:\/\/voiceforms4000.appspot.com\/twiml\/9436\/question\/4","date_created":"Tue, 31 Aug 2010 18:42:43 +0000","api_version":"2008-08-01","date_updated":"Tue, 31 Aug 2010 18:42:43 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO051559b8ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO04f19b0ced59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAca4f89b9ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fvoiceforms4000.appspot.com%2Ftwiml","message_date":"Tue, 31 Aug 2010 13:16:24 +0000","request_method":"get","request_url":"https:\/\/voiceforms4000.appspot.com\/twiml\/7992\/question\/0","date_created":"Tue, 31 Aug 2010 13:16:24 +0000","api_version":"2008-08-01","date_updated":"Tue, 31 Aug 2010 13:16:24 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO04f19b0ced59a5733d2c1c1c69a83a28.json"},{"sid":"NO549b3e62ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA9dc0b1eced59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=414&ErrorCode=11200&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml","message_date":"Tue, 31 Aug 2010 12:33:22 +0000","request_method":"get","request_url":"https:\/\/wufilio.appspot.com\/twiml\/8293\/question\/4?AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&ToZip=94937&FromState=CA&Called=%2B14156694923&FromCountry=US&CallerCountry=US&CalledZip=94937&Direction=inbound&FromCity=SOUTH+LAKE+TAHOE&CalledCountry=US&CallerState=CA&CallSid=CA9dc0b1eced59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B15305451766&CallerZip=89449&FromZip=89449&CallStatus=in-progress&ToCity=INVERNESS&ToState=CA&To=%2B14156694923&ToCountry=US&CallerCity=SOUTH+LAKE+TAHOE&ApiVersion=2010-04-01&Caller=%2B15305451766&CalledCity=INVERNESS&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&ToZip=94937&FromState=CA&Called=%2B14156694923&FromCountry=US&CallerCountry=US&CalledZip=94937&Direction=inbound&FromCity=SOUTH+LAKE+TAHOE&CalledCountry=US&CallerState=CA&CallSid=CA9dc0b1eced59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B15305451766&CallerZip=89449&FromZip=89449&CallStatus=in-progress&ToCity=INVERNESS&ToState=CA&To=%2B14156694923&ToCountry=US&CallerCity=SOUTH+LAKE+TAHOE&ApiVersion=2010-04-01&Caller=%2B15305451766&CalledCity=INVERNESS&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&ToZip=94937&FromState=CA&Called=%2B14156694923&FromCountry=US&CallerCountry=US&CalledZip=94937&Direction=inbound&FromCity=SOUTH+LAKE+TAHOE&CalledCountry=US&CallerState=CA&CallSid=CA9dc0b1eced59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B15305451766&CallerZip=89449&FromZip=89449&CallStatus=in-progress&ToCity=INVERNESS&ToState=CA&To=%2B14156694923&ToCountry=US&CallerCity=SOUTH+LAKE+TAHOE&ApiVersion=2010-04-01&Caller=%2B15305451766&CalledCity=INVERNESS&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&ToZip=94937&FromState=CA&Called=%2B14156694923&FromCountry=US&CallerCountry=US&CalledZip=94937&Direction=inbound&FromCity=SOUTH+LAKE+TAHOE&CalledCountry=US&CallerState=CA&CallSid=CA9dc0b1eced59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B15305451766&CallerZip=89449&FromZip=89449&CallStatus=in-progress&ToCity=INVERNESS&ToState=CA&To=%2B14156694923&ToCountry=US&CallerCity=SOUTH+LAKE+TAHOE&ApiVersion=2010-04-01&Caller=%2B15305451766&CalledCity=INVERNE","date_created":"Tue, 31 Aug 2010 12:33:22 +0000","api_version":"2008-08-01","date_updated":"Tue, 31 Aug 2010 12:33:22 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO549b3e62ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO57586a40ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA43958d73ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=13600&Msg=Invalid+Callback+URL&httpResponse=500&ErrorCode=11200&url=https%3A%2F%2Fwufilio.appspot.com%2Ftwiml%2F9318%2Fquestion%2F0%2Ftranscription%3FKind%3Dshortname%26Part%3D1%26Id%3DField114","message_date":"Tue, 31 Aug 2010 11:46:19 +0000","request_method":null,"request_url":"","date_created":"Tue, 31 Aug 2010 11:46:19 +0000","api_version":"2008-08-01","date_updated":"Tue, 31 Aug 2010 11:46:19 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO57586a40ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO45a2fb55ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA2927a418ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml","message_date":"Tue, 31 Aug 2010 11:34:01 +0000","request_method":"POST","request_url":"https:\/\/wufilio.appspot.com\/twiml\/7442\/submit","date_created":"Tue, 31 Aug 2010 11:34:01 +0000","api_version":"2008-08-01","date_updated":"Tue, 31 Aug 2010 11:34:01 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO45a2fb55ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO8fd6eff3ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAc01dad86ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml","message_date":"Tue, 31 Aug 2010 11:29:06 +0000","request_method":"POST","request_url":"https:\/\/wufilio.appspot.com\/twiml\/7442\/question\/2\/part\/1?Kind=time&Id=Field101","date_created":"Tue, 31 Aug 2010 11:29:06 +0000","api_version":"2008-08-01","date_updated":"Tue, 31 Aug 2010 11:29:06 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO8fd6eff3ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO0a128507ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA90bf4fcced59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml","message_date":"Tue, 31 Aug 2010 11:19:39 +0000","request_method":"POST","request_url":"https:\/\/wufilio.appspot.com\/twiml\/7189\/submit","date_created":"Tue, 31 Aug 2010 11:19:39 +0000","api_version":"2008-08-01","date_updated":"Tue, 31 Aug 2010 11:19:39 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO0a128507ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO2c163951ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA10359f59ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml","message_date":"Tue, 31 Aug 2010 10:55:28 +0000","request_method":"get","request_url":"https:\/\/wufilio.appspot.com\/twiml\/7442\/question\/0\/part\/0\/part\/1","date_created":"Tue, 31 Aug 2010 10:55:28 +0000","api_version":"2008-08-01","date_updated":"Tue, 31 Aug 2010 10:55:28 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO2c163951ed59a5733d2c1c1c69a83a28.json"},{"sid":"NOee9c3a81ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAf6be015fed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml","message_date":"Tue, 31 Aug 2010 10:49:29 +0000","request_method":"POST","request_url":"https:\/\/wufilio.appspot.com\/twiml\/7442\/question\/0\/part\/0?Kind=money&Id=Field102","date_created":"Tue, 31 Aug 2010 10:49:30 +0000","api_version":"2008-08-01","date_updated":"Tue, 31 Aug 2010 10:49:30 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NOee9c3a81ed59a5733d2c1c1c69a83a28.json"},{"sid":"NObd03a7f7ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAd9234d1aed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=414&ErrorCode=11200&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml","message_date":"Tue, 31 Aug 2010 10:48:54 +0000","request_method":"get","request_url":"https:\/\/wufilio.appspot.com\/twiml?AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&ToZip=94937&FromState=CA&Called=%2B14156694923&FromCountry=US&CallerCountry=US&CalledZip=94937&Direction=inbound&FromCity=SOUTH+LAKE+TAHOE&CalledCountry=US&CallerState=CA&CallSid=CAd9234d1aed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B15305451766&CallerZip=89449&FromZip=89449&CallStatus=ringing&ToCity=INVERNESS&ToState=CA&To=%2B14156694923&ToCountry=US&CallerCity=SOUTH+LAKE+TAHOE&ApiVersion=2010-04-01&Caller=%2B15305451766&CalledCity=INVERNESS&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&ToZip=94937&FromState=CA&Called=%2B14156694923&FromCountry=US&CallerCountry=US&CalledZip=94937&Direction=inbound&FromCity=SOUTH+LAKE+TAHOE&CalledCountry=US&CallerState=CA&CallSid=CAd9234d1aed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B15305451766&CallerZip=89449&FromZip=89449&CallStatus=ringing&ToCity=INVERNESS&ToState=CA&To=%2B14156694923&ToCountry=US&CallerCity=SOUTH+LAKE+TAHOE&ApiVersion=2010-04-01&Caller=%2B15305451766&CalledCity=INVERNESS&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&ToZip=94937&FromState=CA&Called=%2B14156694923&FromCountry=US&CallerCountry=US&CalledZip=94937&Direction=inbound&FromCity=SOUTH+LAKE+TAHOE&CalledCountry=US&CallerState=CA&CallSid=CAd9234d1aed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B15305451766&CallerZip=89449&FromZip=89449&CallStatus=in-progress&ToCity=INVERNESS&ToState=CA&To=%2B14156694923&ToCountry=US&CallerCity=SOUTH+LAKE+TAHOE&ApiVersion=2010-04-01&Caller=%2B15305451766&CalledCity=INVERNESS&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&ToZip=94937&FromState=CA&Called=%2B14156694923&FromCountry=US&CallerCountry=US&CalledZip=94937&Direction=inbound&FromCity=SOUTH+LAKE+TAHOE&CalledCountry=US&CallerState=CA&CallSid=CAd9234d1aed59a5733d2c1c1c69a83a28&CalledState=CA&From=%2B15305451766&CallerZip=89449&FromZip=89449&CallStatus=in-progress&ToCity=INVERNESS&ToState=CA&To=%2B14156694923&ToCountry=US&CallerCity=SOUTH+LAKE+TAHOE&ApiVersion=2010-04-01&Caller=%2B15305451766&CalledCity=INVERNESS","date_created":"Tue, 31 Aug 2010 10:48:54 +0000","api_version":"2008-08-01","date_updated":"Tue, 31 Aug 2010 10:48:54 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NObd03a7f7ed59a5733d2c1c1c69a83a28.json"},{"sid":"NOca65ffefed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAbb4e6e51ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml","message_date":"Tue, 31 Aug 2010 09:23:57 +0000","request_method":"get","request_url":"https:\/\/wufilio.appspot.com\/twiml\/4582\/question\/3","date_created":"Tue, 31 Aug 2010 09:23:57 +0000","api_version":"2008-08-01","date_updated":"Tue, 31 Aug 2010 09:23:57 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NOca65ffefed59a5733d2c1c1c69a83a28.json"},{"sid":"NOcb299b12ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA61f0a853ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml","message_date":"Tue, 31 Aug 2010 08:17:05 +0000","request_method":"get","request_url":"https:\/\/wufilio.appspot.com\/twiml\/4815\/question\/0","date_created":"Tue, 31 Aug 2010 08:17:05 +0000","api_version":"2008-08-01","date_updated":"Tue, 31 Aug 2010 08:17:05 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NOcb299b12ed59a5733d2c1c1c69a83a28.json"},{"sid":"NOc8ad3611ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA9acdad59ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml","message_date":"Tue, 31 Aug 2010 08:17:00 +0000","request_method":"get","request_url":"https:\/\/wufilio.appspot.com\/twiml\/4815\/question\/0","date_created":"Tue, 31 Aug 2010 08:17:01 +0000","api_version":"2008-08-01","date_updated":"Tue, 31 Aug 2010 08:17:01 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NOc8ad3611ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO296bf243ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAc63a8115ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml","message_date":"Tue, 31 Aug 2010 06:16:08 +0000","request_method":"get","request_url":"https:\/\/wufilio.appspot.com\/twiml\/5947","date_created":"Tue, 31 Aug 2010 06:16:08 +0000","api_version":"2008-08-01","date_updated":"Tue, 31 Aug 2010 06:16:08 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO296bf243ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO7a3f883eed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA891e938aed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=13600&Msg=Invalid+Callback+URL&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml%2F9823%2Ftranscription%3FKind%3Dtextarea%26Id%3DField111","message_date":"Mon, 30 Aug 2010 07:42:03 +0000","request_method":null,"request_url":"","date_created":"Mon, 30 Aug 2010 07:42:03 +0000","api_version":"2008-08-01","date_updated":"Mon, 30 Aug 2010 07:42:03 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO7a3f883eed59a5733d2c1c1c69a83a28.json"},{"sid":"NOba5b06e0ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA006eccdbed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml","message_date":"Mon, 30 Aug 2010 07:35:40 +0000","request_method":"POST","request_url":"http:\/\/wufilio.appspot.com\/twiml\/9823\/question\/0?Kind=number&Id=Field104","date_created":"Mon, 30 Aug 2010 07:35:40 +0000","api_version":"2008-08-01","date_updated":"Mon, 30 Aug 2010 07:35:40 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NOba5b06e0ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO932c342bed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAb19a9abbed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=414&ErrorCode=11200&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml","message_date":"Sun, 29 Aug 2010 19:50:02 +0000","request_method":"get","request_url":"http:\/\/wufilio.appspot.com\/twiml\/9823\/question\/1?AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&Called=4156694923&CallerCountry=US&CalledZip=94937&ApiVersion=2008-08-01&CallerCity=SOUTH+LAKE+TAHOE&Caller=5305451766&CalledCity=INVERNESS&CallSegmentGuid=&CalledCountry=US&CallerState=CA&CallSid=CAb19a9abbed59a5733d2c1c1c69a83a28&CallGuid=CAb19a9abbed59a5733d2c1c1c69a83a28&AccountGuid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CalledState=CA&CallerZip=89449&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&Called=4156694923&CallerCountry=US&CalledZip=94937&ApiVersion=2008-08-01&CallerCity=SOUTH+LAKE+TAHOE&Caller=5305451766&CalledCity=INVERNESS&CallSegmentGuid=&CalledCountry=US&CallerState=CA&CallSid=CAb19a9abbed59a5733d2c1c1c69a83a28&CallGuid=CAb19a9abbed59a5733d2c1c1c69a83a28&AccountGuid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CalledState=CA&CallerZip=89449&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&Called=4156694923&CallerCountry=US&CalledZip=94937&ApiVersion=2008-08-01&CallerCity=SOUTH+LAKE+TAHOE&Caller=5305451766&CalledCity=INVERNESS&CallSegmentGuid=&CalledCountry=US&CallerState=CA&CallSid=CAb19a9abbed59a5733d2c1c1c69a83a28&CallGuid=CAb19a9abbed59a5733d2c1c1c69a83a28&AccountGuid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CalledState=CA&CallerZip=89449&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&Called=4156694923&CallerCountry=US&CalledZip=94937&ApiVersion=2008-08-01&CallerCity=SOUTH+LAKE+TAHOE&Caller=5305451766&CalledCity=INVERNESS&CallSegmentGuid=&CalledCountry=US&CallerState=CA&CallSid=CAb19a9abbed59a5733d2c1c1c69a83a28&CallGuid=CAb19a9abbed59a5733d2c1c1c69a83a28&AccountGuid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CalledState=CA&CallerZip=89449","date_created":"Sun, 29 Aug 2010 19:50:02 +0000","api_version":"2008-08-01","date_updated":"Sun, 29 Aug 2010 19:50:02 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO932c342bed59a5733d2c1c1c69a83a28.json"},{"sid":"NOeef3b585ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA9d563bbfed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=414&ErrorCode=11200&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml","message_date":"Sun, 29 Aug 2010 19:47:25 +0000","request_method":"get","request_url":"http:\/\/wufilio.appspot.com\/twiml\/9823\/question\/1?AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&Called=4156694923&CallerCountry=US&CalledZip=94937&ApiVersion=2008-08-01&CallerCity=SOUTH+LAKE+TAHOE&Caller=5305451766&CalledCity=INVERNESS&CallSegmentGuid=&CalledCountry=US&CallerState=CA&CallSid=CA9d563bbfed59a5733d2c1c1c69a83a28&CallGuid=CA9d563bbfed59a5733d2c1c1c69a83a28&AccountGuid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CalledState=CA&CallerZip=89449&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&Called=4156694923&CallerCountry=US&CalledZip=94937&ApiVersion=2008-08-01&CallerCity=SOUTH+LAKE+TAHOE&Caller=5305451766&CalledCity=INVERNESS&CallSegmentGuid=&CalledCountry=US&CallerState=CA&CallSid=CA9d563bbfed59a5733d2c1c1c69a83a28&CallGuid=CA9d563bbfed59a5733d2c1c1c69a83a28&AccountGuid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CalledState=CA&CallerZip=89449&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&Called=4156694923&CallerCountry=US&CalledZip=94937&ApiVersion=2008-08-01&CallerCity=SOUTH+LAKE+TAHOE&Caller=5305451766&CalledCity=INVERNESS&CallSegmentGuid=&CalledCountry=US&CallerState=CA&CallSid=CA9d563bbfed59a5733d2c1c1c69a83a28&CallGuid=CA9d563bbfed59a5733d2c1c1c69a83a28&AccountGuid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CalledState=CA&CallerZip=89449&AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&Called=4156694923&CallerCountry=US&CalledZip=94937&ApiVersion=2008-08-01&CallerCity=SOUTH+LAKE+TAHOE&Caller=5305451766&CalledCity=INVERNESS&CallSegmentGuid=&CalledCountry=US&CallerState=CA&CallSid=CA9d563bbfed59a5733d2c1c1c69a83a28&CallGuid=CA9d563bbfed59a5733d2c1c1c69a83a28&AccountGuid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CalledState=CA&CallerZip=89449","date_created":"Sun, 29 Aug 2010 19:47:25 +0000","api_version":"2008-08-01","date_updated":"Sun, 29 Aug 2010 19:47:25 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NOeef3b585ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO204dc7f3ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA6ca08479ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=405&ErrorCode=11200&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml","message_date":"Sun, 29 Aug 2010 11:05:38 +0000","request_method":"POST","request_url":"http:\/\/wufilio.appspot.com\/twiml\/9823\/submit","date_created":"Sun, 29 Aug 2010 11:05:38 +0000","api_version":"2008-08-01","date_updated":"Sun, 29 Aug 2010 11:05:38 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO204dc7f3ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO714ad70aed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAfeae0f49ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=405&ErrorCode=11200&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml","message_date":"Sun, 29 Aug 2010 11:00:32 +0000","request_method":"POST","request_url":"http:\/\/wufilio.appspot.com\/twiml\/9823\/submit","date_created":"Sun, 29 Aug 2010 11:00:32 +0000","api_version":"2008-08-01","date_updated":"Sun, 29 Aug 2010 11:00:32 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO714ad70aed59a5733d2c1c1c69a83a28.json"},{"sid":"NO4b03b62aed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA6ec72a7aed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml","message_date":"Sun, 29 Aug 2010 10:36:50 +0000","request_method":"POST","request_url":"http:\/\/wufilio.appspot.com\/twiml\/9823\/question\/?0=Yes&1=No&Kind=checkbox&2=Maybe&Id=Field3","date_created":"Sun, 29 Aug 2010 10:36:50 +0000","api_version":"2008-08-01","date_updated":"Sun, 29 Aug 2010 10:36:50 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO4b03b62aed59a5733d2c1c1c69a83a28.json"},{"sid":"NOff45b79ded59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA5560843fed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml","message_date":"Sun, 29 Aug 2010 10:24:19 +0000","request_method":"POST","request_url":"http:\/\/wufilio.appspot.com\/twiml\/9823\/question\/?0=Yes&1=No&Kind=checkbox&2=Maybe&Id=Field3","date_created":"Sun, 29 Aug 2010 10:24:19 +0000","api_version":"2008-08-01","date_updated":"Sun, 29 Aug 2010 10:24:19 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NOff45b79ded59a5733d2c1c1c69a83a28.json"},{"sid":"NOa7ede48eed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA37995f90ed59a5733d2c1c1c69a83a28","log":"0","error_code":"12100","more_info":"http:\/\/www.twilio.com\/docs\/errors\/12100","message_text":"EmailNotification=false&LogLevel=ERROR&Msg=&parserMessage=Error+on+line+-1+of+document++%3A+Premature+end+of+file.+&ErrorCode=12100&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml%2F9823%2Fquestion%2F0%3FAccountSid%3DAC4bf2dafed59a5733d2c1c1c69a83a283%26CallStatus%3Din-progress%26Called%3D4156694923%26CallerCountry%3DUS%26CalledZip%3D94937%26ApiVersion%3D2008-08-01%26CallerCity%3DSOUTH%2BLAKE%2BTAHOE%26Caller%3D5305451766%26CalledCity%3DINVERNESS%26CallSegmentGuid%3D%26CalledCountry%3DUS%26CallerState%3DCA%26CallSid%3DCA37995f9ed59a5733d2c1c1c69a83a285%26CallGuid%3DCA37995f9ed59a5733d2c1c1c69a83a285%26AccountGuid%3DAC4bf2dafed59a5733d2c1c1c69a83a283%26CalledState%3DCA%26CallerZip%3D89449","message_date":"Sun, 29 Aug 2010 08:45:02 +0000","request_method":"POST","request_url":"http:\/\/wufilio.appspot.com\/twiml\/9823\/question\/0?AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&Called=4156694923&CallerCountry=US&CalledZip=94937&ApiVersion=2008-08-01&CallerCity=SOUTH+LAKE+TAHOE&Caller=5305451766&CalledCity=INVERNESS&CallSegmentGuid=&CalledCountry=US&CallerState=CA&CallSid=CA37995f90ed59a5733d2c1c1c69a83a28&CallGuid=CA37995f90ed59a5733d2c1c1c69a83a28&AccountGuid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CalledState=CA&CallerZip=89449","date_created":"Sun, 29 Aug 2010 08:45:03 +0000","api_version":"2008-08-01","date_updated":"Sun, 29 Aug 2010 08:45:03 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NOa7ede48eed59a5733d2c1c1c69a83a28.json"},{"sid":"NO21244b44ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAf43f6844ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=404&ErrorCode=11200&url=http%3A%2F%2Fwufilio.appspot.com%2Ftwiml","message_date":"Tue, 24 Aug 2010 22:01:04 +0000","request_method":"get","request_url":"http:\/\/wufilio.appspot.com\/1111","date_created":"Tue, 24 Aug 2010 22:01:04 +0000","api_version":"2008-08-01","date_updated":"Tue, 24 Aug 2010 22:01:04 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO21244b44ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO111b62a1ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA69930793ed59a5733d2c1c1c69a83a28","log":"0","error_code":"12100","more_info":"http:\/\/www.twilio.com\/docs\/errors\/12100","message_text":"EmailNotification=false&LogLevel=ERROR&Msg=&parserMessage=Error+on+line+-1+of+document++%3A+Premature+end+of+file.+&ErrorCode=12100&url=http%3A%2F%2Fapps.dev.twilio.com%2F%7Ekjconroy%2Fhenchentoot.php%3FAccountSid%3DAC4bf2dafed59a5733d2c1c1c69a83a283%26CallStatus%3Din-progress%26Called%3D4156694923%26CallerCountry%3DUS%26CalledZip%3D94937%26ApiVersion%3D2008-08-01%26CallerCity%3DSOUTH%2BLAKE%2BTAHOE%26Caller%3D5305451766%26CalledCity%3DINVERNESS%26CallSegmentGuid%3D%26CalledCountry%3DUS%26DialStatus%3Danswered%26CallerState%3DCA%26CallSid%3DCA6993079ed59a5733d2c1c1c69a83a28b%26CallGuid%3DCA6993079ed59a5733d2c1c1c69a83a28b%26AccountGuid%3DAC4bf2dafed59a5733d2c1c1c69a83a283%26CalledState%3DCA%26CallerZip%3D89449","message_date":"Tue, 24 Aug 2010 20:33:27 +0000","request_method":"GET","request_url":"http:\/\/apps.dev.twilio.com\/~kjconroy\/henchentoot.php?AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&Called=4156694923&CallerCountry=US&CalledZip=94937&ApiVersion=2008-08-01&CallerCity=SOUTH+LAKE+TAHOE&Caller=5305451766&CalledCity=INVERNESS&CallSegmentGuid=&CalledCountry=US&DialStatus=answered&CallerState=CA&CallSid=CA69930793ed59a5733d2c1c1c69a83a28&CallGuid=CA69930793ed59a5733d2c1c1c69a83a28&AccountGuid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CalledState=CA&CallerZip=89449","date_created":"Tue, 24 Aug 2010 20:33:27 +0000","api_version":"2008-08-01","date_updated":"Tue, 24 Aug 2010 20:33:27 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO111b62a1ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO0fe21740ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAf5ead372ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11205","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11205","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=HTTP+Connection+Failure+-+Read+timed+out&ErrorCode=11205&msg=HTTP+Connection+Failure+-+Read+timed+out&url=http%3A%2F%2Fapps.dev.twilio.com%2F%7Ekjconroy%2Fmobilemusical%2Findex.php","message_date":"Sat, 07 Aug 2010 08:50:05 +0000","request_method":null,"request_url":"","date_created":"Sat, 07 Aug 2010 08:50:05 +0000","api_version":"2008-08-01","date_updated":"Sat, 07 Aug 2010 08:50:05 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO0fe21740ed59a5733d2c1c1c69a83a28.json"},{"sid":"NOfbaf6bfeed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA93723936ed59a5733d2c1c1c69a83a28","log":"0","error_code":"12100","more_info":"http:\/\/www.twilio.com\/docs\/errors\/12100","message_text":"EmailNotification=false&LogLevel=ERROR&Msg=&parserMessage=Error+on+line+-1+of+document++%3A+Premature+end+of+file.+&ErrorCode=12100&url=http%3A%2F%2Fapps.dev.twilio.com%2F%7Ekjconroy%2Fhenchentoot.php%3FAccountSid%3DAC4bf2dafed59a5733d2c1c1c69a83a283%26CallStatus%3Din-progress%26Called%3D4156694923%26CallerCountry%3DUS%26CalledZip%3D94937%26ApiVersion%3D2008-08-01%26CallerCity%3DSAN%2BFRANCISCO%26Caller%3D5104231531%26CalledCity%3DINVERNESS%26CallSegmentGuid%3D%26CalledCountry%3DUS%26DialStatus%3Danswered%26CallerState%3DCA%26CallSid%3DCA9372393ed59a5733d2c1c1c69a83a289%26CallGuid%3DCA9372393ed59a5733d2c1c1c69a83a289%26AccountGuid%3DAC4bf2dafed59a5733d2c1c1c69a83a283%26CalledState%3DCA%26CallerZip%3D94108","message_date":"Tue, 29 Jun 2010 23:15:48 +0000","request_method":"GET","request_url":"http:\/\/apps.dev.twilio.com\/~kjconroy\/henchentoot.php?AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&Called=4156694923&CallerCountry=US&CalledZip=94937&ApiVersion=2008-08-01&CallerCity=SAN+FRANCISCO&Caller=5104231531&CalledCity=INVERNESS&CallSegmentGuid=&CalledCountry=US&DialStatus=answered&CallerState=CA&CallSid=CA93723936ed59a5733d2c1c1c69a83a28&CallGuid=CA93723936ed59a5733d2c1c1c69a83a28&AccountGuid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CalledState=CA&CallerZip=94108","date_created":"Tue, 29 Jun 2010 23:15:48 +0000","api_version":"2008-08-01","date_updated":"Tue, 29 Jun 2010 23:15:48 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NOfbaf6bfeed59a5733d2c1c1c69a83a28.json"},{"sid":"NO2993775ced59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA0f608aafed59a5733d2c1c1c69a83a28","log":"0","error_code":"12100","more_info":"http:\/\/www.twilio.com\/docs\/errors\/12100","message_text":"EmailNotification=false&LogLevel=ERROR&Msg=&parserMessage=Error+on+line+2+of+document++%3A+Open+quote+is+expected+for+attribute+%22foo%22+associated+with+an++element+type++%22Response%22.+&ErrorCode=12100&url=http%3A%2F%2Fapps.dev.twilio.com%2F%7Ekjconroy%2Fdebug.xml%3FAccountSid%3DAC4bf2dafed59a5733d2c1c1c69a83a283%26CallStatus%3Din-progress%26Called%3D4156694923%26CallerCountry%3DUS%26CalledZip%3D94937%26CallerCity%3DSAN%2BFRANCISCO%26Caller%3D4158104101%26CalledCity%3DINVERNESS%26CallSegmentGuid%3D%26CalledCountry%3DUS%26DialStatus%3Danswered%26CallerState%3DCA%26CallSid%3DCA0f608aaed59a5733d2c1c1c69a83a28d%26CallGuid%3DCA0f608aaed59a5733d2c1c1c69a83a28d%26AccountGuid%3DAC4bf2dafed59a5733d2c1c1c69a83a283%26CalledState%3DCA%26CallerZip%3D94941","message_date":"Sun, 09 May 2010 23:58:48 +0000","request_method":"GET","request_url":"http:\/\/apps.dev.twilio.com\/~kjconroy\/debug.xml?AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&Called=4156694923&CallerCountry=US&CalledZip=94937&CallerCity=SAN+FRANCISCO&Caller=4158104101&CalledCity=INVERNESS&CallSegmentGuid=&CalledCountry=US&DialStatus=answered&CallerState=CA&CallSid=CA0f608aafed59a5733d2c1c1c69a83a28&CallGuid=CA0f608aafed59a5733d2c1c1c69a83a28&AccountGuid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CalledState=CA&CallerZip=94941","date_created":"Sun, 09 May 2010 23:58:48 +0000","api_version":"2008-08-01","date_updated":"Sun, 09 May 2010 23:58:48 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO2993775ced59a5733d2c1c1c69a83a28.json"},{"sid":"NO80e37341ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA7c1b3d09ed59a5733d2c1c1c69a83a28","log":"0","error_code":"12100","more_info":"http:\/\/www.twilio.com\/docs\/errors\/12100","message_text":"EmailNotification=false&LogLevel=ERROR&Msg=&parserMessage=Error+on+line+-1+of+document++%3A+Premature+end+of+file.+&ErrorCode=12100&url=http%3A%2F%2Fapps.dev.twilio.com%2F%7Ekjconroy%2Fmobilemusical%2FchangeInstrument.php","message_date":"Wed, 05 May 2010 18:50:35 +0000","request_method":"POST","request_url":"http:\/\/apps.dev.twilio.com\/~kjconroy\/mobilemusical\/changeInstrument.php","date_created":"Wed, 05 May 2010 18:50:35 +0000","api_version":"2008-08-01","date_updated":"Wed, 05 May 2010 18:50:35 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO80e37341ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO4d934164ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAfc335287ed59a5733d2c1c1c69a83a28","log":"0","error_code":"12100","more_info":"http:\/\/www.twilio.com\/docs\/errors\/12100","message_text":"EmailNotification=false&LogLevel=ERROR&Msg=&parserMessage=Error+on+line+2+of+document++%3A+The+markup+in+the+document+following+the+root+element+must+be+well-formed.+&ErrorCode=12100&url=http%3A%2F%2Fapps.dev.twilio.com%2F%7Ekjconroy%2Fmobilemusical.php","message_date":"Tue, 04 May 2010 08:56:35 +0000","request_method":"POST","request_url":"http:\/\/apps.dev.twilio.com\/~kjconroy\/mobilemusical.php","date_created":"Tue, 04 May 2010 08:56:35 +0000","api_version":"2008-08-01","date_updated":"Tue, 04 May 2010 08:56:35 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO4d934164ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO7ed2d419ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAf04da7e4ed59a5733d2c1c1c69a83a28","log":"0","error_code":"12100","more_info":"http:\/\/www.twilio.com\/docs\/errors\/12100","message_text":"EmailNotification=false&LogLevel=ERROR&Msg=&parserMessage=Error+on+line+1+of+document++%3A+Content+is+not+allowed+in+prolog.+&ErrorCode=12100&url=http%3A%2F%2Fapps.dev.twilio.com%2F%7Ekjconroy%2Fmobilemusical.php","message_date":"Tue, 04 May 2010 08:48:14 +0000","request_method":"POST","request_url":"http:\/\/apps.dev.twilio.com\/~kjconroy\/mobilemusical.php","date_created":"Tue, 04 May 2010 08:48:14 +0000","api_version":"2008-08-01","date_updated":"Tue, 04 May 2010 08:48:14 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO7ed2d419ed59a5733d2c1c1c69a83a28.json"},{"sid":"NOf5eb3e16ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA68def275ed59a5733d2c1c1c69a83a28","log":"0","error_code":"12100","more_info":"http:\/\/www.twilio.com\/docs\/errors\/12100","message_text":"EmailNotification=false&LogLevel=ERROR&Msg=&parserMessage=Error+on+line+2+of+document++%3A+The+reference+to+entity+%22id%22+must+end+with+the+%27%3B%27+delimiter.+&ErrorCode=12100&url=http%3A%2F%2Fapps.dev.twilio.com%2F%7Ekjconroy%2Fdebug.xml%3FAccountSid%3DAC4bf2dafed59a5733d2c1c1c69a83a283%26CallStatus%3Din-progress%26Called%3D4156694923%26CallerCountry%3DUS%26CalledZip%3D94937%26CallerCity%3DSOUTH%2BLAKE%2BTAHOE%26Caller%3D5305451766%26CalledCity%3DINVERNESS%26CallSegmentGuid%3D%26CalledCountry%3DUS%26DialStatus%3Danswered%26CallerState%3DCA%26CallSid%3DCA68def27ed59a5733d2c1c1c69a83a288%26CallGuid%3DCA68def27ed59a5733d2c1c1c69a83a288%26AccountGuid%3DAC4bf2dafed59a5733d2c1c1c69a83a283%26CalledState%3DCA%26CallerZip%3D89449","message_date":"Thu, 11 Feb 2010 08:53:07 +0000","request_method":"GET","request_url":"http:\/\/apps.dev.twilio.com\/~kjconroy\/debug.xml?AccountSid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CallStatus=in-progress&Called=4156694923&CallerCountry=US&CalledZip=94937&CallerCity=SOUTH+LAKE+TAHOE&Caller=5305451766&CalledCity=INVERNESS&CallSegmentGuid=&CalledCountry=US&DialStatus=answered&CallerState=CA&CallSid=CA68def275ed59a5733d2c1c1c69a83a28&CallGuid=CA68def275ed59a5733d2c1c1c69a83a28&AccountGuid=AC4bf2dafbed59a5733d2c1c1c69a83a28&CalledState=CA&CallerZip=89449","date_created":"Thu, 11 Feb 2010 08:53:07 +0000","api_version":"2008-08-01","date_updated":"Thu, 11 Feb 2010 08:53:07 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NOf5eb3e16ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO3ca97578ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA9ba2dd81ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=404&ErrorCode=11200&url=http%3A%2F%2Fseahorse.caritos.com%2Ftwilio%2Fmakerecording","message_date":"Thu, 24 Dec 2009 11:59:04 +0000","request_method":"GET","request_url":"http:\/\/seahorse.caritos.com\/twilio\/makerecording\/","date_created":"Thu, 24 Dec 2009 11:59:04 +0000","api_version":"2008-08-01","date_updated":"Thu, 24 Dec 2009 11:59:04 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO3ca97578ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO714a2138ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA58808187ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=404&ErrorCode=11200&url=http%3A%2F%2Fseahorse.caritos.com%2Ftwilio%2Fmakerecording","message_date":"Tue, 10 Nov 2009 17:58:08 +0000","request_method":"GET","request_url":"http:\/\/seahorse.caritos.com\/twilio\/makerecording\/","date_created":"Tue, 10 Nov 2009 17:58:08 +0000","api_version":"2008-08-01","date_updated":"Tue, 10 Nov 2009 17:58:08 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO714a2138ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO549f526eed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAd46dd1e5ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=404&ErrorCode=11200&url=http%3A%2F%2Fseahorse.caritos.com%2Ftwilio%2Fmakerecording","message_date":"Sat, 07 Nov 2009 18:44:26 +0000","request_method":"GET","request_url":"http:\/\/seahorse.caritos.com\/twilio\/makerecording\/","date_created":"Sat, 07 Nov 2009 18:44:27 +0000","api_version":"2008-08-01","date_updated":"Sat, 07 Nov 2009 18:44:27 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO549f526eed59a5733d2c1c1c69a83a28.json"},{"sid":"NO007d96abed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA31f48068ed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=404&ErrorCode=11200&url=http%3A%2F%2Fseahorse.caritos.com%2Ftwilio%2Fmakerecording","message_date":"Sat, 07 Nov 2009 18:44:26 +0000","request_method":"GET","request_url":"http:\/\/seahorse.caritos.com\/twilio\/makerecording\/","date_created":"Sat, 07 Nov 2009 18:44:27 +0000","api_version":"2008-08-01","date_updated":"Sat, 07 Nov 2009 18:44:27 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO007d96abed59a5733d2c1c1c69a83a28.json"},{"sid":"NO8e36baebed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":null,"log":"3","error_code":null,"more_info":null,"message_text":"Hello,\n\nYour Twilio Account is empty, so we've suspended your ability to make and receive phone calls. Please visit our <a href='http:\/\/www.twilio.com\/user\/billing\/add-funds'>Add Funds<\/a> page to recharge your payment account and restore service. \n\nNote, you can avoid account suspension in the future by setting up <a href='http:\/\/www.twilio.com\/user\/billing\/recurring'>automatic replenishment<\/a> of your account when it gets low.\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t<a href='http:\/\/www.twilio.com\/user\/account'>Access Your Twilio Account<\/a>\n\t\t\t\t\t\t\t\t\t\n\t\t\t\n\t\t\n\t\t\n\t\t\t \n\t\t\n\t\n\n\n\n\tThis system email was sent to Kyle Conroy (kyle.j.conroy@gmail.com) regarding your Twilio Account AC4bf2dafbed59a5733d2c1c1c69a83a28\/US0f03d945ed59a5733d2c1c1c69a83a28 by Twilio Inc, 548 Market St #14510, San Francisco California 94104, 877-8-TWILIO.\n\t\n\tFeel free to respond to this email, we're always listening.","message_date":"Thu, 20 Aug 2009 17:49:59 +0000","request_method":null,"request_url":null,"date_created":"Thu, 20 Aug 2009 17:49:59 +0000","api_version":"2008-08-01","date_updated":"Thu, 20 Aug 2009 17:49:59 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO8e36baebed59a5733d2c1c1c69a83a28.json"},{"sid":"NO1fd5b596ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAcc943c8eed59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=500&ErrorCode=11200&url=http%3A%2F%2Fseahorse.caritos.com%2Ftwilio%2Fmakerecording","message_date":"Wed, 05 Aug 2009 21:03:07 +0000","request_method":"POST","request_url":"http:\/\/seahorse.caritos.com\/twilio\/makerecording","date_created":"Wed, 05 Aug 2009 21:03:07 +0000","api_version":"2008-08-01","date_updated":"Wed, 05 Aug 2009 21:03:07 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO1fd5b596ed59a5733d2c1c1c69a83a28.json"},{"sid":"NO3b8638d9ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAcb23831ded59a5733d2c1c1c69a83a28","log":"0","error_code":"11200","more_info":"http:\/\/www.twilio.com\/docs\/errors\/11200","message_text":"EmailNotification=false&LogLevel=ERROR&sourceComponent=12000&Msg=&httpResponse=404&ErrorCode=11200&url=http%3A%2F%2Fapps.dev.twilio.com%2F%7Ekjconroy%2Fdebug%2Fverb.php%3Fverb%3Dplay","message_date":"Thu, 30 Jul 2009 06:47:55 +0000","request_method":"POST","request_url":"http:\/\/apps.dev.twilio.com\/~kjconroy\/debug\/verb.php?verb=play","date_created":"Thu, 30 Jul 2009 06:47:55 +0000","api_version":"2008-08-01","date_updated":"Thu, 30 Jul 2009 06:47:55 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Notifications\/NO3b8638d9ed59a5733d2c1c1c69a83a28.json"}]} diff --git a/tests/resources/outgoing_caller_ids_instance.json b/tests/resources/outgoing_caller_ids_instance.json deleted file mode 100644 index 2488bf1ba4..0000000000 --- a/tests/resources/outgoing_caller_ids_instance.json +++ /dev/null @@ -1 +0,0 @@ -{"sid":"PN947e73eded59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","friendly_name":"(415) 867-5309","phone_number":"+141586753096","date_created":"Fri, 21 Aug 2009 00:11:24 +0000","date_updated":"Fri, 21 Aug 2009 00:11:24 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/OutgoingCallerIds\/PN947e73eded59a5733d2c1c1c69a83a28.json"} diff --git a/tests/resources/outgoing_caller_ids_list.json b/tests/resources/outgoing_caller_ids_list.json deleted file mode 100644 index 70ad0af45e..0000000000 --- a/tests/resources/outgoing_caller_ids_list.json +++ /dev/null @@ -1 +0,0 @@ -{"page":0,"num_pages":1,"page_size":50,"total":1,"start":0,"end":0,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/OutgoingCallerIds.json","first_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/OutgoingCallerIds.json?Page=0&PageSize=50","previous_page_uri":null,"next_page_uri":null,"last_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/OutgoingCallerIds.json?Page=0&PageSize=50","outgoing_caller_ids":[{"sid":"PN947e73eded59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","friendly_name":"(415) 867-5309","phone_number":"+141586753096","date_created":"Fri, 21 Aug 2009 00:11:24 +0000","date_updated":"Fri, 21 Aug 2009 00:11:24 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/OutgoingCallerIds\/PN947e73eded59a5733d2c1c1c69a83a28.json"}]} diff --git a/tests/resources/outgoing_caller_ids_validation.json b/tests/resources/outgoing_caller_ids_validation.json deleted file mode 100644 index 4648f83391..0000000000 --- a/tests/resources/outgoing_caller_ids_validation.json +++ /dev/null @@ -1 +0,0 @@ -{"account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","phone_number":"+141586753096","friendly_name":null,"validation_code":147423} diff --git a/tests/resources/participants_instance.json b/tests/resources/participants_instance.json deleted file mode 100644 index 33c24485b5..0000000000 --- a/tests/resources/participants_instance.json +++ /dev/null @@ -1 +0,0 @@ -{"call_sid":"CAd31637cced59a5733d2c1c1c69a83a28","conference_sid":"CFf2fe8498ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","muted":false,"end_conference_on_exit":false,"start_conference_on_enter":true,"date_created":"Fri, 18 Feb 2011 21:07:19 +0000","date_updated":"Fri, 18 Feb 2011 21:07:19 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Conferences\/CFf2fe8498ed59a5733d2c1c1c69a83a28\/Participants\/CAd31637cced59a5733d2c1c1c69a83a28.json"} diff --git a/tests/resources/participants_list.json b/tests/resources/participants_list.json deleted file mode 100644 index 9ab5ce4896..0000000000 --- a/tests/resources/participants_list.json +++ /dev/null @@ -1 +0,0 @@ -{"page":0,"num_pages":1,"page_size":50,"total":1,"start":0,"end":0,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Conferences\/CFf2fe8498ed59a5733d2c1c1c69a83a28\/Participants.json","first_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Conferences\/CFf2fe8498ed59a5733d2c1c1c69a83a28\/Participants.json?Page=0&PageSize=50","previous_page_uri":null,"next_page_uri":null,"last_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Conferences\/CFf2fe8498ed59a5733d2c1c1c69a83a28\/Participants.json?Page=0&PageSize=50","participants":[{"conference_sid":"CFf2fe8498ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAd31637cced59a5733d2c1c1c69a83a28","muted":false,"end_conference_on_exit":false,"start_conference_on_enter":true,"date_created":"Fri, 18 Feb 2011 21:07:19 +0000","date_updated":"Fri, 18 Feb 2011 21:07:19 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Conferences\/CFf2fe8498ed59a5733d2c1c1c69a83a28\/Participants\/CAd31637cced59a5733d2c1c1c69a83a28.json"}]} diff --git a/tests/resources/process.py b/tests/resources/process.py deleted file mode 100644 index 1ff36be7b7..0000000000 --- a/tests/resources/process.py +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env python -from __future__ import with_statement -import re -import os - -sid = "ed59a5733d2c1c1c69a83a28" - - -def twilio_clean(contents): - contents = re.sub(r"([A-Z]{2}\w{8})\w{24}", r"\1%s" % sid, contents) - contents = re.sub(r"\"[a-z0-9]{32}\"", "\"AUTHTOKEN\"", contents) - contents = re.sub(r"\+\d{10}", r"+14158675309", contents) - contents = re.sub(r"[0-9\- \(\)]{14}", r"(415) 867-5309", contents) - return contents - - -def main(): - for f in os.listdir(os.path.abspath(os.path.dirname(__file__))): - path, ext = os.path.splitext(f) - if ext == ".json": - with open(f) as g: - contents = g.read() - contents = twilio_clean(contents) - with open(f, "w") as g: - g.write(contents.strip()) - g.write("\n") - - -if __name__ == "__main__": - main() diff --git a/tests/resources/queues_instance.json b/tests/resources/queues_instance.json deleted file mode 100644 index 2eeff479ba..0000000000 --- a/tests/resources/queues_instance.json +++ /dev/null @@ -1 +0,0 @@ -{"sid": "QU6e2cd5a7c8074edc8b383a3b198b2f8b", "friendly_name": "CutieQueue", "current_size": null, "average_wait_time": null, "max_size": 100, "date_created": "Tue, 07 Aug 2012 21:08:51 +0000", "date_updated": "Tue, 07 Aug 2012 21:08:51 +0000", "uri": "/2010-04-01/Accounts/ACf5af0ea0c9955b67b39c52fb11ee6e69/Queues/QU6e2cd5a7c8074edc8b383a3b198b2f8b.json"} diff --git a/tests/resources/queues_list.json b/tests/resources/queues_list.json deleted file mode 100644 index ae389ef7f1..0000000000 --- a/tests/resources/queues_list.json +++ /dev/null @@ -1 +0,0 @@ -{"first_page_uri": "/2010-04-01/Accounts/ACf5af0ea0c9955b67b39c52fb11ee6e69/Queues.json?Page=0&PageSize=50", "num_pages": 1, "previous_page_uri": null, "queues": [{"sid": "QU1b9faddec3d54ec18488f86c83019bf0", "friendly_name": "Support", "current_size": 0, "average_wait_time": 0, "max_size": 100, "date_created": "Tue, 07 Aug 2012 21:09:04 +0000", "date_updated": "Tue, 07 Aug 2012 21:09:04 +0000", "uri": "/2010-04-01/Accounts/ACf5af0ea0c9955b67b39c52fb11ee6e69/Queues/QU1b9faddec3d54ec18488f86c83019bf0.json"}, {"sid": "QU6e2cd5a7c8074edc8b383a3b198b2f8b", "friendly_name": "CutieQueue", "current_size": 0, "average_wait_time": 0, "max_size": 100, "date_created": "Tue, 07 Aug 2012 21:08:51 +0000", "date_updated": "Tue, 07 Aug 2012 21:08:51 +0000", "uri": "/2010-04-01/Accounts/ACf5af0ea0c9955b67b39c52fb11ee6e69/Queues/QU6e2cd5a7c8074edc8b383a3b198b2f8b.json"}, {"sid": "QUa8ce40f68d3f41958e2519646d55b989", "friendly_name": "Test1", "current_size": 0, "average_wait_time": 0, "max_size": 64, "date_created": "Tue, 07 Aug 2012 19:09:17 +0000", "date_updated": "Tue, 07 Aug 2012 19:09:17 +0000", "uri": "/2010-04-01/Accounts/ACf5af0ea0c9955b67b39c52fb11ee6e69/Queues/QUa8ce40f68d3f41958e2519646d55b989.json"}], "uri": "/2010-04-01/Accounts/ACf5af0ea0c9955b67b39c52fb11ee6e69/Queues.json", "page_size": 50, "start": 0, "next_page_uri": null, "end": 2, "total": 3, "last_page_uri": "/2010-04-01/Accounts/ACf5af0ea0c9955b67b39c52fb11ee6e69/Queues.json?Page=0&PageSize=50", "page": 0} diff --git a/tests/resources/recordings_instance.json b/tests/resources/recordings_instance.json deleted file mode 100644 index 07ae435867..0000000000 --- a/tests/resources/recordings_instance.json +++ /dev/null @@ -1 +0,0 @@ -{"sid":"RE19e96a31ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA31fd3b90ed59a5733d2c1c1c69a83a28","duration":"6","date_created":"Wed, 01 Sep 2010 15:15:41 +0000","api_version":"2010-04-01","date_updated":"Wed, 01 Sep 2010 15:15:41 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE19e96a31ed59a5733d2c1c1c69a83a28.json"} diff --git a/tests/resources/recordings_list.json b/tests/resources/recordings_list.json deleted file mode 100644 index d235441ea0..0000000000 --- a/tests/resources/recordings_list.json +++ /dev/null @@ -1 +0,0 @@ -{"page":0,"num_pages":3,"page_size":50,"total":132,"start":0,"end":49,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings.json","first_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings.json?Page=0&PageSize=50","previous_page_uri":null,"next_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings.json?Page=1&PageSize=50","last_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings.json?Page=2&PageSize=50","recordings":[{"sid":"RE3ce9efa4ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA24388be8ed59a5733d2c1c1c69a83a28","duration":"2","date_created":"Tue, 15 Feb 2011 04:21:54 +0000","api_version":"2010-04-01","date_updated":"Tue, 15 Feb 2011 04:21:54 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE3ce9efa4ed59a5733d2c1c1c69a83a28.json"},{"sid":"RE83fccacded59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA7e3e8c74ed59a5733d2c1c1c69a83a28","duration":"1","date_created":"Sun, 13 Feb 2011 02:12:05 +0000","api_version":"2010-04-01","date_updated":"Sun, 13 Feb 2011 02:12:05 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE83fccacded59a5733d2c1c1c69a83a28.json"},{"sid":"REee24eda1ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAfd85b7a9ed59a5733d2c1c1c69a83a28","duration":"4","date_created":"Sat, 12 Feb 2011 22:51:58 +0000","api_version":"2010-04-01","date_updated":"Sat, 12 Feb 2011 22:51:58 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REee24eda1ed59a5733d2c1c1c69a83a28.json"},{"sid":"RE6df50791ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAfd85b7a9ed59a5733d2c1c1c69a83a28","duration":"1","date_created":"Sat, 12 Feb 2011 22:50:26 +0000","api_version":"2010-04-01","date_updated":"Sat, 12 Feb 2011 22:50:26 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE6df50791ed59a5733d2c1c1c69a83a28.json"},{"sid":"RE0341b5b1ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA0cd446a4ed59a5733d2c1c1c69a83a28","duration":"2","date_created":"Thu, 03 Feb 2011 16:44:40 +0000","api_version":"2010-04-01","date_updated":"Thu, 03 Feb 2011 16:44:40 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE0341b5b1ed59a5733d2c1c1c69a83a28.json"},{"sid":"RE118d90aded59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA5a1f0a21ed59a5733d2c1c1c69a83a28","duration":"2","date_created":"Sat, 18 Dec 2010 22:40:39 +0000","api_version":"2010-04-01","date_updated":"Sat, 18 Dec 2010 22:40:39 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE118d90aded59a5733d2c1c1c69a83a28.json"},{"sid":"REa9f4ed87ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA5a1f0a21ed59a5733d2c1c1c69a83a28","duration":"4","date_created":"Sat, 18 Dec 2010 22:40:25 +0000","api_version":"2010-04-01","date_updated":"Sat, 18 Dec 2010 22:40:25 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REa9f4ed87ed59a5733d2c1c1c69a83a28.json"},{"sid":"REd9d83d23ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA0645767bed59a5733d2c1c1c69a83a28","duration":"5","date_created":"Sun, 05 Dec 2010 21:01:16 +0000","api_version":"2010-04-01","date_updated":"Sun, 05 Dec 2010 21:01:16 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REd9d83d23ed59a5733d2c1c1c69a83a28.json"},{"sid":"REf20ab89bed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA41e7078eed59a5733d2c1c1c69a83a28","duration":"4","date_created":"Thu, 11 Nov 2010 04:15:12 +0000","api_version":"2010-04-01","date_updated":"Thu, 11 Nov 2010 04:15:12 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REf20ab89bed59a5733d2c1c1c69a83a28.json"},{"sid":"RE3b5d582aed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA5c0de550ed59a5733d2c1c1c69a83a28","duration":"2","date_created":"Thu, 28 Oct 2010 11:57:50 +0000","api_version":"2010-04-01","date_updated":"Thu, 28 Oct 2010 11:57:50 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE3b5d582aed59a5733d2c1c1c69a83a28.json"},{"sid":"RE6690bc5ded59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA5c0de550ed59a5733d2c1c1c69a83a28","duration":"4","date_created":"Thu, 28 Oct 2010 11:56:40 +0000","api_version":"2010-04-01","date_updated":"Thu, 28 Oct 2010 11:56:40 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE6690bc5ded59a5733d2c1c1c69a83a28.json"},{"sid":"REae531dfced59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAee5e9f61ed59a5733d2c1c1c69a83a28","duration":"2","date_created":"Sat, 16 Oct 2010 05:26:56 +0000","api_version":"2010-04-01","date_updated":"Sat, 16 Oct 2010 05:26:56 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REae531dfced59a5733d2c1c1c69a83a28.json"},{"sid":"RE24a04918ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA70ba7140ed59a5733d2c1c1c69a83a28","duration":"1","date_created":"Wed, 06 Oct 2010 18:28:34 +0000","api_version":"2010-04-01","date_updated":"Wed, 06 Oct 2010 18:28:34 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE24a04918ed59a5733d2c1c1c69a83a28.json"},{"sid":"REdc38c474ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA70ba7140ed59a5733d2c1c1c69a83a28","duration":"1","date_created":"Wed, 06 Oct 2010 18:28:27 +0000","api_version":"2010-04-01","date_updated":"Wed, 06 Oct 2010 18:28:27 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REdc38c474ed59a5733d2c1c1c69a83a28.json"},{"sid":"RE1797d2e4ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA70ba7140ed59a5733d2c1c1c69a83a28","duration":"3","date_created":"Wed, 06 Oct 2010 18:28:18 +0000","api_version":"2010-04-01","date_updated":"Wed, 06 Oct 2010 18:28:18 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE1797d2e4ed59a5733d2c1c1c69a83a28.json"},{"sid":"REe3ac5562ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAb381aeaded59a5733d2c1c1c69a83a28","duration":"4","date_created":"Wed, 06 Oct 2010 16:52:15 +0000","api_version":"2010-04-01","date_updated":"Wed, 06 Oct 2010 16:52:15 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REe3ac5562ed59a5733d2c1c1c69a83a28.json"},{"sid":"REa42ad83ded59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAb381aeaded59a5733d2c1c1c69a83a28","duration":"2","date_created":"Wed, 06 Oct 2010 16:51:33 +0000","api_version":"2010-04-01","date_updated":"Wed, 06 Oct 2010 16:51:33 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REa42ad83ded59a5733d2c1c1c69a83a28.json"},{"sid":"RE7dda7275ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAb381aeaded59a5733d2c1c1c69a83a28","duration":"1","date_created":"Wed, 06 Oct 2010 16:51:26 +0000","api_version":"2010-04-01","date_updated":"Wed, 06 Oct 2010 16:51:26 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE7dda7275ed59a5733d2c1c1c69a83a28.json"},{"sid":"RE55e4a102ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA475e55a5ed59a5733d2c1c1c69a83a28","duration":"1","date_created":"Mon, 04 Oct 2010 02:28:58 +0000","api_version":"2010-04-01","date_updated":"Mon, 04 Oct 2010 02:28:58 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE55e4a102ed59a5733d2c1c1c69a83a28.json"},{"sid":"RE900b1db1ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA475e55a5ed59a5733d2c1c1c69a83a28","duration":"2","date_created":"Mon, 04 Oct 2010 02:28:51 +0000","api_version":"2010-04-01","date_updated":"Mon, 04 Oct 2010 02:28:51 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE900b1db1ed59a5733d2c1c1c69a83a28.json"},{"sid":"RE573e7920ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA475e55a5ed59a5733d2c1c1c69a83a28","duration":"1","date_created":"Mon, 04 Oct 2010 02:28:44 +0000","api_version":"2010-04-01","date_updated":"Mon, 04 Oct 2010 02:28:44 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE573e7920ed59a5733d2c1c1c69a83a28.json"},{"sid":"RE7934e357ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA475e55a5ed59a5733d2c1c1c69a83a28","duration":"2","date_created":"Mon, 04 Oct 2010 02:28:37 +0000","api_version":"2010-04-01","date_updated":"Mon, 04 Oct 2010 02:28:37 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE7934e357ed59a5733d2c1c1c69a83a28.json"},{"sid":"REd1893bcaed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAef36592ded59a5733d2c1c1c69a83a28","duration":"9","date_created":"Mon, 04 Oct 2010 02:26:10 +0000","api_version":"2010-04-01","date_updated":"Mon, 04 Oct 2010 02:26:10 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REd1893bcaed59a5733d2c1c1c69a83a28.json"},{"sid":"REc9d0c0b1ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAef36592ded59a5733d2c1c1c69a83a28","duration":"3","date_created":"Mon, 04 Oct 2010 02:25:34 +0000","api_version":"2010-04-01","date_updated":"Mon, 04 Oct 2010 02:25:34 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REc9d0c0b1ed59a5733d2c1c1c69a83a28.json"},{"sid":"REbe832fe6ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAef36592ded59a5733d2c1c1c69a83a28","duration":"6","date_created":"Mon, 04 Oct 2010 02:25:22 +0000","api_version":"2010-04-01","date_updated":"Mon, 04 Oct 2010 02:25:22 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REbe832fe6ed59a5733d2c1c1c69a83a28.json"},{"sid":"REd97482faed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA49972ebaed59a5733d2c1c1c69a83a28","duration":"3","date_created":"Wed, 22 Sep 2010 12:41:50 +0000","api_version":"2010-04-01","date_updated":"Wed, 22 Sep 2010 12:41:50 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REd97482faed59a5733d2c1c1c69a83a28.json"},{"sid":"REd07ee10eed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA77ddc8d5ed59a5733d2c1c1c69a83a28","duration":"2","date_created":"Tue, 21 Sep 2010 14:47:38 +0000","api_version":"2010-04-01","date_updated":"Tue, 21 Sep 2010 14:47:38 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REd07ee10eed59a5733d2c1c1c69a83a28.json"},{"sid":"RE75fdaa94ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA75e5238aed59a5733d2c1c1c69a83a28","duration":"1","date_created":"Mon, 20 Sep 2010 23:53:45 +0000","api_version":"2010-04-01","date_updated":"Mon, 20 Sep 2010 23:53:45 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE75fdaa94ed59a5733d2c1c1c69a83a28.json"},{"sid":"RE1a6d455eed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAd9918e25ed59a5733d2c1c1c69a83a28","duration":"1","date_created":"Sun, 19 Sep 2010 02:35:01 +0000","api_version":"2010-04-01","date_updated":"Sun, 19 Sep 2010 02:35:01 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE1a6d455eed59a5733d2c1c1c69a83a28.json"},{"sid":"RE445b6f63ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA39218e45ed59a5733d2c1c1c69a83a28","duration":"1","date_created":"Sat, 18 Sep 2010 02:45:56 +0000","api_version":"2010-04-01","date_updated":"Sat, 18 Sep 2010 02:45:56 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE445b6f63ed59a5733d2c1c1c69a83a28.json"},{"sid":"RE6d3646c3ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA39218e45ed59a5733d2c1c1c69a83a28","duration":"3","date_created":"Sat, 18 Sep 2010 02:44:05 +0000","api_version":"2010-04-01","date_updated":"Sat, 18 Sep 2010 02:44:05 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE6d3646c3ed59a5733d2c1c1c69a83a28.json"},{"sid":"RE721ff2a7ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAa26452b2ed59a5733d2c1c1c69a83a28","duration":"1","date_created":"Fri, 17 Sep 2010 12:07:07 +0000","api_version":"2010-04-01","date_updated":"Fri, 17 Sep 2010 12:07:07 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE721ff2a7ed59a5733d2c1c1c69a83a28.json"},{"sid":"RE00494485ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAcffd776ced59a5733d2c1c1c69a83a28","duration":"3","date_created":"Mon, 13 Sep 2010 20:16:30 +0000","api_version":"2010-04-01","date_updated":"Mon, 13 Sep 2010 20:16:30 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE00494485ed59a5733d2c1c1c69a83a28.json"},{"sid":"REb21cfb3eed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAcffd776ced59a5733d2c1c1c69a83a28","duration":"3","date_created":"Mon, 13 Sep 2010 20:15:31 +0000","api_version":"2010-04-01","date_updated":"Mon, 13 Sep 2010 20:15:31 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REb21cfb3eed59a5733d2c1c1c69a83a28.json"},{"sid":"REdab02432ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAcffd776ced59a5733d2c1c1c69a83a28","duration":"3","date_created":"Mon, 13 Sep 2010 20:15:21 +0000","api_version":"2010-04-01","date_updated":"Mon, 13 Sep 2010 20:15:21 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REdab02432ed59a5733d2c1c1c69a83a28.json"},{"sid":"REcbb9d0e5ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA105cb7b2ed59a5733d2c1c1c69a83a28","duration":"2","date_created":"Mon, 13 Sep 2010 20:06:32 +0000","api_version":"2010-04-01","date_updated":"Mon, 13 Sep 2010 20:06:32 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REcbb9d0e5ed59a5733d2c1c1c69a83a28.json"},{"sid":"REc472d728ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA105cb7b2ed59a5733d2c1c1c69a83a28","duration":"5","date_created":"Mon, 13 Sep 2010 20:06:20 +0000","api_version":"2010-04-01","date_updated":"Mon, 13 Sep 2010 20:06:20 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REc472d728ed59a5733d2c1c1c69a83a28.json"},{"sid":"RE26db132bed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA057f0582ed59a5733d2c1c1c69a83a28","duration":"1","date_created":"Thu, 02 Sep 2010 13:35:31 +0000","api_version":"2010-04-01","date_updated":"Thu, 02 Sep 2010 13:35:31 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE26db132bed59a5733d2c1c1c69a83a28.json"},{"sid":"RE71e8926ded59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA057f0582ed59a5733d2c1c1c69a83a28","duration":"1","date_created":"Thu, 02 Sep 2010 13:34:53 +0000","api_version":"2010-04-01","date_updated":"Thu, 02 Sep 2010 13:34:53 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE71e8926ded59a5733d2c1c1c69a83a28.json"},{"sid":"REb33b7b98ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA057f0582ed59a5733d2c1c1c69a83a28","duration":"6","date_created":"Thu, 02 Sep 2010 13:34:39 +0000","api_version":"2010-04-01","date_updated":"Thu, 02 Sep 2010 13:34:39 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REb33b7b98ed59a5733d2c1c1c69a83a28.json"},{"sid":"REd65d5054ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAcb7e6575ed59a5733d2c1c1c69a83a28","duration":"1","date_created":"Wed, 01 Sep 2010 16:43:47 +0000","api_version":"2010-04-01","date_updated":"Wed, 01 Sep 2010 16:43:47 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REd65d5054ed59a5733d2c1c1c69a83a28.json"},{"sid":"RE1ad56651ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAcb7e6575ed59a5733d2c1c1c69a83a28","duration":"3","date_created":"Wed, 01 Sep 2010 16:43:38 +0000","api_version":"2010-04-01","date_updated":"Wed, 01 Sep 2010 16:43:38 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE1ad56651ed59a5733d2c1c1c69a83a28.json"},{"sid":"REe462c807ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAbe6cf023ed59a5733d2c1c1c69a83a28","duration":"3","date_created":"Wed, 01 Sep 2010 16:38:59 +0000","api_version":"2010-04-01","date_updated":"Wed, 01 Sep 2010 16:38:59 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REe462c807ed59a5733d2c1c1c69a83a28.json"},{"sid":"RE33c6fd8eed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAbe6cf023ed59a5733d2c1c1c69a83a28","duration":"1","date_created":"Wed, 01 Sep 2010 16:38:07 +0000","api_version":"2010-04-01","date_updated":"Wed, 01 Sep 2010 16:38:07 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE33c6fd8eed59a5733d2c1c1c69a83a28.json"},{"sid":"RE99a77b1bed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAbe6cf023ed59a5733d2c1c1c69a83a28","duration":"3","date_created":"Wed, 01 Sep 2010 16:37:56 +0000","api_version":"2010-04-01","date_updated":"Wed, 01 Sep 2010 16:37:56 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE99a77b1bed59a5733d2c1c1c69a83a28.json"},{"sid":"REdf0f01fbed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA31fd3b90ed59a5733d2c1c1c69a83a28","duration":"2","date_created":"Wed, 01 Sep 2010 15:15:54 +0000","api_version":"2010-04-01","date_updated":"Wed, 01 Sep 2010 15:15:54 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REdf0f01fbed59a5733d2c1c1c69a83a28.json"},{"sid":"RE19e96a31ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CA31fd3b90ed59a5733d2c1c1c69a83a28","duration":"6","date_created":"Wed, 01 Sep 2010 15:15:41 +0000","api_version":"2010-04-01","date_updated":"Wed, 01 Sep 2010 15:15:41 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE19e96a31ed59a5733d2c1c1c69a83a28.json"},{"sid":"RE6f1ca7efed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAc1a4a131ed59a5733d2c1c1c69a83a28","duration":"14","date_created":"Wed, 01 Sep 2010 02:20:11 +0000","api_version":"2010-04-01","date_updated":"Wed, 01 Sep 2010 02:20:11 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/RE6f1ca7efed59a5733d2c1c1c69a83a28.json"},{"sid":"REaaa7ee0ced59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAc1a4a131ed59a5733d2c1c1c69a83a28","duration":"1","date_created":"Wed, 01 Sep 2010 02:19:16 +0000","api_version":"2010-04-01","date_updated":"Wed, 01 Sep 2010 02:19:16 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REaaa7ee0ced59a5733d2c1c1c69a83a28.json"},{"sid":"REbcfbcfc4ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","call_sid":"CAc1a4a131ed59a5733d2c1c1c69a83a28","duration":"1","date_created":"Wed, 01 Sep 2010 02:19:08 +0000","api_version":"2010-04-01","date_updated":"Wed, 01 Sep 2010 02:19:08 +0000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Recordings\/REbcfbcfc4ed59a5733d2c1c1c69a83a28.json"}]} diff --git a/tests/resources/sandbox_instance.json b/tests/resources/sandbox_instance.json deleted file mode 100644 index 4c022e6117..0000000000 --- a/tests/resources/sandbox_instance.json +++ /dev/null @@ -1 +0,0 @@ -{"pin":"66528411","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","phone_number":"4155992671","voice_url":"http:\/\/www.digg.com","voice_method":"POST","sms_url":"http:\/\/demo.twilio.com\/welcome\/sms","sms_method":"POST","status_callback":null,"status_callback_method":null,"date_created":"Sun, 15 Mar 2009 02:08:47 +0000","date_updated":"Fri, 18 Feb 2011 17:37:18 +0000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Sandbox.json"} diff --git a/tests/resources/sms_messages_instance.json b/tests/resources/sms_messages_instance.json deleted file mode 100644 index b6c42ac71c..0000000000 --- a/tests/resources/sms_messages_instance.json +++ /dev/null @@ -1 +0,0 @@ -{"sid":"SM6144a547ed59a5733d2c1c1c69a83a28","date_created":"Mon, 26 Jul 2010 21:46:42 +0000","date_updated":"Mon, 26 Jul 2010 21:46:44 +0000","date_sent":"Mon, 26 Jul 2010 21:46:44 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"n","status":"sent","direction":"outbound-api","api_version":"2008-08-01","price":"-0.03000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM6144a547ed59a5733d2c1c1c69a83a28.json"} diff --git a/tests/resources/sms_messages_list.json b/tests/resources/sms_messages_list.json deleted file mode 100644 index e2a1ee8ac6..0000000000 --- a/tests/resources/sms_messages_list.json +++ /dev/null @@ -1 +0,0 @@ -{"page":0,"num_pages":2,"page_size":50,"total":54,"start":0,"end":49,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages.json","first_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages.json?Page=0&PageSize=50","previous_page_uri":null,"next_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages.json?Page=1&PageSize=50","last_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages.json?Page=1&PageSize=50","sms_messages":[{"sid":"SMa54f53faed59a5733d2c1c1c69a83a28","date_created":"Sat, 12 Feb 2011 02:22:26 +0000","date_updated":"Sat, 12 Feb 2011 02:22:27 +0000","date_sent":"Sat, 12 Feb 2011 02:22:27 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"IT WORKS~!","status":"sent","direction":"outbound-api","price":"-0.02000","api_version":"2010-04-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SMa54f53faed59a5733d2c1c1c69a83a28.json"},{"sid":"SM8e9a672aed59a5733d2c1c1c69a83a28","date_created":"Sat, 12 Feb 2011 02:19:23 +0000","date_updated":"Sat, 12 Feb 2011 02:19:26 +0000","date_sent":"Sat, 12 Feb 2011 02:19:26 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"AHHHH YEAH","status":"sent","direction":"outbound-api","price":"-0.02000","api_version":"2010-04-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM8e9a672aed59a5733d2c1c1c69a83a28.json"},{"sid":"SMa4dba3b9ed59a5733d2c1c1c69a83a28","date_created":"Sat, 12 Feb 2011 02:18:13 +0000","date_updated":"Sat, 12 Feb 2011 02:18:14 +0000","date_sent":"Sat, 12 Feb 2011 02:18:14 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"HI!!!","status":"sent","direction":"outbound-api","price":"-0.02000","api_version":"2010-04-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SMa4dba3b9ed59a5733d2c1c1c69a83a28.json"},{"sid":"SM38513fdfed59a5733d2c1c1c69a83a28","date_created":"Mon, 26 Jul 2010 21:48:06 +0000","date_updated":"Mon, 26 Jul 2010 21:48:08 +0000","date_sent":"Mon, 26 Jul 2010 21:48:08 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nn","status":"sent","direction":"outbound-api","price":"-0.03000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM38513fdfed59a5733d2c1c1c69a83a28.json"},{"sid":"SM6144a547ed59a5733d2c1c1c69a83a28","date_created":"Mon, 26 Jul 2010 21:46:42 +0000","date_updated":"Mon, 26 Jul 2010 21:46:44 +0000","date_sent":"Mon, 26 Jul 2010 21:46:44 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"n","status":"sent","direction":"outbound-api","price":"-0.03000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM6144a547ed59a5733d2c1c1c69a83a28.json"},{"sid":"SM2aabd6eced59a5733d2c1c1c69a83a28","date_created":"Mon, 26 Jul 2010 21:45:16 +0000","date_updated":"Mon, 26 Jul 2010 21:45:18 +0000","date_sent":"Mon, 26 Jul 2010 21:45:18 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn","status":"sent","direction":"outbound-api","price":"-0.03000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM2aabd6eced59a5733d2c1c1c69a83a28.json"},{"sid":"SM6ef54c91ed59a5733d2c1c1c69a83a28","date_created":"Wed, 14 Jul 2010 22:08:09 +0000","date_updated":"Wed, 14 Jul 2010 22:08:09 +0000","date_sent":"Wed, 14 Jul 2010 22:08:09 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753092","from":"+141586753093","body":"ttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt","status":"failed","direction":"outbound-api","price":null,"api_version":"2010-04-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM6ef54c91ed59a5733d2c1c1c69a83a28.json"},{"sid":"SM40935e7bed59a5733d2c1c1c69a83a28","date_created":"Wed, 14 Jul 2010 21:36:00 +0000","date_updated":"Wed, 14 Jul 2010 21:36:02 +0000","date_sent":"Wed, 14 Jul 2010 21:36:02 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt","status":"sent","direction":"outbound-api","price":"-0.03000","api_version":"2010-04-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM40935e7bed59a5733d2c1c1c69a83a28.json"},{"sid":"SM85ce5ee4ed59a5733d2c1c1c69a83a28","date_created":"Sun, 04 Apr 2010 08:24:08 +0000","date_updated":"Sun, 04 Apr 2010 08:24:10 +0000","date_sent":"Sun, 04 Apr 2010 08:24:10 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"THE SERVER IS UP","status":"sent","direction":"outbound-api","price":"-0.03000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM85ce5ee4ed59a5733d2c1c1c69a83a28.json"},{"sid":"SMca0364d7ed59a5733d2c1c1c69a83a28","date_created":"Wed, 13 Jan 2010 07:28:23 +0000","date_updated":"Wed, 13 Jan 2010 07:28:27 +0000","date_sent":"Wed, 13 Jan 2010 07:28:27 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753090","from":"+141586753093","body":"Monkey has messaged(415) 867-5309times","status":"sent","direction":"outbound-reply","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SMca0364d7ed59a5733d2c1c1c69a83a28.json"},{"sid":"SM3f72c7bbed59a5733d2c1c1c69a83a28","date_created":"Wed, 13 Jan 2010 07:28:22 +0000","date_updated":"Wed, 13 Jan 2010 07:28:22 +0000","date_sent":"Wed, 13 Jan 2010 07:28:22 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753090","body":"Did you want fish with that?","status":"sending","direction":"inbound","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM3f72c7bbed59a5733d2c1c1c69a83a28.json"},{"sid":"SMf976e1eded59a5733d2c1c1c69a83a28","date_created":"Mon, 11 Jan 2010 23:45:43 +0000","date_updated":"Mon, 11 Jan 2010 23:45:44 +0000","date_sent":"Mon, 11 Jan 2010 23:45:44 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+1415867530955","from":"+141586753093","body":"Hey Kyle, Monkey Party at 6PM. Bring Bananas!","status":"failed","direction":"outbound-api","price":null,"api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SMf976e1eded59a5733d2c1c1c69a83a28.json"},{"sid":"SMd40f1c41ed59a5733d2c1c1c69a83a28","date_created":"Mon, 11 Jan 2010 23:45:22 +0000","date_updated":"Mon, 11 Jan 2010 23:45:23 +0000","date_sent":"Mon, 11 Jan 2010 23:45:23 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+1415867530955","from":"+141586753093","body":"Hey Kyle, Monkey Party at 6PM. Bring Bananas!","status":"failed","direction":"outbound-api","price":null,"api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SMd40f1c41ed59a5733d2c1c1c69a83a28.json"},{"sid":"SMfaecba9fed59a5733d2c1c1c69a83a28","date_created":"Mon, 11 Jan 2010 20:58:36 +0000","date_updated":"Mon, 11 Jan 2010 20:58:38 +0000","date_sent":"Mon, 11 Jan 2010 20:58:38 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"Monkey, thanks for the call!","status":"sent","direction":"outbound-call","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SMfaecba9fed59a5733d2c1c1c69a83a28.json"},{"sid":"SMb63148bced59a5733d2c1c1c69a83a28","date_created":"Mon, 11 Jan 2010 20:54:26 +0000","date_updated":"Mon, 11 Jan 2010 20:54:29 +0000","date_sent":"Mon, 11 Jan 2010 20:54:29 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"Hey Kyle, Monkey Party at 6PM. Bring Bananas!","status":"sent","direction":"outbound-api","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SMb63148bced59a5733d2c1c1c69a83a28.json"},{"sid":"SM7b2f0685ed59a5733d2c1c1c69a83a28","date_created":"Mon, 11 Jan 2010 20:54:26 +0000","date_updated":"Mon, 11 Jan 2010 20:54:29 +0000","date_sent":"Mon, 11 Jan 2010 20:54:29 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753091","from":"+141586753093","body":"Hey Virgil, Monkey Party at 6PM. Bring Bananas!","status":"sent","direction":"outbound-api","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM7b2f0685ed59a5733d2c1c1c69a83a28.json"},{"sid":"SM7bb05562ed59a5733d2c1c1c69a83a28","date_created":"Mon, 11 Jan 2010 20:54:25 +0000","date_updated":"Mon, 11 Jan 2010 20:54:27 +0000","date_sent":"Mon, 11 Jan 2010 20:54:27 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753090","from":"+141586753093","body":"Hey Boots, Monkey Party at 6PM. Bring Bananas!","status":"sent","direction":"outbound-api","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM7bb05562ed59a5733d2c1c1c69a83a28.json"},{"sid":"SM281f1faded59a5733d2c1c1c69a83a28","date_created":"Mon, 11 Jan 2010 20:54:25 +0000","date_updated":"Mon, 11 Jan 2010 20:54:26 +0000","date_sent":"Mon, 11 Jan 2010 20:54:26 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753099","from":"+141586753093","body":"Hey Curious George, Monkey Party at 6PM. Bring Bananas!","status":"failed","direction":"outbound-api","price":null,"api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM281f1faded59a5733d2c1c1c69a83a28.json"},{"sid":"SM7a6b2338ed59a5733d2c1c1c69a83a28","date_created":"Mon, 11 Jan 2010 20:22:43 +0000","date_updated":"Mon, 11 Jan 2010 20:22:44 +0000","date_sent":"Mon, 11 Jan 2010 20:22:44 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"Monkey has messaged(415) 867-5309times","status":"sent","direction":"outbound-reply","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM7a6b2338ed59a5733d2c1c1c69a83a28.json"},{"sid":"SM1a04f29bed59a5733d2c1c1c69a83a28","date_created":"Mon, 11 Jan 2010 20:22:42 +0000","date_updated":"Mon, 11 Jan 2010 20:22:42 +0000","date_sent":"Mon, 11 Jan 2010 20:22:42 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753096","body":"Two?","status":"sending","direction":"inbound","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM1a04f29bed59a5733d2c1c1c69a83a28.json"},{"sid":"SMc5846a48ed59a5733d2c1c1c69a83a28","date_created":"Mon, 11 Jan 2010 20:22:06 +0000","date_updated":"Mon, 11 Jan 2010 20:22:14 +0000","date_sent":"Mon, 11 Jan 2010 20:22:14 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"Monkey has messaged(415) 867-5309times","status":"sent","direction":"outbound-reply","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SMc5846a48ed59a5733d2c1c1c69a83a28.json"},{"sid":"SM16ddd23aed59a5733d2c1c1c69a83a28","date_created":"Mon, 11 Jan 2010 20:22:05 +0000","date_updated":"Mon, 11 Jan 2010 20:22:05 +0000","date_sent":"Mon, 11 Jan 2010 20:22:05 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753096","body":"Ohhhhhh","status":"sending","direction":"inbound","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM16ddd23aed59a5733d2c1c1c69a83a28.json"},{"sid":"SM880fdc19ed59a5733d2c1c1c69a83a28","date_created":"Mon, 11 Jan 2010 20:21:45 +0000","date_updated":"Mon, 11 Jan 2010 20:21:47 +0000","date_sent":"Mon, 11 Jan 2010 20:21:47 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"Monkey has messaged(415) 867-5309times","status":"sent","direction":"outbound-reply","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM880fdc19ed59a5733d2c1c1c69a83a28.json"},{"sid":"SMf61e2ceced59a5733d2c1c1c69a83a28","date_created":"Mon, 11 Jan 2010 20:21:45 +0000","date_updated":"Mon, 11 Jan 2010 20:21:45 +0000","date_sent":"Mon, 11 Jan 2010 20:21:45 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753096","body":"Jol","status":"sending","direction":"inbound","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SMf61e2ceced59a5733d2c1c1c69a83a28.json"},{"sid":"SMea266b01ed59a5733d2c1c1c69a83a28","date_created":"Mon, 11 Jan 2010 19:57:48 +0000","date_updated":"Mon, 11 Jan 2010 19:57:49 +0000","date_sent":"Mon, 11 Jan 2010 19:57:49 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"Kyle, thanks for the message!","status":"sent","direction":"outbound-reply","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SMea266b01ed59a5733d2c1c1c69a83a28.json"},{"sid":"SM99c423dbed59a5733d2c1c1c69a83a28","date_created":"Mon, 11 Jan 2010 19:57:48 +0000","date_updated":"Mon, 11 Jan 2010 19:57:48 +0000","date_sent":"Mon, 11 Jan 2010 19:57:48 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753096","body":"Dude","status":"sending","direction":"inbound","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM99c423dbed59a5733d2c1c1c69a83a28.json"},{"sid":"SM7c186225ed59a5733d2c1c1c69a83a28","date_created":"Mon, 11 Jan 2010 19:55:56 +0000","date_updated":"Mon, 11 Jan 2010 19:55:57 +0000","date_sent":"Mon, 11 Jan 2010 19:55:57 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"Hello, Mobile Monkey","status":"sent","direction":"outbound-reply","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM7c186225ed59a5733d2c1c1c69a83a28.json"},{"sid":"SM431f8d3ded59a5733d2c1c1c69a83a28","date_created":"Mon, 11 Jan 2010 19:55:56 +0000","date_updated":"Mon, 11 Jan 2010 19:55:56 +0000","date_sent":"Mon, 11 Jan 2010 19:55:56 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753096","body":"This is a yesty","status":"sending","direction":"inbound","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM431f8d3ded59a5733d2c1c1c69a83a28.json"},{"sid":"SM0ab15a14ed59a5733d2c1c1c69a83a28","date_created":"Fri, 08 Jan 2010 19:46:42 +0000","date_updated":"Fri, 08 Jan 2010 19:46:42 +0000","date_sent":"Fri, 08 Jan 2010 19:46:42 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"Bad news Johnny, the server is down and it needs your help","status":"sent","direction":"outbound-api","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM0ab15a14ed59a5733d2c1c1c69a83a28.json"},{"sid":"SM791c9a74ed59a5733d2c1c1c69a83a28","date_created":"Fri, 08 Jan 2010 19:45:52 +0000","date_updated":"Fri, 08 Jan 2010 19:45:53 +0000","date_sent":"Fri, 08 Jan 2010 19:45:53 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"Bad news Johnny, the server is down and it needs your help","status":"sent","direction":"outbound-api","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM791c9a74ed59a5733d2c1c1c69a83a28.json"},{"sid":"SM393a14b3ed59a5733d2c1c1c69a83a28","date_created":"Thu, 07 Jan 2010 20:22:37 +0000","date_updated":"Thu, 07 Jan 2010 20:22:37 +0000","date_sent":"Thu, 07 Jan 2010 20:22:37 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753096","body":"Wake","status":"sent","direction":"inbound","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM393a14b3ed59a5733d2c1c1c69a83a28.json"},{"sid":"SM650c6414ed59a5733d2c1c1c69a83a28","date_created":"Thu, 07 Jan 2010 10:58:18 +0000","date_updated":"Thu, 07 Jan 2010 10:58:18 +0000","date_sent":"Thu, 07 Jan 2010 10:58:18 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753096","body":"Sleep","status":"sent","direction":"inbound","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM650c6414ed59a5733d2c1c1c69a83a28.json"},{"sid":"SM9a154589ed59a5733d2c1c1c69a83a28","date_created":"Thu, 07 Jan 2010 10:55:28 +0000","date_updated":"Thu, 07 Jan 2010 10:55:28 +0000","date_sent":"Thu, 07 Jan 2010 10:55:28 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753096","body":"Sleep","status":"sent","direction":"inbound","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM9a154589ed59a5733d2c1c1c69a83a28.json"},{"sid":"SMe286a21ded59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Jan 2010 02:35:19 +0000","date_updated":"Mon, 04 Jan 2010 02:35:21 +0000","date_sent":"Mon, 04 Jan 2010 02:35:21 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753099","from":"+141586753093","body":"Hey Mom, Monkey Party at 6PM. Bring Bananas!","status":"sent","direction":"outbound-api","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SMe286a21ded59a5733d2c1c1c69a83a28.json"},{"sid":"SM9fd3236ded59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Jan 2010 02:35:19 +0000","date_updated":"Mon, 04 Jan 2010 02:35:20 +0000","date_sent":"Mon, 04 Jan 2010 02:35:20 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"Hey Kyle Conroy, Monkey Party at 6PM. Bring Bananas!","status":"sent","direction":"outbound-api","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM9fd3236ded59a5733d2c1c1c69a83a28.json"},{"sid":"SMf3808ce5ed59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Jan 2010 02:07:45 +0000","date_updated":"Mon, 04 Jan 2010 02:07:46 +0000","date_sent":"Mon, 04 Jan 2010 02:07:46 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753099","from":"+141586753093","body":"Hey Mom, Monkey Party at 6PM. Bring Bananas!","status":"sent","direction":"outbound-api","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SMf3808ce5ed59a5733d2c1c1c69a83a28.json"},{"sid":"SMd6159b74ed59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Jan 2010 02:07:44 +0000","date_updated":"Mon, 04 Jan 2010 02:07:45 +0000","date_sent":"Mon, 04 Jan 2010 02:07:45 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"Hey Kyle Conroy, Monkey Party at 6PM. Bring Bananas!","status":"sent","direction":"outbound-api","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SMd6159b74ed59a5733d2c1c1c69a83a28.json"},{"sid":"SM60a32f65ed59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Jan 2010 02:07:16 +0000","date_updated":"Mon, 04 Jan 2010 02:07:17 +0000","date_sent":"Mon, 04 Jan 2010 02:07:17 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"Monkey Party at 6PM. Bring Bananas!","status":"sent","direction":"outbound-api","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM60a32f65ed59a5733d2c1c1c69a83a28.json"},{"sid":"SM2240adf6ed59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Jan 2010 02:05:57 +0000","date_updated":"Mon, 04 Jan 2010 02:06:02 +0000","date_sent":"Mon, 04 Jan 2010 02:06:02 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"Monkey Party at 6PM. Bring Bananas!","status":"sent","direction":"outbound-api","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM2240adf6ed59a5733d2c1c1c69a83a28.json"},{"sid":"SM61121366ed59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Jan 2010 02:04:51 +0000","date_updated":"Mon, 04 Jan 2010 02:04:53 +0000","date_sent":"Mon, 04 Jan 2010 02:04:53 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"Monkey Party at 6PM. Bring Bananas!","status":"sent","direction":"outbound-api","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM61121366ed59a5733d2c1c1c69a83a28.json"},{"sid":"SM85b4392fed59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Jan 2010 01:52:05 +0000","date_updated":"Mon, 04 Jan 2010 01:52:06 +0000","date_sent":"Mon, 04 Jan 2010 01:52:06 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"Monkey has messaged(415) 867-5309times","status":"sent","direction":"outbound-reply","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM85b4392fed59a5733d2c1c1c69a83a28.json"},{"sid":"SM6d1771bded59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Jan 2010 01:52:04 +0000","date_updated":"Mon, 04 Jan 2010 01:52:04 +0000","date_sent":"Mon, 04 Jan 2010 01:52:04 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753096","body":"You sick","status":"sent","direction":"inbound","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM6d1771bded59a5733d2c1c1c69a83a28.json"},{"sid":"SM4e355a73ed59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Jan 2010 01:50:17 +0000","date_updated":"Mon, 04 Jan 2010 01:50:18 +0000","date_sent":"Mon, 04 Jan 2010 01:50:18 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"Monkey has messaged(415) 867-5309times","status":"sent","direction":"outbound-reply","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM4e355a73ed59a5733d2c1c1c69a83a28.json"},{"sid":"SMe6b395a5ed59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Jan 2010 01:50:16 +0000","date_updated":"Mon, 04 Jan 2010 01:50:16 +0000","date_sent":"Mon, 04 Jan 2010 01:50:16 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753096","body":"Two?","status":"sent","direction":"inbound","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SMe6b395a5ed59a5733d2c1c1c69a83a28.json"},{"sid":"SM5c79073fed59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Jan 2010 01:50:00 +0000","date_updated":"Mon, 04 Jan 2010 01:50:02 +0000","date_sent":"Mon, 04 Jan 2010 01:50:02 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"Monkey has messaged(415) 867-5309times","status":"sent","direction":"outbound-reply","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM5c79073fed59a5733d2c1c1c69a83a28.json"},{"sid":"SM9925a1bded59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Jan 2010 01:50:00 +0000","date_updated":"Mon, 04 Jan 2010 01:50:00 +0000","date_sent":"Mon, 04 Jan 2010 01:50:00 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753096","body":"I have?","status":"sent","direction":"inbound","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SM9925a1bded59a5733d2c1c1c69a83a28.json"},{"sid":"SMedcc2c7eed59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Jan 2010 01:48:17 +0000","date_updated":"Mon, 04 Jan 2010 01:48:19 +0000","date_sent":"Mon, 04 Jan 2010 01:48:19 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753096","from":"+141586753093","body":"Monkey has messaged 4156694923 times","status":"sent","direction":"outbound-reply","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SMedcc2c7eed59a5733d2c1c1c69a83a28.json"},{"sid":"SMd28eea45ed59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Jan 2010 01:48:17 +0000","date_updated":"Mon, 04 Jan 2010 01:48:17 +0000","date_sent":"Mon, 04 Jan 2010 01:48:17 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753096","body":"Thank you?","status":"sent","direction":"inbound","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SMd28eea45ed59a5733d2c1c1c69a83a28.json"},{"sid":"SMb6d45ec3ed59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Jan 2010 01:46:54 +0000","date_updated":"Mon, 04 Jan 2010 01:47:00 +0000","date_sent":"Mon, 04 Jan 2010 01:47:00 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753099","from":"+141586753093","body":"Monkey, thanks for the message!","status":"sent","direction":"outbound-reply","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SMb6d45ec3ed59a5733d2c1c1c69a83a28.json"},{"sid":"SMe8598826ed59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Jan 2010 01:46:54 +0000","date_updated":"Mon, 04 Jan 2010 01:46:54 +0000","date_sent":"Mon, 04 Jan 2010 01:46:54 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","to":"+141586753093","from":"+141586753099","body":"O","status":"sent","direction":"inbound","price":"0.00000","api_version":"2008-08-01","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/SMS\/Messages\/SMe8598826ed59a5733d2c1c1c69a83a28.json"}]} diff --git a/tests/resources/transcriptions_instance.json b/tests/resources/transcriptions_instance.json deleted file mode 100644 index 1c0502b0b5..0000000000 --- a/tests/resources/transcriptions_instance.json +++ /dev/null @@ -1 +0,0 @@ -{"sid":"TR4d6e2ae6ed59a5733d2c1c1c69a83a28","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","date_created":"Sun, 13 Feb 2011 02:12:08 +0000","date_updated":"Sun, 13 Feb 2011 02:30:01 +0000","status":"failed","type":"fast","recording_sid":"RE83fccacded59a5733d2c1c1c69a83a28","duration":"1","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR4d6e2ae6ed59a5733d2c1c1c69a83a28.json"} diff --git a/tests/resources/transcriptions_list.json b/tests/resources/transcriptions_list.json deleted file mode 100644 index f88aef69c8..0000000000 --- a/tests/resources/transcriptions_list.json +++ /dev/null @@ -1 +0,0 @@ -{"page":0,"num_pages":3,"page_size":50,"total":101,"start":0,"end":49,"uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions.json","first_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions.json?Page=0&PageSize=50","previous_page_uri":null,"next_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions.json?Page=1&PageSize=50","last_page_uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions.json?Page=2&PageSize=50","transcriptions":[{"sid":"TR565eb796ed59a5733d2c1c1c69a83a28","date_created":"Tue, 15 Feb 2011 04:21:56 +0000","date_updated":"Tue, 15 Feb 2011 04:40:00 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"RE3ce9efa4ed59a5733d2c1c1c69a83a28","duration":"0","transcription_text":"(blank)","api_version":"2008-08-01","price":"0.00000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR565eb796ed59a5733d2c1c1c69a83a28.json"},{"sid":"TR4d6e2ae6ed59a5733d2c1c1c69a83a28","date_created":"Sun, 13 Feb 2011 02:12:08 +0000","date_updated":"Sun, 13 Feb 2011 02:30:01 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"RE83fccacded59a5733d2c1c1c69a83a28","duration":"1","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR4d6e2ae6ed59a5733d2c1c1c69a83a28.json"},{"sid":"TR52246cffed59a5733d2c1c1c69a83a28","date_created":"Sat, 12 Feb 2011 22:50:28 +0000","date_updated":"Sat, 12 Feb 2011 23:10:02 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"RE6df50791ed59a5733d2c1c1c69a83a28","duration":"1","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR52246cffed59a5733d2c1c1c69a83a28.json"},{"sid":"TRe38d7f5fed59a5733d2c1c1c69a83a28","date_created":"Sat, 12 Feb 2011 22:52:03 +0000","date_updated":"Sat, 12 Feb 2011 22:52:23 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"REee24eda1ed59a5733d2c1c1c69a83a28","duration":"4","transcription_text":"No everything is perfect they really enjoyed the website.","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRe38d7f5fed59a5733d2c1c1c69a83a28.json"},{"sid":"TRc399d006ed59a5733d2c1c1c69a83a28","date_created":"Thu, 03 Feb 2011 16:44:42 +0000","date_updated":"Thu, 03 Feb 2011 17:00:02 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"RE0341b5b1ed59a5733d2c1c1c69a83a28","duration":"0","transcription_text":"(blank)","api_version":"2008-08-01","price":"0.00000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRc399d006ed59a5733d2c1c1c69a83a28.json"},{"sid":"TR49859042ed59a5733d2c1c1c69a83a28","date_created":"Sat, 18 Dec 2010 22:40:42 +0000","date_updated":"Sat, 18 Dec 2010 23:00:02 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"RE118d90aded59a5733d2c1c1c69a83a28","duration":"2","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR49859042ed59a5733d2c1c1c69a83a28.json"},{"sid":"TR651952b5ed59a5733d2c1c1c69a83a28","date_created":"Sat, 18 Dec 2010 22:40:34 +0000","date_updated":"Sat, 18 Dec 2010 22:40:49 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"REa9f4ed87ed59a5733d2c1c1c69a83a28","duration":"4","transcription_text":"Austin so should.","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR651952b5ed59a5733d2c1c1c69a83a28.json"},{"sid":"TR869b0305ed59a5733d2c1c1c69a83a28","date_created":"Sun, 05 Dec 2010 21:01:22 +0000","date_updated":"Sun, 05 Dec 2010 21:01:42 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"REd9d83d23ed59a5733d2c1c1c69a83a28","duration":"5","transcription_text":"Hey.","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR869b0305ed59a5733d2c1c1c69a83a28.json"},{"sid":"TRf5b9166ced59a5733d2c1c1c69a83a28","date_created":"Thu, 11 Nov 2010 04:15:16 +0000","date_updated":"Thu, 11 Nov 2010 04:35:01 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"REf20ab89bed59a5733d2c1c1c69a83a28","duration":"0","transcription_text":"(blank)","api_version":"2008-08-01","price":"0.00000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRf5b9166ced59a5733d2c1c1c69a83a28.json"},{"sid":"TRd2428db2ed59a5733d2c1c1c69a83a28","date_created":"Thu, 28 Oct 2010 11:57:53 +0000","date_updated":"Thu, 28 Oct 2010 12:15:02 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"RE3b5d582aed59a5733d2c1c1c69a83a28","duration":"2","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRd2428db2ed59a5733d2c1c1c69a83a28.json"},{"sid":"TRcb42ce7fed59a5733d2c1c1c69a83a28","date_created":"Thu, 28 Oct 2010 11:56:47 +0000","date_updated":"Thu, 28 Oct 2010 11:57:12 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"RE6690bc5ded59a5733d2c1c1c69a83a28","duration":"4","transcription_text":"Hi ... recording something.","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRcb42ce7fed59a5733d2c1c1c69a83a28.json"},{"sid":"TRedd6fbb7ed59a5733d2c1c1c69a83a28","date_created":"Sat, 16 Oct 2010 05:27:03 +0000","date_updated":"Sat, 16 Oct 2010 05:45:02 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"REae531dfced59a5733d2c1c1c69a83a28","duration":"1","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRedd6fbb7ed59a5733d2c1c1c69a83a28.json"},{"sid":"TRf6a6119ded59a5733d2c1c1c69a83a28","date_created":"Wed, 06 Oct 2010 18:28:35 +0000","date_updated":"Wed, 06 Oct 2010 19:03:27 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"RE24a04918ed59a5733d2c1c1c69a83a28","duration":"0","transcription_text":"(blank)","api_version":"2008-08-01","price":"0.00000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRf6a6119ded59a5733d2c1c1c69a83a28.json"},{"sid":"TR81bc64a7ed59a5733d2c1c1c69a83a28","date_created":"Wed, 06 Oct 2010 18:28:29 +0000","date_updated":"Wed, 06 Oct 2010 18:45:02 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"REdc38c474ed59a5733d2c1c1c69a83a28","duration":"1","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR81bc64a7ed59a5733d2c1c1c69a83a28.json"},{"sid":"TR75d9f8daed59a5733d2c1c1c69a83a28","date_created":"Wed, 06 Oct 2010 18:28:22 +0000","date_updated":"Wed, 06 Oct 2010 18:36:03 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"RE1797d2e4ed59a5733d2c1c1c69a83a28","duration":"3","transcription_text":"For grandma.","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR75d9f8daed59a5733d2c1c1c69a83a28.json"},{"sid":"TR40f768dced59a5733d2c1c1c69a83a28","date_created":"Wed, 06 Oct 2010 16:51:28 +0000","date_updated":"Wed, 06 Oct 2010 17:10:02 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"RE7dda7275ed59a5733d2c1c1c69a83a28","duration":"1","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR40f768dced59a5733d2c1c1c69a83a28.json"},{"sid":"TR2244931ced59a5733d2c1c1c69a83a28","date_created":"Wed, 06 Oct 2010 16:51:36 +0000","date_updated":"Wed, 06 Oct 2010 17:10:02 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"REa42ad83ded59a5733d2c1c1c69a83a28","duration":"2","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR2244931ced59a5733d2c1c1c69a83a28.json"},{"sid":"TRf37fb96aed59a5733d2c1c1c69a83a28","date_created":"Wed, 06 Oct 2010 16:52:20 +0000","date_updated":"Wed, 06 Oct 2010 17:03:28 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"REe3ac5562ed59a5733d2c1c1c69a83a28","duration":"4","transcription_text":"Hi I'm very ... Spy snipers.","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRf37fb96aed59a5733d2c1c1c69a83a28.json"},{"sid":"TR5d21046bed59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Oct 2010 02:28:40 +0000","date_updated":"Mon, 04 Oct 2010 02:45:04 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"RE7934e357ed59a5733d2c1c1c69a83a28","duration":"2","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR5d21046bed59a5733d2c1c1c69a83a28.json"},{"sid":"TRb1a1c1e2ed59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Oct 2010 02:28:46 +0000","date_updated":"Mon, 04 Oct 2010 02:45:04 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"RE573e7920ed59a5733d2c1c1c69a83a28","duration":"1","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRb1a1c1e2ed59a5733d2c1c1c69a83a28.json"},{"sid":"TR5abadbc8ed59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Oct 2010 02:28:54 +0000","date_updated":"Mon, 04 Oct 2010 02:45:04 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"RE900b1db1ed59a5733d2c1c1c69a83a28","duration":"2","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR5abadbc8ed59a5733d2c1c1c69a83a28.json"},{"sid":"TR6dcb3df9ed59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Oct 2010 02:29:01 +0000","date_updated":"Mon, 04 Oct 2010 02:45:02 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"RE55e4a102ed59a5733d2c1c1c69a83a28","duration":"1","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR6dcb3df9ed59a5733d2c1c1c69a83a28.json"},{"sid":"TRe1b85d19ed59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Oct 2010 02:26:20 +0000","date_updated":"Mon, 04 Oct 2010 02:26:39 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"REd1893bcaed59a5733d2c1c1c69a83a28","duration":"9","transcription_text":"I need some help on friday doing anything.","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRe1b85d19ed59a5733d2c1c1c69a83a28.json"},{"sid":"TRf7729fbced59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Oct 2010 02:25:38 +0000","date_updated":"Mon, 04 Oct 2010 02:26:03 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"REc9d0c0b1ed59a5733d2c1c1c69a83a28","duration":"3","transcription_text":"Yo for.","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRf7729fbced59a5733d2c1c1c69a83a28.json"},{"sid":"TRb5cae78aed59a5733d2c1c1c69a83a28","date_created":"Mon, 04 Oct 2010 02:25:29 +0000","date_updated":"Mon, 04 Oct 2010 02:25:46 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"REbe832fe6ed59a5733d2c1c1c69a83a28","duration":"6","transcription_text":"Morris.","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRb5cae78aed59a5733d2c1c1c69a83a28.json"},{"sid":"TR6ae10341ed59a5733d2c1c1c69a83a28","date_created":"Wed, 22 Sep 2010 12:41:53 +0000","date_updated":"Wed, 22 Sep 2010 12:42:05 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"REd97482faed59a5733d2c1c1c69a83a28","duration":"3","transcription_text":".","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR6ae10341ed59a5733d2c1c1c69a83a28.json"},{"sid":"TRde45e7c1ed59a5733d2c1c1c69a83a28","date_created":"Tue, 21 Sep 2010 14:47:40 +0000","date_updated":"Tue, 21 Sep 2010 15:05:02 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"REd07ee10eed59a5733d2c1c1c69a83a28","duration":"2","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRde45e7c1ed59a5733d2c1c1c69a83a28.json"},{"sid":"TRf9eacf57ed59a5733d2c1c1c69a83a28","date_created":"Mon, 20 Sep 2010 23:53:47 +0000","date_updated":"Tue, 21 Sep 2010 00:42:37 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"RE75fdaa94ed59a5733d2c1c1c69a83a28","duration":"1","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRf9eacf57ed59a5733d2c1c1c69a83a28.json"},{"sid":"TR94d5eeeded59a5733d2c1c1c69a83a28","date_created":"Sun, 19 Sep 2010 02:35:08 +0000","date_updated":"Sun, 19 Sep 2010 02:55:02 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"RE1a6d455eed59a5733d2c1c1c69a83a28","duration":"1","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR94d5eeeded59a5733d2c1c1c69a83a28.json"},{"sid":"TR54111a2aed59a5733d2c1c1c69a83a28","date_created":"Sat, 18 Sep 2010 02:45:58 +0000","date_updated":"Sat, 18 Sep 2010 03:05:01 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"RE445b6f63ed59a5733d2c1c1c69a83a28","duration":"1","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR54111a2aed59a5733d2c1c1c69a83a28.json"},{"sid":"TR4698451aed59a5733d2c1c1c69a83a28","date_created":"Sat, 18 Sep 2010 02:44:08 +0000","date_updated":"Sat, 18 Sep 2010 02:44:29 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"RE6d3646c3ed59a5733d2c1c1c69a83a28","duration":"3","transcription_text":"Mike.","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR4698451aed59a5733d2c1c1c69a83a28.json"},{"sid":"TRa0a1808bed59a5733d2c1c1c69a83a28","date_created":"Fri, 17 Sep 2010 12:07:11 +0000","date_updated":"Fri, 17 Sep 2010 12:25:01 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"RE721ff2a7ed59a5733d2c1c1c69a83a28","duration":"1","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRa0a1808bed59a5733d2c1c1c69a83a28.json"},{"sid":"TR5497b744ed59a5733d2c1c1c69a83a28","date_created":"Mon, 13 Sep 2010 20:06:36 +0000","date_updated":"Mon, 13 Sep 2010 20:25:01 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"REcbb9d0e5ed59a5733d2c1c1c69a83a28","duration":"2","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR5497b744ed59a5733d2c1c1c69a83a28.json"},{"sid":"TR6c0417abed59a5733d2c1c1c69a83a28","date_created":"Mon, 13 Sep 2010 20:15:26 +0000","date_updated":"Mon, 13 Sep 2010 20:17:30 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"REdab02432ed59a5733d2c1c1c69a83a28","duration":"3","transcription_text":"Hey.","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR6c0417abed59a5733d2c1c1c69a83a28.json"},{"sid":"TR803bdd03ed59a5733d2c1c1c69a83a28","date_created":"Mon, 13 Sep 2010 20:16:34 +0000","date_updated":"Mon, 13 Sep 2010 20:17:12 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"RE00494485ed59a5733d2c1c1c69a83a28","duration":"3","transcription_text":"I'm very Cool.","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR803bdd03ed59a5733d2c1c1c69a83a28.json"},{"sid":"TR98ad4aa7ed59a5733d2c1c1c69a83a28","date_created":"Mon, 13 Sep 2010 20:15:35 +0000","date_updated":"Mon, 13 Sep 2010 20:16:11 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"REb21cfb3eed59a5733d2c1c1c69a83a28","duration":"3","transcription_text":"Romero.","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR98ad4aa7ed59a5733d2c1c1c69a83a28.json"},{"sid":"TR509010daed59a5733d2c1c1c69a83a28","date_created":"Mon, 13 Sep 2010 20:06:27 +0000","date_updated":"Mon, 13 Sep 2010 20:09:13 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"REc472d728ed59a5733d2c1c1c69a83a28","duration":"5","transcription_text":"Hey hello thanks.","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR509010daed59a5733d2c1c1c69a83a28.json"},{"sid":"TRe0036d35ed59a5733d2c1c1c69a83a28","date_created":"Thu, 02 Sep 2010 13:35:34 +0000","date_updated":"Thu, 02 Sep 2010 13:55:02 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"RE26db132bed59a5733d2c1c1c69a83a28","duration":"1","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRe0036d35ed59a5733d2c1c1c69a83a28.json"},{"sid":"TRc16d0edeed59a5733d2c1c1c69a83a28","date_created":"Thu, 02 Sep 2010 13:34:55 +0000","date_updated":"Thu, 02 Sep 2010 13:50:02 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"RE71e8926ded59a5733d2c1c1c69a83a28","duration":"1","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRc16d0edeed59a5733d2c1c1c69a83a28.json"},{"sid":"TRd4a5851ded59a5733d2c1c1c69a83a28","date_created":"Thu, 02 Sep 2010 13:34:47 +0000","date_updated":"Thu, 02 Sep 2010 13:35:15 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"REb33b7b98ed59a5733d2c1c1c69a83a28","duration":"6","transcription_text":"Hello hello.","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRd4a5851ded59a5733d2c1c1c69a83a28.json"},{"sid":"TRda6ff6f5ed59a5733d2c1c1c69a83a28","date_created":"Wed, 01 Sep 2010 16:43:50 +0000","date_updated":"Wed, 01 Sep 2010 17:00:03 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"REd65d5054ed59a5733d2c1c1c69a83a28","duration":"1","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRda6ff6f5ed59a5733d2c1c1c69a83a28.json"},{"sid":"TRf1d9ad4fed59a5733d2c1c1c69a83a28","date_created":"Wed, 01 Sep 2010 16:38:09 +0000","date_updated":"Wed, 01 Sep 2010 16:55:02 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"RE33c6fd8eed59a5733d2c1c1c69a83a28","duration":"1","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRf1d9ad4fed59a5733d2c1c1c69a83a28.json"},{"sid":"TR4b59e241ed59a5733d2c1c1c69a83a28","date_created":"Wed, 01 Sep 2010 16:43:42 +0000","date_updated":"Wed, 01 Sep 2010 16:44:01 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"RE1ad56651ed59a5733d2c1c1c69a83a28","duration":"3","transcription_text":"Hello.","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR4b59e241ed59a5733d2c1c1c69a83a28.json"},{"sid":"TR7dc8e0c3ed59a5733d2c1c1c69a83a28","date_created":"Wed, 01 Sep 2010 16:39:02 +0000","date_updated":"Wed, 01 Sep 2010 16:39:32 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"REe462c807ed59a5733d2c1c1c69a83a28","duration":"3","transcription_text":"Hello in like bring.","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR7dc8e0c3ed59a5733d2c1c1c69a83a28.json"},{"sid":"TRe1faf9cced59a5733d2c1c1c69a83a28","date_created":"Wed, 01 Sep 2010 16:38:02 +0000","date_updated":"Wed, 01 Sep 2010 16:38:40 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"RE99a77b1bed59a5733d2c1c1c69a83a28","duration":"3","transcription_text":".","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TRe1faf9cced59a5733d2c1c1c69a83a28.json"},{"sid":"TR266e1283ed59a5733d2c1c1c69a83a28","date_created":"Wed, 01 Sep 2010 15:15:56 +0000","date_updated":"Wed, 01 Sep 2010 15:35:01 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"REdf0f01fbed59a5733d2c1c1c69a83a28","duration":"2","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR266e1283ed59a5733d2c1c1c69a83a28.json"},{"sid":"TR87c0ab57ed59a5733d2c1c1c69a83a28","date_created":"Wed, 01 Sep 2010 15:15:48 +0000","date_updated":"Wed, 01 Sep 2010 15:16:10 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"RE19e96a31ed59a5733d2c1c1c69a83a28","duration":"6","transcription_text":"Hey.","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR87c0ab57ed59a5733d2c1c1c69a83a28.json"},{"sid":"TR1250b1d0ed59a5733d2c1c1c69a83a28","date_created":"Wed, 01 Sep 2010 02:19:11 +0000","date_updated":"Wed, 01 Sep 2010 02:35:02 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"REbcfbcfc4ed59a5733d2c1c1c69a83a28","duration":"1","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR1250b1d0ed59a5733d2c1c1c69a83a28.json"},{"sid":"TR2f40b3aded59a5733d2c1c1c69a83a28","date_created":"Wed, 01 Sep 2010 02:19:18 +0000","date_updated":"Wed, 01 Sep 2010 02:35:02 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"failed","type":"fast","recording_sid":"REaaa7ee0ced59a5733d2c1c1c69a83a28","duration":"1","transcription_text":"(blank)","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR2f40b3aded59a5733d2c1c1c69a83a28.json"},{"sid":"TR40825aeded59a5733d2c1c1c69a83a28","date_created":"Wed, 01 Sep 2010 02:20:27 +0000","date_updated":"Wed, 01 Sep 2010 02:21:12 +0000","account_sid":"AC4bf2dafbed59a5733d2c1c1c69a83a28","status":"completed","type":"fast","recording_sid":"RE6f1ca7efed59a5733d2c1c1c69a83a28","duration":"14","transcription_text":"I found the spam entry to the contest on hacker news hi I'm very interested in Forrest forms 4000 hey and ... I am gonna call me hello.","api_version":"2008-08-01","price":"-0.05000","uri":"\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Transcriptions\/TR40825aeded59a5733d2c1c1c69a83a28.json"}]} diff --git a/tests/resources/usage_records_list.json b/tests/resources/usage_records_list.json deleted file mode 100644 index da581316d0..0000000000 --- a/tests/resources/usage_records_list.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "page": 0, - "num_pages": 1, - "page_size": 50, - "total": 2, - "start": 0, - "end": 1, - "uri": "\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Usage/Records.json?Page=0&PageSize=50", - "previous_page_uri": null, - "next_page_uri": "\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls.json?Page=1&PageSize=50", - "last_page_uri": "\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls.json?Page=10&PageSize=50", - "first_page_uri": "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records.json?Page=0&PageSize=50", - "usage_records": [ - { - "category": "calleridlookups", - "subresource_uris": [ - "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records/AllTime.json?Category=calleridlookups", - "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records/Today.json?Category=calleridlookups", - "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records/Yesterday.json?Category=calleridlookups", - "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records/ThisMonth.json?Category=calleridlookups", - "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records/LastMonth.json?Category=calleridlookups", - "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records/ThisYear.json?Category=calleridlookups", - "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records/LastYear.json?Category=calleridlookups", - "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records/Daily.json?Category=calleridlookups", - "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records/Monthly.json?Category=calleridlookups", - "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records/Yearly.json?Category=calleridlookups" - ], - "description": "Caller ID lookups", - "end_date": "2012-09-29", - "usage_unit": "Lookups", - "price": "0", - "uri": "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records.json?Category=calleridlookups&StartDate=2012-09-22&EndDate=2012-09-29", - "number": "0", - "account_sid": "ACed70abd024d3f57a4027b5dc2ca88d5b", - "trigger_uri": "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Triggers.json?UsageCategory=calleridlookups", - "usage": "0", - "start_date": "2012-09-22" - }, - { - "category": "recordings", - "subresource_uris": [ - "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records/AllTime.json?Category=recordings", - "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records/Today.json?Category=recordings", - "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records/Yesterday.json?Category=recordings", - "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records/ThisMonth.json?Category=recordings", - "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records/LastMonth.json?Category=recordings", - "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records/ThisYear.json?Category=recordings", - "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records/LastYear.json?Category=recordings", - "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records/Daily.json?Category=recordings", - "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records/Monthly.json?Category=recordings", - "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records/Yearly.json?Category=recordings" - ], - "description": "Call recordings", - "end_date": "2012-09-29", - "usage_unit": "Minutes", - "price": "0", - "uri": "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records.json?Category=recordings&StartDate=2012-09-22&EndDate=2012-09-29", - "number": "0", - "account_sid": "ACed70abd024d3f57a4027b5dc2ca88d5b", - "trigger_uri": "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Triggers.json?UsageCategory=recordings", - "usage": "0", - "start_date": "2012-09-22" - } - ] -} diff --git a/tests/resources/usage_triggers_instance.json b/tests/resources/usage_triggers_instance.json deleted file mode 100644 index 0f66a2bc36..0000000000 --- a/tests/resources/usage_triggers_instance.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "sid": "UT33c6aeeba34e48f38d6899ea5b765ad4", - "date_updated": "2012-09-29 12:47:54", - "current_usage_value": "7", - "friendly_name": "Trigger for calls at usage of 500", - "uri": "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Triggers/UT33c6aeeba34e48f38d6899ea5b765ad4/UT33c6aeeba34e48f38d6899ea5b765ad4.json", - "usage_record_uri": "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records.json?Category=calls", - "trigger_by": "usage", - "callback_method": "POST", - "date_created": "2012-09-29 12:45:43", - "callback_url": "http://www.example.com/", - "recurring": "daily", - "usage_category": "calls", - "trigger_value": "500.000000" -} diff --git a/tests/resources/usage_triggers_list.json b/tests/resources/usage_triggers_list.json deleted file mode 100644 index 7272eb7392..0000000000 --- a/tests/resources/usage_triggers_list.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "page": 0, - "num_pages": 1, - "page_size": 50, - "total": 2, - "start": 0, - "end": 1, - "uri": "\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Usage/Triggers.json?Page=0&PageSize=50", - "previous_page_uri": null, - "next_page_uri": "\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls.json?Page=1&PageSize=50", - "last_page_uri": "\/2010-04-01\/Accounts\/AC4bf2dafbed59a5733d2c1c1c69a83a28\/Calls.json?Page=10&PageSize=50", - "usage_triggers": [ - { - "sid": "UT33c6aeeba34e48f38d6899ea5b765ad4", - "date_updated": "2012-09-29 12:47:54", - "current_usage_value": "7", - "friendly_name": "Trigger for calls at usage of 500", - "uri": "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Triggers/UT33c6aeeba34e48f38d6899ea5b765ad4/UT33c6aeeba34e48f38d6899ea5b765ad4.json", - "usage_record_uri": "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records.json?Category=calls", - "trigger_by": "usage", - "callback_method": "POST", - "date_created": "2012-09-29 12:45:43", - "callback_url": "http://www.example.com/", - "recurring": "daily", - "usage_category": "calls", - "trigger_value": "500.000000" - }, { - "sid": "UT33c6aeeba34e48f38d6899ea5b765ad5", - "date_updated": "2012-09-30 12:47:54", - "current_usage_value": "7", - "friendly_name": "Trigger for calls at usage of 500", - "uri": "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Triggers/UT33c6aeeba34e48f38d6899ea5b765ad4/UT33c6aeeba34e48f38d6899ea5b765ad4.json", - "usage_record_uri": "/2010-04-01/Accounts/ACed70abd024d3f57a4027b5dc2ca88d5b/Usage/Records.json?Category=calls", - "trigger_by": "usage", - "callback_method": "POST", - "date_created": "2012-09-30 12:45:43", - "callback_url": "http://www.example.com/", - "recurring": "daily", - "usage_category": "calls", - "trigger_value": "500.000000" - } - ] -} diff --git a/tests/test_accounts.py b/tests/test_accounts.py deleted file mode 100644 index 10971c0505..0000000000 --- a/tests/test_accounts.py +++ /dev/null @@ -1,33 +0,0 @@ -import unittest - -from mock import Mock, patch - -from tools import create_mock_json -from twilio.rest.resources import Account - - -class AccountTest(unittest.TestCase): - - @patch("twilio.rest.resources.base.make_twilio_request") - def test_usage_records_subresource(self, request): - resp = create_mock_json("tests/resources/usage_records_list.json") - request.return_value = resp - - mock = Mock() - mock.uri = "/base" - account = Account(mock, 'AC123') - account.load_subresources() - records = account.usage_records.list() - self.assertEquals(len(records), 2) - - @patch("twilio.rest.resources.base.make_twilio_request") - def test_usage_triggers_subresource(self, request): - resp = create_mock_json("tests/resources/usage_triggers_list.json") - request.return_value = resp - - mock = Mock() - mock.uri = "/base" - account = Account(mock, 'AC123') - account.load_subresources() - triggers = account.usage_triggers.list() - self.assertEquals(len(triggers), 2) diff --git a/tests/test_applications.py b/tests/test_applications.py deleted file mode 100644 index be1a5e71c2..0000000000 --- a/tests/test_applications.py +++ /dev/null @@ -1,58 +0,0 @@ -import six -if six.PY3: - import unittest -else: - import unittest2 as unittest - -from mock import Mock -from twilio.rest.resources import Applications - - -class ApplicationsTest(unittest.TestCase): - def setUp(self): - self.parent = Mock() - self.resource = Applications("http://api.twilio.com", ("user", "pass")) - - def test_create_appliation_sms_url_method(self): - self.resource.create_instance = Mock() - self.resource.create(sms_method="hey") - self.resource.create_instance.assert_called_with({"sms_method": "hey"}) - - def test_create_appliation_sms_url(self): - self.resource.create_instance = Mock() - self.resource.create(sms_url="hey") - self.resource.create_instance.assert_called_with({"sms_url": "hey"}) - - def test_update_appliation_sms_url_method(self): - self.resource.update_instance = Mock() - self.resource.update("123", sms_method="hey") - self.resource.update_instance.assert_called_with( - "123", {"sms_method": "hey"}) - - def test_update_appliation_sms_url(self): - self.resource.update_instance = Mock() - self.resource.update("123", sms_url="hey") - self.resource.update_instance.assert_called_with( - "123", {"sms_url": "hey"}) - - def test_update(self): - request = Mock() - request.return_value = (Mock(), {"sid": "123"}) - self.resource.request = request - - self.resource.update("123", voice_url="hey") - - uri = "http://api.twilio.com/Applications/123" - request.assert_called_with("POST", uri, data={"VoiceUrl": "hey"}) - - def test_create(self): - request = Mock() - request.return_value = (request, {"sid": "123"}) - request.status_code = 201 - - self.resource.request = request - - self.resource.create(friendly_name="hey") - - uri = "http://api.twilio.com/Applications" - request.assert_called_with("POST", uri, data={"FriendlyName": "hey"}) diff --git a/tests/test_authorized_connect_apps.py b/tests/test_authorized_connect_apps.py deleted file mode 100644 index 372ed89b9c..0000000000 --- a/tests/test_authorized_connect_apps.py +++ /dev/null @@ -1,69 +0,0 @@ -from __future__ import with_statement -import six -if six.PY3: - import unittest -else: - import unittest2 as unittest - -from mock import Mock, patch -from twilio.rest.resources import AuthorizedConnectApps -from twilio.rest.resources import AuthorizedConnectApp - - -class AuthorizedConnectAppTest(unittest.TestCase): - - def setUp(self): - self.parent = Mock() - self.uri = "/base" - self.auth = ("AC123", "token") - self.resource = AuthorizedConnectApps(self.uri, self.auth) - - @patch("twilio.rest.resources.base.make_twilio_request") - def test_get(self, mock): - mock.return_value = Mock() - mock.return_value.content = '{"connect_app_sid": "SID"}' - - self.resource.get("SID") - mock.assert_called_with("GET", "/base/AuthorizedConnectApps/SID", - auth=self.auth) - - @patch("twilio.rest.resources.base.make_twilio_request") - def test_list(self, mock): - mock.return_value = Mock() - mock.return_value.content = '{"authorized_connect_apps": []}' - - self.resource.list() - mock.assert_called_with("GET", "/base/AuthorizedConnectApps", - params={}, auth=self.auth) - - def test_load(self): - instance = AuthorizedConnectApp(Mock(), "sid") - instance.load({ - "connect_app_sid": "SID", - "account_sid": "AC8dfe2f2358cf421cb6134cf6f217c6a3", - "permissions": ["get-all"], - "connect_app_friendly_name": "foo", - "connect_app_description": "bat", - "connect_app_company_name": "bar", - "connect_app_homepage_url": "http://www.google.com", - "uri": "/2010-04-01/Accounts/", - }) - - self.assertEquals(instance.permissions, ["get-all"]) - self.assertEquals(instance.sid, "SID") - self.assertEquals(instance.friendly_name, "foo") - self.assertEquals(instance.description, "bat") - self.assertEquals(instance.homepage_url, "http://www.google.com") - self.assertEquals(instance.company_name, "bar") - - def test_delete(self): - with self.assertRaises(AttributeError): - self.resource.delete() - - def test_create(self): - with self.assertRaises(AttributeError): - self.resource.create() - - def test_update(self): - with self.assertRaises(AttributeError): - self.resource.update() diff --git a/tests/test_available_phonenumber.py b/tests/test_available_phonenumber.py deleted file mode 100644 index 9f34e61e33..0000000000 --- a/tests/test_available_phonenumber.py +++ /dev/null @@ -1,98 +0,0 @@ -from __future__ import with_statement - -import six -if six.PY3: - import unittest -else: - import unittest2 as unittest - -from mock import Mock -from twilio import TwilioException -from twilio.rest.resources import AvailablePhoneNumber -from twilio.rest.resources import AvailablePhoneNumbers -from twilio.rest.resources import PhoneNumbers - - -class AvailablePhoneNumberTest(unittest.TestCase): - - def setUp(self): - self.parent = Mock() - self.instance = AvailablePhoneNumber(self.parent) - - def test_init(self): - self.assertEquals(self.instance.name, "") - - def test_purchase(self): - self.instance.phone_number = "+123" - self.instance.purchase(voice_url="http://www.google.com") - - self.parent.purchase.assert_called_with( - voice_url="http://www.google.com", - phone_number="+123") - - -class AvailabePhoneNumbersTest(unittest.TestCase): - - def setUp(self): - self.resource = AvailablePhoneNumbers("http://api.twilio.com", - ("user", "pass"), Mock()) - - def test_get(self): - with self.assertRaises(TwilioException): - self.resource.get("PN123") - - def test_list(self): - request = Mock() - request.return_value = (Mock(), {"available_phone_numbers": []}) - self.resource.request = request - - self.resource.list() - - uri = "http://api.twilio.com/AvailablePhoneNumbers/US/Local" - request.assert_called_with("GET", uri, params={}) - - def test_load_instance(self): - instance = self.resource.load_instance({"hey": "you"}) - self.assertIsInstance(instance.parent, Mock) - self.assertEquals(instance.hey, "you") - - def test_purchase_status_callback(self): - request = Mock() - request.return_value = (Mock(), {"available_phone_numbers": []}) - self.resource.request = request - - self.resource.list() - - uri = "http://api.twilio.com/AvailablePhoneNumbers/US/Local" - request.assert_called_with("GET", uri, params={}) - - -class PhoneNumbersTest(unittest.TestCase): - - def setUp(self): - self.resource = PhoneNumbers("http://api.twilio.com", - ("user", "pass")) - - def test_reference(self): - self.assertEquals(self.resource.available_phone_numbers.phone_numbers, - self.resource) - - def test_purchase_status_callback(self): - request = Mock() - response = Mock() - response.status_code = 201 - request.return_value = (response, {"sid": ""}) - self.resource.request = request - - self.resource.purchase(area_code="530", status_callback_url="http://", - status_callback_method="POST") - - uri = "http://api.twilio.com/IncomingPhoneNumbers" - - data = { - "AreaCode": "530", - "StatusCallback": "http://", - "StatusCallbackMethod": "POST", - } - - request.assert_called_with("POST", uri, data=data) diff --git a/tests/test_base_resource.py b/tests/test_base_resource.py deleted file mode 100644 index b50aa83859..0000000000 --- a/tests/test_base_resource.py +++ /dev/null @@ -1,117 +0,0 @@ -# -*- coding: utf-8 -*- -from __future__ import with_statement -import six -if six.PY3: - import unittest -else: - import unittest2 as unittest - -from mock import Mock -from nose.tools import assert_equals -from twilio.rest.resources import Resource -from twilio.rest.resources import ListResource -from twilio.rest.resources import InstanceResource -from six import advance_iterator - -base_uri = "https://api.twilio.com/2010-04-01" -account_sid = "AC123" -auth = (account_sid, "token") - - -def test_resource_init(): - r = Resource(base_uri, auth) - uri = "%s/%s" % (base_uri, r.name) - - assert_equals(r.base_uri, base_uri) - assert_equals(r.auth, auth) - assert_equals(r.uri, uri) - - -def test_equivalence(): - p = ListResource(base_uri, auth) - r1 = p.load_instance({"sid": "AC123"}) - r2 = p.load_instance({"sid": "AC123"}) - assert_equals(r1, r2) - - -class ListResourceTest(unittest.TestCase): - - def setUp(self): - self.r = ListResource(base_uri, auth) - - def testListResourceInit(self): - uri = "%s/%s" % (base_uri, self.r.name) - self.assertEquals(self.r.uri, uri) - - def testKeyValueLower(self): - self.assertEquals(self.r.key, self.r.name.lower()) - - def testIterNoKey(self): - self.r.request = Mock() - self.r.request.return_value = Mock(), {} - - with self.assertRaises(StopIteration): - advance_iterator(self.r.iter()) - - def testRequest(self): - self.r.request = Mock() - self.r.request.return_value = Mock(), {self.r.key: [{'sid': 'foo'}]} - advance_iterator(self.r.iter()) - self.r.request.assert_called_with("GET", "https://api.twilio.com/2010-04-01/Resources", params={}) - - def testIterOneItem(self): - self.r.request = Mock() - self.r.request.return_value = Mock(), {self.r.key: [{'sid': 'foo'}]} - - items = self.r.iter() - advance_iterator(items) - - with self.assertRaises(StopIteration): - advance_iterator(items) - - def testIterNoNextPage(self): - self.r.request = Mock() - self.r.request.return_value = Mock(), {self.r.key: []} - - with self.assertRaises(StopIteration): - advance_iterator(self.r.iter()) - - def testKeyValue(self): - self.r.key = "Hey" - self.assertEquals(self.r.key, "Hey") - - def testInstanceLoading(self): - instance = self.r.load_instance({"sid": "foo"}) - - self.assertIsInstance(instance, InstanceResource) - self.assertEquals(instance.sid, "foo") - - -class testInstanceResourceInit(unittest.TestCase): - - def setUp(self): - self.parent = ListResource(base_uri, auth) - self.r = InstanceResource(self.parent, "123") - self.uri = "%s/%s" % (self.parent.uri, "123") - - def testInit(self): - self.assertEquals(self.r.uri, self.uri) - - def testLoad(self): - self.r.load({"hey": "you"}) - self.assertEquals(self.r.hey, "you") - - def testLoadWithUri(self): - self.r.load({"hey": "you", "uri": "foobar"}) - self.assertEquals(self.r.hey, "you") - self.assertEquals(self.r.uri, self.uri) - - def testLoadWithFrom(self): - self.r.load({"from": "foo"}) - self.assertEquals(self.r.from_, "foo") - - def testLoadSubresources(self): - m = Mock() - self.r.subresources = [m] - self.r.load_subresources() - m.assert_called_with(self.r.uri, self.r.auth) diff --git a/tests/test_calls.py b/tests/test_calls.py deleted file mode 100644 index 83fa6198e8..0000000000 --- a/tests/test_calls.py +++ /dev/null @@ -1,87 +0,0 @@ -from datetime import date -from mock import patch -from nose.tools import raises, assert_true -from twilio.rest.resources import Calls -from tools import create_mock_json - -BASE_URI = "https://api.twilio.com/2010-04-01/Accounts/AC123" -ACCOUNT_SID = "AC123" -AUTH = (ACCOUNT_SID, "token") -CALL_SID = "CA47e13748ed59a5733d2c1c1c69a83a28" - -list_resource = Calls(BASE_URI, AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_create_call(mock): - resp = create_mock_json("tests/resources/calls_instance.json") - resp.status_code = 201 - mock.return_value = resp - - uri = "%s/Calls" % (BASE_URI) - list_resource.create("TO", "FROM", "url", record=True, application_sid='APPSID') - exp_params = { - 'To': "TO", - 'From': "FROM", - 'Url': "url", - 'Record': "true", - 'ApplicationSid': 'APPSID', - } - - mock.assert_called_with("POST", uri, data=exp_params, auth=AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_paging(mock): - resp = create_mock_json("tests/resources/calls_list.json") - mock.return_value = resp - - uri = "%s/Calls" % (BASE_URI) - list_resource.list(started_before=date(2010, 12, 5)) - exp_params = {'StartTime<': '2010-12-05'} - - mock.assert_called_with("GET", uri, params=exp_params, auth=AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_get(mock): - resp = create_mock_json("tests/resources/calls_instance.json") - mock.return_value = resp - - uri = "%s/Calls/%s" % (BASE_URI, CALL_SID) - list_resource.get(CALL_SID) - - mock.assert_called_with("GET", uri, auth=AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_hangup(mock): - resp = create_mock_json("tests/resources/calls_instance.json") - resp.status_code = 204 - mock.return_value = resp - - uri = "%s/Calls/%s" % (BASE_URI, CALL_SID) - r = list_resource.hangup(CALL_SID) - exp_data = {"Status": "completed"} - - mock.assert_called_with("POST", uri, data=exp_data, auth=AUTH) - assert_true(r) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_cancel(mock): - resp = create_mock_json("tests/resources/calls_instance.json") - resp.status_code = 204 - mock.return_value = resp - - uri = "%s/Calls/%s" % (BASE_URI, CALL_SID) - r = list_resource.cancel(CALL_SID) - exp_data = {"Status": "canceled"} - - mock.assert_called_with("POST", uri, data=exp_data, auth=AUTH) - assert_true(r) - - -@raises(AttributeError) -def test_create(): - list_resource.delete diff --git a/tests/test_client.py b/tests/test_client.py deleted file mode 100644 index 04487d2d61..0000000000 --- a/tests/test_client.py +++ /dev/null @@ -1,47 +0,0 @@ -import six -if six.PY3: - import unittest -else: - import unittest2 as unittest - -from twilio.rest import TwilioRestClient, resources -from mock import patch, Mock -from tools import create_mock_json - -AUTH = ("ACCOUNT_SID", "AUTH_TOKEN") - - -class RestClientTest(unittest.TestCase): - - def setUp(self): - self.client = TwilioRestClient("ACCOUNT_SID", "AUTH_TOKEN") - - @patch("twilio.rest.make_request") - def test_request(self, mock): - self.client.request("2010-04-01", method="GET") - mock.assert_called_with("GET", "https://api.twilio.com/2010-04-01", - headers={"User-Agent": 'twilio-python'}, params={}, - auth=AUTH, data=None) - - def test_connect_apps(self): - self.assertIsInstance(self.client.connect_apps, - resources.ConnectApps) - - def test_authorized_apps(self): - self.assertIsInstance(self.client.authorized_connect_apps, - resources.AuthorizedConnectApps) - - @patch("twilio.rest.resources.base.make_request") - def test_conferences(self, mock): - mock.return_value = Mock() - mock.return_value.ok = True - mock.return_value.content = '{"conferences": []}' - self.client.conferences.list() - - @patch("twilio.rest.resources.base.make_twilio_request") - def test_members(self, mock): - resp = create_mock_json("tests/resources/members_list.json") - mock.return_value = resp - self.client.members("QU123").list() - uri = "https://api.twilio.com/2010-04-01/Accounts/ACCOUNT_SID/Queues/QU123/Members" - mock.assert_called_with("GET", uri, params={}, auth=AUTH) diff --git a/tests/test_conferences.py b/tests/test_conferences.py deleted file mode 100644 index 362657589e..0000000000 --- a/tests/test_conferences.py +++ /dev/null @@ -1,48 +0,0 @@ -import six -if six.PY3: - import unittest -else: - import unittest2 as unittest - -from datetime import date -from mock import Mock -from twilio.rest.resources import Conferences - -DEFAULT = { - 'DateUpdated<': None, - 'DateUpdated>': None, - 'DateUpdated': None, - 'DateCreated<': None, - 'DateCreated>': None, - 'DateCreated': None, - } - - -class ConferenceTest(unittest.TestCase): - - def setUp(self): - self.resource = Conferences("foo", ("sid", "token")) - self.params = DEFAULT.copy() - - def test_list(self): - self.resource.get_instances = Mock() - self.resource.list() - self.resource.get_instances.assert_called_with(self.params) - - def test_list_after(self): - self.resource.get_instances = Mock() - self.resource.list(created_after=date(2011, 1, 1)) - self.params["DateCreated>"] = "2011-01-01" - self.resource.get_instances.assert_called_with(self.params) - - def test_list_on(self): - self.resource.get_instances = Mock() - self.resource.list(created=date(2011, 1, 1)) - self.params["DateCreated"] = "2011-01-01" - self.resource.get_instances.assert_called_with(self.params) - - def test_list_before(self): - self.resource.get_instances = Mock() - self.resource.list(created_before=date(2011, 1, 1)) - self.params["DateCreated<"] = "2011-01-01" - self.resource.get_instances.assert_called_with(self.params) diff --git a/tests/test_connect_apps.py b/tests/test_connect_apps.py deleted file mode 100644 index 636765be2f..0000000000 --- a/tests/test_connect_apps.py +++ /dev/null @@ -1,57 +0,0 @@ -from __future__ import with_statement -import six -if six.PY3: - import unittest -else: - import unittest2 as unittest - -from mock import Mock, patch -from twilio.rest.resources import ConnectApps - - -class ConnectAppTest(unittest.TestCase): - - def setUp(self): - self.parent = Mock() - self.uri = "/base" - self.auth = ("AC123", "token") - self.resource = ConnectApps(self.uri, self.auth) - - @patch("twilio.rest.resources.base.make_twilio_request") - def test_get(self, mock): - mock.return_value = Mock() - mock.return_value.content = '{"sid": "SID"}' - - self.resource.get("SID") - mock.assert_called_with("GET", "/base/ConnectApps/SID", - auth=self.auth) - - @patch("twilio.rest.resources.base.make_twilio_request") - def test_list_with_paging(self, mock): - mock.return_value = Mock() - mock.return_value.content = '{"connect_apps": []}' - - self.resource.list(page=1, page_size=50) - mock.assert_called_with("GET", "/base/ConnectApps", - params={"Page": 1, "PageSize": 50}, auth=self.auth) - - @patch("twilio.rest.resources.base.make_twilio_request") - def test_list(self, mock): - mock.return_value = Mock() - mock.return_value.content = '{"connect_apps": []}' - - self.resource.list() - mock.assert_called_with("GET", "/base/ConnectApps", - params={}, auth=self.auth) - - def test_create(self): - with self.assertRaises(AttributeError): - self.resource.create() - - def test_delete(self): - with self.assertRaises(AttributeError): - self.resource.delete() - - def test_update(self): - with self.assertRaises(AttributeError): - self.resource.update() diff --git a/tests/test_core.py b/tests/test_core.py deleted file mode 100644 index c1b60ceeea..0000000000 --- a/tests/test_core.py +++ /dev/null @@ -1,90 +0,0 @@ -import six -if six.PY3: - import unittest -else: - import unittest2 as unittest -from datetime import datetime -from datetime import date -from twilio.rest.resources import parse_date -from twilio.rest.resources import transform_params -from twilio.rest.resources import convert_keys -from twilio.rest.resources import convert_case -from twilio.rest.resources import convert_boolean -from twilio.rest.resources import normalize_dates - - -class CoreTest(unittest.TestCase): - - def test_date(self): - d = date(2009, 10, 10) - self.assertEquals(parse_date(d), "2009-10-10") - - def test_datetime(self): - d = datetime(2009, 10, 10) - self.assertEquals(parse_date(d), "2009-10-10") - - def test_string_date(self): - d = "2009-10-10" - self.assertEquals(parse_date(d), "2009-10-10") - - def test_string_date_none(self): - d = None - self.assertEquals(parse_date(d), None) - - def test_string_date_false(self): - d = False - self.assertEquals(parse_date(d), None) - - def test_fparam(self): - d = {"HEY": None, "YOU": 3} - ed = {"YOU": 3} - self.assertEquals(transform_params(d), ed) - - def test_fparam_booleans(self): - d = {"HEY": None, "YOU": 3, "Activated": False} - ed = {"YOU": 3, "Activated": "false"} - self.assertEquals(transform_params(d), ed) - - def test_normalize_dates(self): - - @normalize_dates - def foo(on=None, before=None, after=None): - return { - "on": on, - "before": before, - "after": after, - } - - d = foo(on="2009-10-10", before=date(2009, 10, 10), - after=datetime(2009, 10, 10)) - - self.assertEquals(d["on"], "2009-10-10") - self.assertEquals(d["after"], "2009-10-10") - self.assertEquals(d["before"], "2009-10-10") - - def test_convert_case(self): - self.assertEquals(convert_case("from_"), "From") - self.assertEquals(convert_case("to"), "To") - self.assertEquals(convert_case("friendly_name"), "FriendlyName") - - def test_convert_bool(self): - self.assertEquals(convert_boolean(False), "false") - self.assertEquals(convert_boolean(True), "true") - self.assertEquals(convert_boolean(1), 1) - - def test_convert_keys(self): - d = { - "from_": 0, - "to": 0, - "friendly_name": 0, - "ended": 0, - } - - ed = { - "From": 0, - "To": 0, - "FriendlyName": 0, - "EndTime": 0, - } - - self.assertEquals(ed, convert_keys(d)) diff --git a/tests/test_jwt.py b/tests/test_jwt.py deleted file mode 100644 index b3e3f2936d..0000000000 --- a/tests/test_jwt.py +++ /dev/null @@ -1,119 +0,0 @@ -import time -from twilio import jwt -import six -if six.PY3: - import unittest -else: - import unittest2 as unittest - -from twilio.util import TwilioCapability - - -class JwtTest(unittest.TestCase): - - def assertIn(self, foo, bar, msg=None): - """backport for 2.6""" - return self.assertTrue(foo in bar, msg=(msg or "%s not found in %s" - % (foo, bar))) - - def test_no_permissions(self): - token = TwilioCapability("AC123", "XXXXX") - payload = token.payload() - self.assertEquals(len(payload), 1) - self.assertEquals(payload["scope"], '') - - def test_inbound_permissions(self): - token = TwilioCapability("AC123", "XXXXX") - token.allow_client_incoming("andy") - payload = token.payload() - - eurl = "scope:client:incoming?clientName=andy" - self.assertEquals(len(payload), 1) - self.assertEquals(payload['scope'], eurl) - - def test_outbound_permissions(self): - token = TwilioCapability("AC123", "XXXXX") - token.allow_client_outgoing("AP123") - payload = token.payload() - - eurl = "scope:client:outgoing?appSid=AP123" - - self.assertEquals(len(payload), 1) - self.assertIn(eurl, payload['scope']) - - def test_outbound_permissions_params(self): - token = TwilioCapability("AC123", "XXXXX") - token.allow_client_outgoing("AP123", foobar=3) - payload = token.payload() - - eurl = "scope:client:outgoing?appParams=foobar%3D3&appSid=AP123" - self.assertEquals(payload["scope"], eurl) - - def test_events(self): - token = TwilioCapability("AC123", "XXXXX") - token.allow_event_stream() - payload = token.payload() - - event_uri = "scope:stream:subscribe?path=%2F2010-04-01%2FEvents" - self.assertEquals(payload["scope"], event_uri) - - def test_events_with_filters(self): - token = TwilioCapability("AC123", "XXXXX") - token.allow_event_stream(foobar="hey") - payload = token.payload() - - event_uri = "scope:stream:subscribe?params=foobar%3Dhey&path=%2F2010-04-01%2FEvents" - self.assertEquals(payload["scope"], event_uri) - - def test_decode(self): - token = TwilioCapability("AC123", "XXXXX") - token.allow_client_outgoing("AP123", foobar=3) - token.allow_client_incoming("andy") - token.allow_event_stream() - - outgoing_uri = "scope:client:outgoing?appParams=foobar%3D3&appSid=AP123&clientName=andy" - incoming_uri = "scope:client:incoming?clientName=andy" - event_uri = "scope:stream:subscribe?path=%2F2010-04-01%2FEvents" - - result = jwt.decode(token.generate(), "XXXXX") - scope = result["scope"].split(" ") - - self.assertIn(outgoing_uri, scope) - self.assertIn(incoming_uri, scope) - self.assertIn(event_uri, scope) - - def setUp(self): - self.payload = {"iss": "jeff", "exp": int(time.time()), "claim": "insanity"} - - def test_encode_decode(self): - secret = 'secret' - jwt_message = jwt.encode(self.payload, secret) - decoded_payload = jwt.decode(jwt_message, secret) - self.assertEqual(decoded_payload, self.payload) - - def test_bad_secret(self): - right_secret = 'foo' - bad_secret = 'bar' - jwt_message = jwt.encode(self.payload, right_secret) - self.assertRaises(jwt.DecodeError, jwt.decode, jwt_message, bad_secret) - - def test_decodes_valid_jwt(self): - example_payload = {"hello": "world"} - example_secret = "secret" - example_jwt = "eyJhbGciOiAiSFMyNTYiLCAidHlwIjogIkpXVCJ9.eyJoZWxsbyI6ICJ3b3JsZCJ9.tvagLDLoaiJKxOKqpBXSEGy7SYSifZhjntgm9ctpyj8" - decoded_payload = jwt.decode(example_jwt, example_secret) - self.assertEqual(decoded_payload, example_payload) - - def test_allow_skip_verification(self): - right_secret = 'foo' - jwt_message = jwt.encode(self.payload, right_secret) - decoded_payload = jwt.decode(jwt_message, verify=False) - self.assertEqual(decoded_payload, self.payload) - - def test_no_secret(self): - right_secret = 'foo' - jwt_message = jwt.encode(self.payload, right_secret) - self.assertRaises(jwt.DecodeError, jwt.decode, jwt_message) - - def test_invalid_crypto_alg(self): - self.assertRaises(NotImplementedError, jwt.encode, self.payload, "secret", "HS1024") diff --git a/tests/test_make_request.py b/tests/test_make_request.py deleted file mode 100644 index f5b3a7ee5c..0000000000 --- a/tests/test_make_request.py +++ /dev/null @@ -1,72 +0,0 @@ -""" -Test that make+request is making correct HTTP requests - -Uses the awesome httpbin.org to validate responses -""" -import twilio -from nose.tools import raises -from mock import patch, Mock -from twilio import TwilioRestException -from twilio.rest.resources.base import make_request, make_twilio_request - -get_headers = { - "User-Agent": "twilio-python/%s" % (twilio.__version__), - "Accept": "application/json", - } - -post_headers = get_headers.copy() -post_headers["Content-Type"] = "application/x-www-form-urlencoded" - - -@patch('twilio.rest.resources.base.Response') -@patch('httplib2.Http') -def test_get_params(http_mock, response_mock): - http = Mock() - http.request.return_value = (Mock(), Mock()) - http_mock.return_value = http - make_request("GET", "http://httpbin.org/get", params={"hey": "you"}) - http.request.assert_called_with("http://httpbin.org/get?hey=you", "GET", - body=None, headers=None) - - -@patch('twilio.rest.resources.base.Response') -@patch('httplib2.Http') -def test_get_extra_params(http_mock, response_mock): - http = Mock() - http.request.return_value = (Mock(), Mock()) - http_mock.return_value = http - make_request("GET", "http://httpbin.org/get?foo=bar", params={"hey": "you"}) - http.request.assert_called_with("http://httpbin.org/get?foo=bar&hey=you", "GET", - body=None, headers=None) - - -@patch('twilio.rest.resources.base.Response') -@patch('httplib2.Http') -def test_resp_uri(http_mock, response_mock): - http = Mock() - http.request.return_value = (Mock(), Mock()) - http_mock.return_value = http - make_request("GET", "http://httpbin.org/get") - http.request.assert_called_with("http://httpbin.org/get", "GET", - body=None, headers=None) - - -@patch('twilio.rest.resources.base.make_request') -def test_make_twilio_request_headers(mock): - url = "http://random/url" - make_twilio_request("POST", url) - mock.assert_called_with("POST", "http://random/url.json", - headers=post_headers) - - -@raises(TwilioRestException) -@patch('twilio.rest.resources.base.make_request') -def test_make_twilio_request_bad_data(mock): - resp = Mock() - resp.ok = False - mock.return_value = resp - - url = "http://random/url" - make_twilio_request("POST", url) - mock.assert_called_with("POST", "http://random/url.json", - headers=post_headers) diff --git a/tests/test_members.py b/tests/test_members.py deleted file mode 100644 index cdccd20410..0000000000 --- a/tests/test_members.py +++ /dev/null @@ -1,46 +0,0 @@ -from mock import patch -from tools import create_mock_json -from twilio.rest.resources import Members - -QUEUE_SID = "QU1b9faddec3d54ec18488f86c83019bf0" -ACCOUNT_SID = "AC123" -AUTH = (ACCOUNT_SID, "token") -CALL_SID = "CAaaf2e9ded94aba3e57c42a3d55be6ff2" -BASE_URI = "https://api.twilio.com/2010-04-01/Accounts/AC123/Queues/%s" % ( - QUEUE_SID) -TWIML_URL = "example_twiml_url" - -list_resource = Members(BASE_URI, AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_members_list(mock): - resp = create_mock_json("tests/resources/members_list.json") - mock.return_value = resp - - uri = "%s/Members" % (BASE_URI) - list_resource.list() - - mock.assert_called_with("GET", uri, params={}, auth=AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_members_dequeue_front(mock): - resp = create_mock_json("tests/resources/members_instance.json") - mock.return_value = resp - - uri = "%s/Members/Front" % (BASE_URI) - list_resource.dequeue(TWIML_URL) - - mock.assert_called_with("POST", uri, data={"Url": TWIML_URL}, auth=AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_members_dequeue_call(mock): - resp = create_mock_json("tests/resources/members_instance.json") - mock.return_value = resp - - uri = "%s/Members/%s" % (BASE_URI, CALL_SID) - list_resource.dequeue(TWIML_URL, call_sid=CALL_SID) - - mock.assert_called_with("POST", uri, data={"Url": TWIML_URL}, auth=AUTH) diff --git a/tests/test_notifications.py b/tests/test_notifications.py deleted file mode 100644 index 5c8c2f9880..0000000000 --- a/tests/test_notifications.py +++ /dev/null @@ -1,59 +0,0 @@ -from datetime import date -from mock import patch -from nose.tools import raises, assert_true -from twilio.rest.resources import Notifications -from tools import create_mock_json - -BASE_URI = "https://api.twilio.com/2010-04-01/Accounts/AC123" -ACCOUNT_SID = "AC123" -AUTH = (ACCOUNT_SID, "token") - -RE_SID = "RE19e96a31ed59a5733d2c1c1c69a83a28" - -list_resource = Notifications(BASE_URI, AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_paging(mock): - resp = create_mock_json("tests/resources/notifications_list.json") - mock.return_value = resp - - uri = "%s/Notifications" % (BASE_URI) - list_resource.list(before=date(2010, 12, 5)) - exp_params = {'MessageDate<': '2010-12-05'} - - mock.assert_called_with("GET", uri, params=exp_params, auth=AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_get(mock): - resp = create_mock_json("tests/resources/notifications_instance.json") - mock.return_value = resp - - uri = "%s/Notifications/%s" % (BASE_URI, RE_SID) - list_resource.get(RE_SID) - - mock.assert_called_with("GET", uri, auth=AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_get2(mock): - resp = create_mock_json("tests/resources/notifications_instance.json") - resp.status_code = 204 - mock.return_value = resp - - uri = "%s/Notifications/%s" % (BASE_URI, RE_SID) - r = list_resource.delete(RE_SID) - - mock.assert_called_with("DELETE", uri, auth=AUTH) - assert_true(r) - - -@raises(AttributeError) -def test_create(): - list_resource.create - - -@raises(AttributeError) -def test_update(): - list_resource.update diff --git a/tests/test_phone_numbers.py b/tests/test_phone_numbers.py deleted file mode 100644 index 8e4a9aa9fa..0000000000 --- a/tests/test_phone_numbers.py +++ /dev/null @@ -1,89 +0,0 @@ -from __future__ import with_statement -try: - import json -except ImportError: - import simplejson as json -import six -if six.PY3: - import unittest -else: - import unittest2 as unittest -from mock import Mock -from twilio.rest.resources import PhoneNumbers -from twilio.rest.resources import PhoneNumber - - -class PhoneNumberTest(unittest.TestCase): - - def setUp(self): - self.parent = Mock() - self.uri = "/base" - self.auth = ("AC123", "token") - - def test_update_rename_status_callback_url(self): - mock = Mock() - mock.uri = "/base" - instance = PhoneNumber(mock, "SID") - instance.update(status_callback_url="http://www.example.com") - mock.update.assert_called_with("SID", status_callback="http://www.example.com") - - def test_update_instance_rename_status_callback_url(self): - resource = PhoneNumbers(self.uri, self.auth) - resource.update_instance = Mock() - resource.update("SID", status_callback_url="http://www.example.com") - resource.update_instance.assert_called_with("SID", {"status_callback": "http://www.example.com"}) - - def test_application_sid(self): - resource = PhoneNumbers(self.uri, self.auth) - resource.update_instance = Mock() - resource.update("SID", application_sid="foo") - resource.update_instance.assert_called_with( - "SID", {"voice_application_sid": "foo", "sms_application_sid": "foo"}) - - def test_voice_application_sid(self): - resource = PhoneNumbers(self.uri, self.auth) - resource.update_instance = Mock() - resource.update("SID", voice_application_sid="foo") - resource.update_instance.assert_called_with( - "SID", {"voice_application_sid": "foo"}) - - def test_sms_application_sid(self): - resource = PhoneNumbers(self.uri, self.auth) - resource.update_instance = Mock() - resource.update("SID", sms_application_sid="foo") - resource.update_instance.assert_called_with( - "SID", {"sms_application_sid": "foo"}) - - def test_status_callback_url(self): - resource = PhoneNumbers(self.uri, self.auth) - resource.update_instance = Mock() - resource.update("SID", status_callback="foo") - resource.update_instance.assert_called_with( - "SID", {"status_callback": "foo"}) - - def test_transfer(self): - resource = PhoneNumbers(self.uri, self.auth) - resource.update = Mock() - resource.transfer("SID", "AC123") - resource.update.assert_called_with("SID", account_sid="AC123") - - def test_instance_transfer(self): - mock = Mock() - mock.uri = "/base" - instance = PhoneNumber(mock, "SID") - instance.transfer("AC123") - mock.transfer.assert_called_with("SID", "AC123") - - def test_base_uri(self): - parent = Mock() - parent.base_uri = ("https://api.twilio.com/2010-04-01/Accounts/" - "AC123") - resource = PhoneNumber(parent, "PNd2ae06cced59a5733d2c1c1c69a83a28") - - with open("tests/resources/incoming_phone_numbers_instance.json") as f: - entry = json.load(f) - resource.load(entry) - - self.assertEquals(resource.parent.base_uri, - ("https://api.twilio.com/2010-04-01/Accounts/AC4bf2dafbed59a573" - "3d2c1c1c69a83a28")) diff --git a/tests/test_queues.py b/tests/test_queues.py deleted file mode 100644 index d9aa658d13..0000000000 --- a/tests/test_queues.py +++ /dev/null @@ -1,70 +0,0 @@ -from mock import patch -from tools import create_mock_json -from twilio.rest.resources import Queues, Queue - -BASE_URI = "https://api.twilio.com/2010-04-01/Accounts/AC123" -ACCOUNT_SID = "AC123" -AUTH = (ACCOUNT_SID, "token") -QUEUE_SID = "QU1b9faddec3d54ec18488f86c83019bf0" -CALL_SID = "CAaaf2e9ded94aba3e57c42a3d55be6ff2" - -list_resource = Queues(BASE_URI, AUTH) -instance_resource = Queue(list_resource, QUEUE_SID) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_queues_list(mock): - resp = create_mock_json("tests/resources/queues_list.json") - mock.return_value = resp - - uri = "%s/Queues" % (BASE_URI) - list_resource.list() - - mock.assert_called_with("GET", uri, params={}, auth=AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_queues_create(mock): - resp = create_mock_json("tests/resources/queues_instance.json") - resp.status_code = 201 - mock.return_value = resp - - uri = "%s/Queues" % (BASE_URI) - list_resource.create('test', max_size=9001) - - mock.assert_called_with("POST", uri, - data={'FriendlyName': 'test', 'MaxSize': 9001}, - auth=AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_queues_get(mock): - resp = create_mock_json("tests/resources/queues_instance.json") - mock.return_value = resp - - uri = "%s/Queues/%s" % (BASE_URI, QUEUE_SID) - list_resource.get(QUEUE_SID) - mock.assert_called_with("GET", uri, auth=AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_queue_update(mock): - resp = create_mock_json("tests/resources/queues_instance.json") - mock.return_value = resp - - uri = "%s/Queues/%s" % (BASE_URI, QUEUE_SID) - instance_resource.update(friendly_name='QQ') - - mock.assert_called_with("POST", uri, - data={'FriendlyName': 'QQ'}, auth=AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_queue_delete(mock): - resp = create_mock_json("tests/resources/queues_instance.json") - mock.return_value = resp - - uri = "%s/Queues/%s" % (BASE_URI, QUEUE_SID) - instance_resource.delete() - - mock.assert_called_with("DELETE", uri, auth=AUTH) diff --git a/tests/test_recordings.py b/tests/test_recordings.py deleted file mode 100644 index 94fd6fcd03..0000000000 --- a/tests/test_recordings.py +++ /dev/null @@ -1,62 +0,0 @@ -from datetime import date -from mock import patch -from nose.tools import raises, assert_equals, assert_true -from twilio.rest.resources import Recordings -from tools import create_mock_json - -BASE_URI = "https://api.twilio.com/2010-04-01/Accounts/AC123" -ACCOUNT_SID = "AC123" -AUTH = (ACCOUNT_SID, "token") - -RE_SID = "RE19e96a31ed59a5733d2c1c1c69a83a28" - -recordings = Recordings(BASE_URI, AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_paging(mock): - resp = create_mock_json("tests/resources/recordings_list.json") - mock.return_value = resp - - uri = "%s/Recordings" % (BASE_URI) - recordings.list(call_sid="CA123", before=date(2010, 12, 5)) - exp_params = {'CallSid': 'CA123', 'DateCreated<': '2010-12-05'} - - mock.assert_called_with("GET", uri, params=exp_params, auth=AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_get(mock): - resp = create_mock_json("tests/resources/recordings_instance.json") - mock.return_value = resp - - uri = "%s/Recordings/%s" % (BASE_URI, RE_SID) - r = recordings.get(RE_SID) - - mock.assert_called_with("GET", uri, auth=AUTH) - - truri = "%s/Recordings/%s/Transcriptions" % (BASE_URI, RE_SID) - assert_equals(r.transcriptions.uri, truri) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_get2(mock): - resp = create_mock_json("tests/resources/recordings_instance.json") - resp.status_code = 204 - mock.return_value = resp - - uri = "%s/Recordings/%s" % (BASE_URI, RE_SID) - r = recordings.delete(RE_SID) - - mock.assert_called_with("DELETE", uri, auth=AUTH) - assert_true(r) - - -@raises(AttributeError) -def test_create(): - recordings.create - - -@raises(AttributeError) -def test_update(): - recordings.update diff --git a/tests/test_rest.py.inactive b/tests/test_rest.py.inactive deleted file mode 100644 index 4ff12af851..0000000000 --- a/tests/test_rest.py.inactive +++ /dev/null @@ -1,651 +0,0 @@ -import json -import os -import unittest - -from datetime import datetime -from datetime import date -from mock import patch -from mock import Mock -from twilio import TwilioException -from twilio import TwilioRestException -from twilio.rest import TwilioRestClient as TwilioClient -from twilio.rest.resources import * - -ACCOUNT_SID = "AC111111111" -AUTH_TOKEN = "AUTH_TOKEN" -BASE_URI = "https://api.twilio.com/2010-04-01/" -ACCOUNT_URI = "{0}Accounts/{1}/".format(BASE_URI, ACCOUNT_SID) - -DEFAULT_HEADERS = { - 'User-Agent': 'twilio-python/3.0.0', - } - -FORM_CONTENT_TYPE = { - 'Content-type': 'application/x-www-form-urlencoded', - 'User-Agent': 'twilio-python/3.0.0', - } - -def create_mock_request(status=200, content="{}"): - request = Mock() - resp = Mock() - resp.status = status - resp.reason = "CREATED" - request.return_value = resp, content - return request - -class GeneralResourceTest(unittest.TestCase): - - def setUp(self): - self.c = TwilioClient(account=ACCOUNT_SID, token=AUTH_TOKEN) - - def mock_request(self, status=200, content="{}"): - request = Mock() - resp = Mock() - resp.status = status - resp.reason = "CREATED" - request.return_value = resp, content - self.c.client.request = request - return request - -class ListResourceTest(GeneralResourceTest): - - def check_list_uri(self, resource, e_uri, **kwargs): - body = '{"%s":[]}' % resource.key - request = self.mock_request(content=body) - resource.list(**kwargs) - request.assert_called_with(e_uri, method="GET", - headers=DEFAULT_HEADERS) - - def check_delete_uri(self, resource, sid, e_uri): - request = self.mock_request() - resource.delete(sid) - request.assert_called_with(e_uri, method="DELETE", - headers=DEFAULT_HEADERS) - - def check_update_uri(self, resource, sid, e_uri, body, **kwargs): - request = self.mock_request(content='{"sid":"hey"}') - resource.update(sid, **kwargs) - request.assert_called_with(e_uri, method="POST", body=body, - headers=FORM_CONTENT_TYPE) - - def check_paging(self, resource, response, uri): - request = self.mock_request(content=response) - resource.list(page=2) - request.assert_called_with(uri, method="GET", - headers=DEFAULT_HEADERS) - -class InstanceResourceTest(GeneralResourceTest): - - def check_update_uri(self, resource, e_uri, body, **kwargs): - request = self.mock_request(content='{"sid":"hey"}') - resource.update(**kwargs) - request.assert_called_with(e_uri, method="POST", body=body, - headers=FORM_CONTENT_TYPE) - - def check_delete_uri(self, resource, e_uri): - request = self.mock_request(content='{"sid":"hey"}') - resource.delete() - request.assert_called_with(e_uri, method="DELETE", - headers=DEFAULT_HEADERS) - -class ClientTest(unittest.TestCase): - - def setUp(self): - self.c = TwilioClient(account=ACCOUNT_SID, token=AUTH_TOKEN) - - def test_creation(self): - c = TwilioClient(account=ACCOUNT_SID, token=AUTH_TOKEN) - self.assertEquals(c.account_sid, ACCOUNT_SID) - self.assertEquals(c.auth_token, AUTH_TOKEN) - - def test_creation_env_variables(self): - creds = { - "TWILIO_ACCOUNT_SID": ACCOUNT_SID, - "TWILIO_AUTH_TOKEN": AUTH_TOKEN, - } - - with patch.dict(os.environ, creds): - c = TwilioClient() - - self.assertEquals(c.account_sid, ACCOUNT_SID) - self.assertEquals(c.auth_token, AUTH_TOKEN) - - def test_credential_adding(self): - client = Mock() - client.add_credentials = Mock() - c = TwilioClient(account=ACCOUNT_SID, token=AUTH_TOKEN, client=client) - - client.add_credentials.assert_called_with(ACCOUNT_SID, AUTH_TOKEN) - - def test_creation_fails(self): - with self.assertRaises(TwilioException) as cm: - with patch.dict(os.environ, {}, clear=True): - c = TwilioClient() - - def test_notificaitons_uri(self): - uri = "{0}Notifications".format(ACCOUNT_URI) - self.assertEquals(self.c.notifications.uri, uri) - - -class ResourceTest(unittest.TestCase): - - def setUp(self): - mock_http, request, self.resp = Mock(), Mock(), Mock() - request.return_value = self.resp, "" - mock_http.request = request - self.c = TwilioClient(account=ACCOUNT_SID, token=AUTH_TOKEN, - client=mock_http) - - def test_not_found(self): - self.resp.status = 404 - self.resp.description = "NOT FOUND" - with self.assertRaises(TwilioRestException) as cm: - self.c.accounts.create(friendly_name="MyNewAccount") - - def test_auth_required(self): - self.resp.status = 401 - self.resp.description = "AUTH REQUIRED" - with self.assertRaises(TwilioRestException) as cm: - self.c.accounts.create(friendly_name="MyNewAccount") - -class AccountsTest(ListResourceTest): - - def setUp(self): - self.mock_http = Mock() - self.c = TwilioClient(account=ACCOUNT_SID, token=AUTH_TOKEN, - client=self.mock_http) - - def test_paging(self): - with open("tests/resources/accounts_list.json") as f: - uri = "{0}Accounts.json?Page=2".format(BASE_URI) - self.check_paging(self.c.accounts, f.read(), uri) - - def test_uri(self): - uri = "{0}Accounts".format(BASE_URI) - self.assertEquals(self.c.accounts.uri, uri) - - def test_create_wrong_arg(self): - with self.assertRaises(TypeError) as cm: - a = self.c.accounts.create() - - def test_create(self): - with open("tests/resources/accounts_instance.json") as f: - content = f.read() - - request = create_mock_request(201, content) - self.mock_http.request = request - - c = self.c.accounts.create(friendly_name="account_name") - - entries = json.loads(content) - self.assertEquals(c.sid, entries["sid"]) - self.assertEquals(c.date_created, entries["date_created"]) - self.assertEquals(c.date_updated, entries["date_updated"]) - self.assertEquals(c.status, entries["status"]) - self.assertEquals(c.auth_token, entries["auth_token"]) - - def test_get_uri(self): - - account_sid = "AC4bf2dafb92341f7caf8650403e422d23" - expected_uri = "{0}Accounts/{1}.json".format(BASE_URI,account_sid) - - request = create_mock_request() - self.mock_http.request = request - - with self.assertRaises(TwilioException) as cm: - c = self.c.accounts.get(account_sid) - - request.assert_called_with(expected_uri, method="GET", - headers=DEFAULT_HEADERS) - - def test_list_uri(self): - - expected_uri = "{0}Accounts.json".format(BASE_URI) - - request = create_mock_request() - self.mock_http.request = request - - with self.assertRaises(TwilioException) as cm: - c = self.c.accounts.list() - - request.assert_called_with(expected_uri, method="GET", - headers=DEFAULT_HEADERS) - - def test_list_uri_filter(self): - - expected_uri = "{0}Accounts.json?FriendlyName=You&Status=active".format(BASE_URI) - - request = create_mock_request() - self.mock_http.request = request - - with self.assertRaises(TwilioException) as cm: - c = self.c.accounts.list(friendly_name="You", status="active") - - request.assert_called_with(expected_uri, method="GET", - headers=DEFAULT_HEADERS) - - def test_update_uri(self): - account_sid = "AC4bf2dafb92341f7caf8650403e422d23" - expected_uri = "{0}Accounts/{1}.json".format(BASE_URI, account_sid) - - request = create_mock_request() - self.mock_http.request = request - with self.assertRaises(TwilioException) as cm: - c = self.c.accounts.update(account_sid, friendly_name="You") - - body = "FriendlyName=You" - request.assert_called_with(expected_uri, method="POST", body=body, - headers=FORM_CONTENT_TYPE) - - def test_instance_update_uri(self): - account_sid = "AC4bf2dafb92341f7caf8650403e422d23" - base_uri = "{0}Accounts".format(BASE_URI) - expected_uri = "{0}Accounts/{1}.json".format(BASE_URI, account_sid) - - request = create_mock_request() - self.mock_http.request = request - a = Account(self.c.accounts, base_uri, {"sid": account_sid}) - - with self.assertRaises(TwilioException) as cm: - c = a.update(friendly_name="You") - - body = "FriendlyName=You" - request.assert_called_with(expected_uri, method="POST", body=body, - headers=FORM_CONTENT_TYPE) - - with open("tests/resources/accounts_instance.json") as f: - content = f.read() - - def test_close_uri(self): - account_sid = "AC4bf2dafb92341f7caf8650403e422d23" - expected_uri = "{0}Accounts/{1}.json".format(BASE_URI, account_sid) - - request = create_mock_request() - self.mock_http.request = request - with self.assertRaises(TwilioException) as cm: - c = self.c.accounts.close(account_sid) - - body = "Status=closed" - request.assert_called_with(expected_uri, method="POST", body=body, - headers=FORM_CONTENT_TYPE) - - def test_request(self): - request = create_mock_request(status=201) - self.mock_http.request = request - self.c.accounts._create_instance = Mock() - - self.c.accounts.create(friendly_name="MyNewAccount") - - uri = "{0}.json".format(self.c.accounts.uri) - body = "FriendlyName=MyNewAccount" - request.assert_called_with(uri, method="POST", body=body, - headers=FORM_CONTENT_TYPE) - - def test_instance_creation(self): - - with open("tests/resources/accounts_instance.json") as f: - content = f.read() - - entries = json.loads(content) - - print self.c.accounts.instance - a = self.c.accounts._create_instance(entries) - - uri = "{0}Accounts/{1}".format(BASE_URI, entries["sid"]) - self.assertEquals(a.sid, entries["sid"]) - self.assertEquals(a.uri, uri) - self.assertEquals(a.date_created, entries["date_created"]) - self.assertEquals(a.date_updated, entries["date_updated"]) - self.assertEquals(a.status, entries["status"]) - self.assertEquals(a.auth_token, entries["auth_token"]) - - -class AccountTest(unittest.TestCase): - - ct = FORM_CONTENT_TYPE - - def setUp(self): - self.mock_http = Mock() - self.c = TwilioClient(account=ACCOUNT_SID, token=AUTH_TOKEN) - - self.account_sid = "AC4bf2dafb92341f7caf8650403e422d23" - self.base_uri = "{0}Accounts".format(BASE_URI) - self.expected_uri = "{0}Accounts/{1}.json".format(BASE_URI, - self.account_sid) - self.account = Account(self.c.accounts, {"sid": self.account_sid}) - - - def _validate(self, func, content_path, status): - with open(content_path) as f: - request = create_mock_request(content=f.read()) - self.mock_http.request = request - - func() - - request.assert_called_with(self.expected_uri, method="POST", - body="Status={0}".format(status), - headers=self.ct) - - def test_close(self): - self._validate(self.account.close, "tests/resources/accounts_instance.json", - Account.CLOSED) - - def test_suspend(self): - self._validate(self.account.suspend, "tests/resources/accounts_instance.json", - Account.SUSPENDED) - - def test_activate(self): - self._validate(self.account.activate, "tests/resources/accounts_instance.json", - Account.ACTIVE) - - -class CallsTest(ListResourceTest): - - def test_paging(self): - with open("tests/resources/calls_list.json") as f: - uri = "{}Calls.json?Page=2".format(ACCOUNT_URI) - self.check_paging(self.c.calls, f.read(), uri) - - def test_uri(self): - uri = "{0}Calls".format(ACCOUNT_URI) - self.assertEquals(self.c.calls.uri, uri) - - def test_get_uri(self): - csid = "CA12312313" - e_uri = "{0}Accounts/{1}/Calls/{2}.json".format(BASE_URI, - ACCOUNT_SID, csid) - request = self.mock_request() - with self.assertRaises(TwilioException) as cm: - c = self.c.calls.get(csid) - - request.assert_called_with(e_uri, method="GET", - headers=DEFAULT_HEADERS) - - def test_list_uri(self): - query = "EndTime%3C=2009-01-31&StartTime%3E=2009-01-01&EndTime=2009-12-12" - e_uri = "{0}Accounts/{1}/Calls.json?{2}".format(BASE_URI, ACCOUNT_SID, - query) - request = self.mock_request() - with self.assertRaises(TwilioException) as cm: - c = self.c.calls.list(ended=date(2009,12,12), - started_after="2009-01-01", - ended_before=datetime.datetime(2009,1,31)) - - request.assert_called_with(e_uri, method="GET", - headers=DEFAULT_HEADERS) - - def test_create_uri(self): - e_uri = "{0}Accounts/{1}/Calls.json".format(BASE_URI, ACCOUNT_SID) - body = urllib.urlencode({ - "From":5551231234, - "To":5551231234, - "Url":"http://www.google.com", - }) - request = self.mock_request() - - with self.assertRaises(TwilioException) as cm: - c = self.c.calls.create(to=5551231234, from_=5551231234, - url="http://www.google.com") - - request.assert_called_with(e_uri, method="POST", body=body, - headers=FORM_CONTENT_TYPE) - - def test_hangup_uri(self): - sid = "CA123123123123" - e_uri = "{0}Accounts/{1}/Calls/{2}.json".format(BASE_URI, ACCOUNT_SID, sid) - body = urllib.urlencode({"Status": Call.CANCELED}) - request = self.mock_request() - - with self.assertRaises(TwilioException) as cm: - c = self.c.calls.hangup(sid) - - request.assert_called_with(e_uri, method="POST", body=body, - headers=FORM_CONTENT_TYPE) - - def test_route_uri(self): - sid = "CA123123123123" - e_uri = "{0}Accounts/{1}/Calls/{2}.json".format(BASE_URI, ACCOUNT_SID, sid) - body = urllib.urlencode({"Url": "http://www.google.com", "Method": "POST"}) - request = self.mock_request() - - with self.assertRaises(TwilioException) as cm: - c = self.c.calls.route(sid, "http://www.google.com") - - request.assert_called_with(e_uri, method="POST", body=body, - headers=FORM_CONTENT_TYPE) -class CallTest(unittest.TestCase): - - def setUp(self): - self.c = TwilioClient(account=ACCOUNT_SID, token=AUTH_TOKEN) - self.call_sid = "CA123123" - self.base_uri = "{0}Accounts/{1}/Calls".format(BASE_URI, ACCOUNT_SID) - self.call_uri = "{0}/{1}.json".format(self.base_uri, self.call_sid) - - self.call = Call(self.c.calls, self.base_uri, {"sid": self.call_sid}) - - def mock_request(self, status=200, content="{}"): - request = Mock() - resp = Mock() - resp.status = status - resp.reason = "CREATED" - request.return_value = resp, content - self.c.client.request = request - return request - - def test_subresources(self): - euri = "{1}/{0}/Notifications".format(self.call_sid, self.base_uri) - self.assertEquals(euri, self.call.notifications.uri) - - def test_hangup(self): - request = self.mock_request() - - try: - self.call.hangup() - except: - pass - - request.assert_called_with(self.call_uri, method="POST", - body="Status={0}".format(Call.CANCELED), - headers=FORM_CONTENT_TYPE) - -class CallerIdsTest(ListResourceTest): - - def test_paging(self): - with open("tests/resources/outgoing_caller_ids_list.json") as f: - uri = "{}OutgoingCallerIds.json?Page=2".format(ACCOUNT_URI) - self.check_paging(self.c.caller_ids, f.read(), uri) - - def test_validate(self): - - with open("tests/resources/outgoing_caller_ids_validation.json") as f: - content = f.read() - - e_uri = "{0}Accounts/{1}/OutgoingCallerIds.json".format(BASE_URI, ACCOUNT_SID) - body = urllib.urlencode({ - "PhoneNumber": 5551231234, - }) - request = self.mock_request(status=201, content=content) - - c = self.c.caller_ids.validate(5551231234) - print c - - request.assert_called_with(e_uri, method="POST", body=body, - headers=FORM_CONTENT_TYPE) - self.assertTrue("validation_code" in c) - - def test_list(self): - - body = urllib.urlencode({ - "PhoneNumber": 5551231234, - }) - e_uri = "{}OutgoingCallerIds.json?{}".format(ACCOUNT_URI,body) - request = self.mock_request() - - with self.assertRaises(TwilioException) as cm: - c = self.c.caller_ids.list(phone_number=5551231234) - - request.assert_called_with(e_uri, method="GET", - headers=DEFAULT_HEADERS) - - def test_list_uri(self): - uri = "{}OutgoingCallerIds.json".format(ACCOUNT_URI) - self.check_list_uri(self.c.caller_ids, uri) - - def test_delete_uri(self): - sid = "CI123123" - uri = "{}OutgoingCallerIds/{}.json".format(ACCOUNT_URI, sid) - self.check_delete_uri(self.c.caller_ids, sid, uri) - - def test_update_uri(self): - sid = "CI123123" - uri = "{}OutgoingCallerIds/{}.json".format(ACCOUNT_URI, sid) - body = urllib.urlencode({"FriendlyName": "MyCallerId"}) - self.check_update_uri(self.c.caller_ids, sid, uri, body, - friendly_name="MyCallerId") - -class CallerIdTest(InstanceResourceTest): - - def setUp(self): - self.c = TwilioClient(account=ACCOUNT_SID, token=AUTH_TOKEN) - self.sid = "CA123123" - self.base_uri = "{0}Accounts/{1}/OutgoingCallerIds".format(BASE_URI, ACCOUNT_SID) - self.uri = "{0}/{1}.json".format(self.base_uri, self.sid) - self.callerid = CallerId(self.c.caller_ids, self.base_uri, {"sid": self.sid}) - - def test_hangup(self): - request = self.mock_request(content='{"sid":"asdh"}') - self.check_update_uri(self.callerid, self.uri, - "FriendlyName=MyFriendlyName", - friendly_name="MyFriendlyName") - - def test_delete(self): - request = self.mock_request(content='{"sid":"asdh"}') - self.check_delete_uri(self.callerid, self.uri) - -class NotificationsTest(ListResourceTest): - - def test_list_uri(self): - uri = "{}Notifications.json".format(ACCOUNT_URI) - self.check_list_uri(self.c.notifications, uri) - - def test_list_uri_fiter(self): - query = urllib.urlencode({"MessageDate<": "2009-10-10", - "MessageDate>": "2010-10-10", - "LogLevel": 1}) - uri = "{}Notifications.json?{}".format(ACCOUNT_URI, query) - self.check_list_uri(self.c.notifications, uri, before="2009-10-10", - after="2010-10-10", log_level=1) - - def test_delete_uri(self): - sid = "N123123" - uri = "{}Notifications/{}.json".format(ACCOUNT_URI, sid) - self.check_delete_uri(self.c.notifications, sid, uri) - -class NotificationTest(InstanceResourceTest): - - def setUp(self): - self.c = TwilioClient(account=ACCOUNT_SID, token=AUTH_TOKEN) - self.sid = "NO123123" - self.base_uri = "{0}Accounts/{1}/Notifications".format(BASE_URI, ACCOUNT_SID) - self.uri = "{0}/{1}.json".format(self.base_uri, self.sid) - self.notification = Notification(self.c.notifications, self.base_uri, {"sid": self.sid}) - - def test_delete(self): - request = self.mock_request(content='{"sid":"asdh"}') - self.check_delete_uri(self.notification, self.uri) - - def test_paging(self): - with open("tests/resources/notifications_list.json") as f: - uri = "{}.json?Page=2".format(self.base_uri) - request = self.mock_request(content=f.read()) - self.c.notifications.list(page=2) - request.assert_called_with(uri, method="GET", - headers=DEFAULT_HEADERS) - - -class TranscriptionsTest(ListResourceTest): - - def test_list_uri(self): - uri = "{}Transcriptions.json".format(ACCOUNT_URI) - self.check_list_uri(self.c.transcriptions, uri) - - def test_paging(self): - with open("tests/resources/transcriptions_list.json") as f: - uri = "{}Transcriptions.json?Page=2".format(ACCOUNT_URI) - request = self.mock_request(content=f.read()) - self.c.transcriptions.list(page=2) - request.assert_called_with(uri, method="GET", - headers=DEFAULT_HEADERS) - -class PhoneNumbersTest(ListResourceTest): - - list_response = "tests/resources/incoming_phone_numbers_list.json" - instancet_response = "tests/resources/incoming_phone_numbers_instance.json" - - def test_paging(self): - with open(self.list_response) as f: - uri = "{}IncomingPhoneNumbers.json?Page=2".format(ACCOUNT_URI) - self.check_paging(self.c.phone_numbers, f.read(), uri) - - def test_list_uri(self): - uri = "{}IncomingPhoneNumbers.json".format(ACCOUNT_URI) - self.check_list_uri(self.c.phone_numbers, uri) - - def test_delete_uri(self): - sid = "PN123123" - uri = "{}IncomingPhoneNumbers/{}.json".format(ACCOUNT_URI, sid) - self.check_delete_uri(self.c.phone_numbers, sid, uri) - - def test_check_count(self): - with open("tests/resources/incoming_phone_numbers_list.json") as f: - content = f.read() - self.mock_request(content=content) - self.assertEquals(self.c.phone_numbers.count(), 3) - -class ConferencesTest(ListResourceTest): - - list_response = "tests/resources/conferences_list.json" - instancet_response = "tests/resources/conferences_instance.json" - - def test_paging(self): - with open(self.list_response) as f: - uri = "{}Conferences.json?Page=2".format(ACCOUNT_URI) - self.check_paging(self.c.conferences, f.read(), uri) - - def test_list_uri(self): - uri = "{}Conferences.json".format(ACCOUNT_URI) - self.check_list_uri(self.c.conferences, uri) - - -class AvailableNumbersTest(ListResourceTest): - - def test_search_local_uri(self): - uri = "{}AvailablePhoneNumbers/US/Local.json".format(ACCOUNT_URI) - body = '{"available_phone_numbers":[]}' - request = self.mock_request(content=body) - self.c.phone_numbers.search() - request.assert_called_with(uri, method="GET", - headers=DEFAULT_HEADERS) - - def test_search_local_uri(self): - uri = "{}AvailablePhoneNumbers/US/TollFree.json".format(ACCOUNT_URI) - body = '{"available_phone_numbers":[]}' - request = self.mock_request(content=body) - self.c.phone_numbers.search(type="TOLLFREE") - request.assert_called_with(uri, method="GET", - headers=DEFAULT_HEADERS) - - -class RecordingsTest(ListResourceTest): - - list_response = "tests/resources/recordings_list.json" - instancet_response = "tests/resources/recordings_instance.json" - - def test_paging(self): - with open(self.list_response) as f: - uri = "{}Recordings.json?Page=2".format(ACCOUNT_URI) - self.check_paging(self.c.recordings, f.read(), uri) - - def test_list_uri(self): - uri = "{}Recordings.json".format(ACCOUNT_URI) - self.check_list_uri(self.c.recordings, uri) diff --git a/tests/test_sms_messages.py b/tests/test_sms_messages.py deleted file mode 100644 index a455a34649..0000000000 --- a/tests/test_sms_messages.py +++ /dev/null @@ -1,41 +0,0 @@ -import six -if six.PY3: - import unittest -else: - import unittest2 as unittest - -from datetime import date -from mock import Mock -from twilio.rest.resources import SmsMessages - -DEFAULT = { - 'From': None, - 'DateSent<': None, - 'DateSent>': None, - 'DateSent': None, - } - - -class SmsTest(unittest.TestCase): - - def setUp(self): - self.resource = SmsMessages("foo", ("sid", "token")) - self.params = DEFAULT.copy() - - def test_list_on(self): - self.resource.get_instances = Mock() - self.resource.list(date_sent=date(2011, 1, 1)) - self.params['DateSent'] = "2011-01-01" - self.resource.get_instances.assert_called_with(self.params) - - def test_list_after(self): - self.resource.get_instances = Mock() - self.resource.list(after=date(2011, 1, 1)) - self.params['DateSent>'] = "2011-01-01" - self.resource.get_instances.assert_called_with(self.params) - - def test_list_before(self): - self.resource.get_instances = Mock() - self.resource.list(before=date(2011, 1, 1)) - self.params['DateSent<'] = "2011-01-01" - self.resource.get_instances.assert_called_with(self.params) diff --git a/tests/test_transcriptions.py b/tests/test_transcriptions.py deleted file mode 100644 index 6fe272140e..0000000000 --- a/tests/test_transcriptions.py +++ /dev/null @@ -1,42 +0,0 @@ -from mock import patch -from nose.tools import raises -from twilio.rest.resources import Transcriptions -from tools import create_mock_json - -BASE_URI = "https://api.twilio.com/2010-04-01/Accounts/AC123" -ACCOUNT_SID = "AC123" -AUTH = (ACCOUNT_SID, "token") - -transcriptions = Transcriptions(BASE_URI, AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_paging(mock): - resp = create_mock_json("tests/resources/transcriptions_list.json") - mock.return_value = resp - - uri = "%s/Transcriptions" % (BASE_URI) - transcriptions.list(page=2) - - mock.assert_called_with("GET", uri, params={"Page": 2}, auth=AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_get(mock): - resp = create_mock_json("tests/resources/transcriptions_instance.json") - mock.return_value = resp - - uri = "%s/Transcriptions/TR123" % (BASE_URI) - transcriptions.get("TR123") - - mock.assert_called_with("GET", uri, auth=AUTH) - - -@raises(AttributeError) -def test_create(): - transcriptions.create - - -@raises(AttributeError) -def test_update(): - transcriptions.update diff --git a/tests/test_twiml.py b/tests/test_twiml.py deleted file mode 100644 index 3c1336b053..0000000000 --- a/tests/test_twiml.py +++ /dev/null @@ -1,568 +0,0 @@ -# -*- coding: utf-8 -*- -from __future__ import with_statement - -from six import u, text_type -import six -if six.PY3: - import unittest -else: - import unittest2 as unittest -from twilio import twiml -from twilio.twiml import TwimlException -from twilio.twiml import Response -import xml.etree.ElementTree as ET - - -class TwilioTest(unittest.TestCase): - def strip(self, xml): - return text_type(xml) - - def improperAppend(self, verb): - self.assertRaises(TwimlException, verb.append, twiml.Say("")) - self.assertRaises(TwimlException, verb.append, twiml.Gather()) - self.assertRaises(TwimlException, verb.append, twiml.Play("")) - self.assertRaises(TwimlException, verb.append, twiml.Record()) - self.assertRaises(TwimlException, verb.append, twiml.Hangup()) - self.assertRaises(TwimlException, verb.append, twiml.Reject()) - self.assertRaises(TwimlException, verb.append, twiml.Redirect()) - self.assertRaises(TwimlException, verb.append, twiml.Dial()) - self.assertRaises(TwimlException, verb.append, twiml.Enqueue("")) - self.assertRaises(TwimlException, verb.append, twiml.Queue("")) - self.assertRaises(TwimlException, verb.append, twiml.Leave()) - self.assertRaises(TwimlException, verb.append, twiml.Conference("")) - self.assertRaises(TwimlException, verb.append, twiml.Client("")) - self.assertRaises(TwimlException, verb.append, twiml.Sms("")) - self.assertRaises(TwimlException, verb.append, twiml.Pause()) - - -class TestResponse(TwilioTest): - - def testEmptyResponse(self): - r = Response() - self.assertEquals(self.strip(r), '<?xml version="1.0" encoding="UTF-8"?><Response />') - - def testResponseAddAttribute(self): - r = Response(foo="bar") - self.assertEquals(self.strip(r), '<?xml version="1.0" encoding="UTF-8"?><Response foo="bar" />') - - -class TestSay(TwilioTest): - - def testEmptySay(self): - """should be a say with no text""" - r = Response() - r.append(twiml.Say("")) - self.assertEquals(self.strip(r), '<?xml version="1.0" encoding="UTF-8"?><Response><Say /></Response>') - - def testSayHelloWorld(self): - """should say hello monkey""" - r = Response() - r.append(twiml.Say("Hello World")) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Say>Hello World</Say></Response>') - - def testSayFrench(self): - """should say hello monkey""" - r = Response() - r.append(twiml.Say(u("n\xe9cessaire et d'autres"))) # it works on python 2.6 with the from __future__ import unicode_literal - self.assertEquals(text_type(r), - '<?xml version="1.0" encoding="UTF-8"?><Response><Say>nécessaire et d\'autres</Say></Response>') - - def testSayLoop(self): - """should say hello monkey and loop 3 times""" - r = Response() - r.append(twiml.Say("Hello Monkey", loop=3)) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Say loop="3">Hello Monkey</Say></Response>') - - def testSayLoopGreatBritian(self): - """should say have a woman say hello monkey and loop 3 times""" - r = Response() - r.append(twiml.Say("Hello Monkey", language="en-gb")) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Say language="en-gb">Hello Monkey</Say></Response>') - - def testSayLoopWoman(self): - """should say have a woman say hello monkey and loop 3 times""" - r = Response() - r.append(twiml.Say("Hello Monkey", loop=3, voice=twiml.Say.WOMAN)) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Say loop="3" voice="woman">Hello Monkey</Say></Response>') - - def testSayConvienceMethod(self): - """convenience method: should say have a woman say hello monkey and loop 3 times and be in french""" - r = Response() - r.addSay("Hello Monkey", loop=3, voice=twiml.Say.MAN, language=twiml.Say.FRENCH) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Say language="fr" loop="3" voice="man">Hello Monkey</Say></Response>') - - def testSayAddAttribute(self): - """add attribute""" - r = twiml.Say("", foo="bar") - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Say foo="bar" />') - - def testSayBadAppend(self): - """ should raise exceptions for wrong appending""" - self.improperAppend(twiml.Say("")) - - -class TestPlay(TwilioTest): - - def testEmptyPlay(self): - """should play hello monkey""" - r = Response() - r.append(twiml.Play("")) - r = self.strip(r) - self.assertEqual(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Play /></Response>') - - def testPlayHello(self): - """should play hello monkey""" - r = Response() - r.append(twiml.Play("http://hellomonkey.mp3")) - r = self.strip(r) - self.assertEqual(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Play>http://hellomonkey.mp3</Play></Response>') - - def testPlayHelloLoop(self): - """should play hello monkey loop""" - r = Response() - r.append(twiml.Play("http://hellomonkey.mp3", loop=3)) - r = self.strip(r) - self.assertEqual(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Play loop="3">http://hellomonkey.mp3</Play></Response>') - - def testPlayConvienceMethod(self): - """convenience method: should play hello monkey""" - r = Response() - r.addPlay("http://hellomonkey.mp3", loop=3) - r = self.strip(r) - self.assertEqual(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Play loop="3">http://hellomonkey.mp3</Play></Response>') - - def testPlayAddAttribute(self): - """add attribute""" - r = twiml.Play("", foo="bar") - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Play foo="bar" />') - - def testPlayBadAppend(self): - """ should raise exceptions for wrong appending""" - self.improperAppend(twiml.Play("")) - - -class TestRecord(TwilioTest): - - def testRecordEmpty(self): - """should record""" - r = Response() - r.append(twiml.Record()) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Record /></Response>') - - def testRecordActionMethod(self): - """should record with an action and a get method""" - r = Response() - r.append(twiml.Record(action="example.com", method="GET")) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Record action="example.com" method="GET" /></Response>') - - def testRecordMaxlengthFinishTimeout(self): - """should record with an maxlength, finishonkey, and timeout""" - r = Response() - r.append(twiml.Record(timeout=4, finishOnKey="#", maxLength=30)) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Record finishOnKey="#" maxLength="30" timeout="4" /></Response>') - - def testRecordTranscribeCallback(self): - """should record with a transcribe and transcribeCallback""" - r = Response() - r.append(twiml.Record(transcribeCallback="example.com")) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Record transcribeCallback="example.com" /></Response>') - - def testRecordAddAttribute(self): - """add attribute""" - r = twiml.Record(foo="bar") - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Record foo="bar" />') - - def testRecordBadAppend(self): - """ should raise exceptions for wrong appending""" - self.improperAppend(twiml.Record()) - - -class TestRedirect(TwilioTest): - - def testRedirectEmpty(self): - r = Response() - r.append(twiml.Redirect()) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Redirect /></Response>') - - def testRedirectMethod(self): - r = Response() - r.append(twiml.Redirect(url="example.com", method="POST")) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Redirect method="POST">example.com</Redirect></Response>') - - def testRedirectMethodGetParams(self): - r = Response() - r.append(twiml.Redirect(url="example.com?id=34&action=hey", method="POST")) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Redirect method="POST">example.com?id=34&action=hey</Redirect></Response>') - - def testAddAttribute(self): - """add attribute""" - r = twiml.Redirect("", foo="bar") - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Redirect foo="bar" />') - - def testBadAppend(self): - """ should raise exceptions for wrong appending""" - self.improperAppend(twiml.Redirect()) - - -class TestHangup(TwilioTest): - - def testHangup(self): - """convenience: should Hangup to a url via POST""" - r = Response() - r.append(twiml.Hangup()) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Hangup /></Response>') - - def testHangupConvience(self): - """should raises exceptions for wrong appending""" - r = Response() - r.addHangup() - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Hangup /></Response>') - - def testBadAppend(self): - """ should raise exceptions for wrong appending""" - self.improperAppend(twiml.Hangup()) - - -class TestLeave(TwilioTest): - - def testLeave(self): - """convenience: should Hangup to a url via POST""" - r = Response() - r.append(twiml.Leave()) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Leave /></Response>') - - def testBadAppend(self): - """ should raise exceptions for wrong appending""" - self.improperAppend(twiml.Leave()) - - -class TestReject(TwilioTest): - - def testReject(self): - """should be a Reject with default reason""" - r = Response() - r.append(twiml.Reject()) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Reject /></Response>') - - def testRejectConvenience(self): - """should be a Reject with reason Busy""" - r = Response() - r.addReject(reason='busy') - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Reject reason="busy" /></Response>') - - def testBadAppend(self): - """ should raise exceptions for wrong appending""" - self.improperAppend(twiml.Reject()) - - -class TestSms(TwilioTest): - - def testEmpty(self): - """Test empty sms verb""" - r = Response() - r.append(twiml.Sms("")) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Sms /></Response>') - - def testBody(self): - """Test hello world""" - r = Response() - r.append(twiml.Sms("Hello, World")) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Sms>Hello, World</Sms></Response>') - - def testToFromAction(self): - """ Test the to, from, and status callback""" - r = Response() - r.append(twiml.Sms("Hello, World", to=1231231234, sender=3453453456, - statusCallback="example.com?id=34&action=hey")) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Sms from="3453453456" statusCallback="example.com?id=34&action=hey" to="1231231234">Hello, World</Sms></Response>') - - def testActionMethod(self): - """ Test the action and method parameters on Sms""" - r = Response() - r.append(twiml.Sms("Hello", method="POST", action="example.com?id=34&action=hey")) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Sms action="example.com?id=34&action=hey" method="POST">Hello</Sms></Response>') - - def testConvience(self): - """should raises exceptions for wrong appending""" - r = Response() - r.addSms("Hello") - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Sms>Hello</Sms></Response>') - - def testBadAppend(self): - """ should raise exceptions for wrong appending""" - self.improperAppend(twiml.Sms("Hello")) - - -class TestConference(TwilioTest): - - def setUp(self): - r = Response() - with r.dial() as dial: - dial.conference("TestConferenceAttributes", beep=False, waitUrl="", - startConferenceOnEnter=True, endConferenceOnExit=True) - xml = r.toxml() - - #parse twiml XML string with Element Tree and inspect structure - tree = ET.fromstring(xml) - self.conf = tree.find(".//Conference") - - def test_conf_text(self): - self.assertEqual(self.conf.text.strip(), "TestConferenceAttributes") - - def test_conf_beep(self): - self.assertEqual(self.conf.get('beep'), "false") - - def test_conf_waiturl(self): - self.assertEqual(self.conf.get('waitUrl'), "") - - def test_conf_start_conference(self): - self.assertEqual(self.conf.get('startConferenceOnEnter'), "true") - - def test_conf_end_conference(self): - self.assertEqual(self.conf.get('endConferenceOnExit'), "true") - - -class TestQueue(TwilioTest): - - def setUp(self): - r = Response() - with r.dial() as dial: - dial.queue("TestQueueAttribute", url="", method='GET') - xml = r.toxml() - - #parse twiml XML string with Element Tree and inspect - #structure - tree = ET.fromstring(xml) - self.conf = tree.find(".//Queue") - - def test_conf_text(self): - self.assertEqual(self.conf.text.strip(), "TestQueueAttribute") - - def test_conf_waiturl(self): - self.assertEqual(self.conf.get('url'), "") - - def test_conf_method(self): - self.assertEqual(self.conf.get('method'), "GET") - - -class TestEnqueue(TwilioTest): - - def setUp(self): - r = Response() - r.enqueue("TestEnqueueAttribute", action="act", method='GET', - wait_url='wait', wait_url_method='POST') - xml = r.toxml() - - #parse twiml XML string with Element Tree and inspect - #structure - tree = ET.fromstring(xml) - self.conf = tree.find("./Enqueue") - - def test_conf_text(self): - self.assertEqual(self.conf.text.strip(), "TestEnqueueAttribute") - - def test_conf_waiturl(self): - self.assertEqual(self.conf.get('wait_url'), "wait") - - def test_conf_method(self): - self.assertEqual(self.conf.get('method'), "GET") - - def test_conf_action(self): - self.assertEqual(self.conf.get('action'), "act") - - def test_conf_waitmethod(self): - self.assertEqual(self.conf.get('wait_url_method'), "POST") - - -class TestDial(TwilioTest): - - def testDial(self): - """ should redirect the call""" - r = Response() - r.append(twiml.Dial("1231231234")) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Dial>1231231234</Dial></Response>') - - def testSip(self): - """ should redirect the call""" - r = Response() - d = r.dial() - d.sip('foo@example.com') - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Dial><Sip>foo@example.com</Sip></Dial></Response>') - - def testSipUsernamePass(self): - """ should redirect the call""" - r = Response() - d = r.dial() - d.sip('foo@example.com', username='foo', password='bar') - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Dial><Sip password="bar" username="foo">foo@example.com</Sip></Dial></Response>') - - def testSipUri(self): - """ should redirect the call""" - r = Response() - d = r.dial() - s = d.sip() - s.uri('foo@example.com') - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Dial><Sip><Uri>foo@example.com</Uri></Sip></Dial></Response>') - - def testConvienceMethod(self): - """ should dial to a url via post""" - r = Response() - r.addDial() - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Dial /></Response>') - - def testAddNumber(self): - """add a number to a dial""" - r = Response() - d = twiml.Dial() - d.append(twiml.Number("1231231234")) - r.append(d) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Dial><Number>1231231234</Number></Dial></Response>') - - def testAddNumberConvience(self): - """add a number to a dial, convience method""" - r = Response() - d = r.addDial() - d.addNumber("1231231234") - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Dial><Number>1231231234</Number></Dial></Response>') - - def testAddConference(self): - """ add a conference to a dial""" - r = Response() - d = twiml.Dial() - d.append(twiml.Conference("My Room")) - r.append(d) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Dial><Conference>My Room</Conference></Dial></Response>') - - def test_add_queue(self): - """ add a queue to a dial""" - r = Response() - d = r.dial() - d.append(twiml.Queue("The Cute Queue")) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Dial><Queue>The Cute Queue</Queue></Dial></Response>') - - def test_add_empty_client(self): - """ add an empty client to a dial""" - r = Response() - d = r.dial() - d.client("") - self.assertEquals(str(r), '<?xml version="1.0" encoding="UTF-8"?><Response><Dial><Client /></Dial></Response>') - - def test_add_client(self): - """ add a client to a dial""" - r = Response() - d = r.dial() - d.client("alice") - self.assertEquals(str(r), '<?xml version="1.0" encoding="UTF-8"?><Response><Dial><Client>alice</Client></Dial></Response>') - - def testAddConferenceConvenceMethod(self): - """ add a conference to a dial, conviently""" - r = Response() - d = r.addDial() - d.addConference("My Room") - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Dial><Conference>My Room</Conference></Dial></Response>') - - def testAddAttribute(self): - """add attribute""" - r = twiml.Conference("MyRoom", foo="bar") - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Conference foo="bar">MyRoom</Conference>') - - def testBadAppend(self): - """ should raise exceptions for wrong appending""" - self.improperAppend(twiml.Conference("Hello")) - - -class TestGather(TwilioTest): - - def testEmpty(self): - """ a gather with nothing inside""" - r = Response() - r.append(twiml.Gather()) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Gather /></Response>') - - def test_context_manager(self): - with Response() as r: - with r.gather() as g: - g.say("Hello") - - self.assertEquals(str(r), '<?xml version="1.0" encoding="UTF-8"?><Response><Gather><Say>Hello</Say></Gather></Response>') - - def testNestedSayPlayPause(self): - """ a gather with a say, play, and pause""" - r = Response() - g = twiml.Gather() - g.append(twiml.Say("Hey")) - g.append(twiml.Play("hey.mp3")) - g.append(twiml.Pause()) - r.append(g) - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Gather><Say>Hey</Say><Play>hey.mp3</Play><Pause /></Gather></Response>') - - def testNestedSayPlayPauseConvience(self): - """ a gather with a say, play, and pause""" - r = Response() - g = r.addGather() - g.addSay("Hey") - g.addPlay("hey.mp3") - g.addPause() - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Response><Gather><Say>Hey</Say><Play>hey.mp3</Play><Pause /></Gather></Response>') - - def testAddAttribute(self): - """add attribute""" - r = twiml.Gather(foo="bar") - r = self.strip(r) - self.assertEquals(r, '<?xml version="1.0" encoding="UTF-8"?><Gather foo="bar" />') - - def testNoDeclaration(self): - """add attribute""" - r = twiml.Gather(foo="bar") - self.assertEquals(r.toxml(xml_declaration=False), '<Gather foo="bar" />') - - def testImproperNesting(self): - """ bad nesting""" - verb = twiml.Gather() - self.assertRaises(TwimlException, verb.append, twiml.Gather()) - self.assertRaises(TwimlException, verb.append, twiml.Record()) - self.assertRaises(TwimlException, verb.append, twiml.Hangup()) - self.assertRaises(TwimlException, verb.append, twiml.Redirect()) - self.assertRaises(TwimlException, verb.append, twiml.Dial()) - self.assertRaises(TwimlException, verb.append, twiml.Conference("")) - self.assertRaises(TwimlException, verb.append, twiml.Sms("")) diff --git a/tests/test_unicode.py b/tests/test_unicode.py deleted file mode 100644 index 5916448118..0000000000 --- a/tests/test_unicode.py +++ /dev/null @@ -1,70 +0,0 @@ -# -*- coding: utf-8 -*- -from mock import patch, Mock -from six import u -from twilio.rest import resources - - -@patch("httplib2.Http") -@patch("twilio.rest.resources.base.Response") -def test_ascii_encode(resp_mock, mock): - http = mock.return_value - http.request.return_value = (Mock(), Mock()) - - data = { - "body": "HeyHey".encode('utf-8') - } - - resources.make_request("GET", "http://www.example.com", data=data) - - http.request.assert_called_with("http://www.example.com", "GET", - headers=None, body="body=HeyHey") - - -@patch("httplib2.Http") -@patch("twilio.rest.resources.base.Response") -def test_ascii(resp_mock, mock): - http = mock.return_value - http.request.return_value = (Mock(), Mock()) - - data = { - "body": "HeyHey" - } - - resources.make_request("GET", "http://www.example.com", data=data) - - http.request.assert_called_with("http://www.example.com", "GET", - headers=None, body="body=HeyHey") - - -@patch("httplib2.Http") -@patch("twilio.rest.resources.base.Response") -def test_double_encoding(resp_mock, mock): - http = mock.return_value - http.request.return_value = (Mock(), Mock()) - - body = u('Chlo\xe9\xf1') - - data = { - "body": body.encode('utf-8'), - } - - resources.make_request("GET", "http://www.example.com", data=data) - - http.request.assert_called_with("http://www.example.com", "GET", - headers=None, body="body=Chlo%C3%A9%C3%B1") - - -@patch("httplib2.Http") -@patch("twilio.rest.resources.base.Response") -def test_paging(resp_mock, mock): - http = mock.return_value - http.request.return_value = (Mock(), Mock()) - - data = { - "body": u('Chlo\xe9\xf1'), - } - - resources.make_request("GET", "http://www.example.com", data=data) - - http.request.assert_called_with("http://www.example.com", "GET", - headers=None, body="body=Chlo%C3%A9%C3%B1") diff --git a/tests/test_usage.py b/tests/test_usage.py deleted file mode 100644 index 9db77c0db8..0000000000 --- a/tests/test_usage.py +++ /dev/null @@ -1,89 +0,0 @@ -from mock import patch -from nose.tools import raises -from tools import create_mock_json -from twilio.rest.resources import Usage - -BASE_URI = "https://api.twilio.com/2010-04-01/Accounts/AC123" -ACCOUNT_SID = "AC123" -AUTH = (ACCOUNT_SID, "token") - -usage = Usage(BASE_URI, AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_triggers_create(request): - resp = create_mock_json("tests/resources/usage_triggers_instance.json") - resp.status_code = 201 - request.return_value = resp - - usage.triggers.create( - friendly_name="foo", - usage_category="sms", - trigger_by="count", - recurring="price", - trigger_value="10.00", - callback_url="http://www.example.com", - callback_method="POST" - ) - - uri = "%s/Usage/Triggers" % BASE_URI - request.assert_called_with("POST", uri, data={ - "FriendlyName": "foo", - "UsageCategory": "sms", - "TriggerBy": "count", - "Recurring": "price", - "TriggerValue": "10.00", - "CallbackUrl": "http://www.example.com", - "CallbackMethod": "POST" - }, auth=AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_triggers_paging(request): - resp = create_mock_json("tests/resources/usage_triggers_list.json") - request.return_value = resp - - uri = "%s/Usage/Triggers" % BASE_URI - usage.triggers.list( - recurring="daily", - usage_category="sms", - trigger_by="count") - - request.assert_called_with("GET", uri, params={ - "Recurring": "daily", - "UsageCategory": "sms", - "TriggerBy": "count" - }, auth=AUTH) - - -@patch("twilio.rest.resources.base.make_twilio_request") -def test_records_paging(request): - resp = create_mock_json("tests/resources/usage_records_list.json") - request.return_value = resp - - uri = "%s/Usage/Records" % BASE_URI - usage.records.list( - start_date="2012-10-12", - end_date="2012-10-13", - category="sms") - - request.assert_called_with("GET", uri, params={ - "StartDate": "2012-10-12", - "EndDate": "2012-10-13", - "Category": "sms" - }, auth=AUTH) - - -@raises(AttributeError) -def test_records_create(): - usage.records.all.create - - -@raises(AttributeError) -def test_records_delete(): - usage.records.all.delete - - -@raises(AttributeError) -def test_records_get(): - usage.records.all.get('abc') diff --git a/tests/test_validation.py b/tests/test_validation.py deleted file mode 100644 index 3dcc2bbb38..0000000000 --- a/tests/test_validation.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -from six import b - -import six -if six.PY3: - import unittest -else: - import unittest2 as unittest -from twilio.util import RequestValidator - - -class ValidationTest(unittest.TestCase): - - def test_validation(self): - token = "1c892n40nd03kdnc0112slzkl3091j20" - validator = RequestValidator(token) - - uri = "http://www.postbin.org/1ed898x" - params = { - "AccountSid": "AC9a9f9392lad99kla0sklakjs90j092j3", - "ApiVersion": "2010-04-01", - "CallSid": "CAd800bb12c0426a7ea4230e492fef2a4f", - "CallStatus": "ringing", - "Called": "+15306384866", - "CalledCity": "OAKLAND", - "CalledCountry": "US", - "CalledState": "CA", - "CalledZip": "94612", - "Caller": "+15306666666", - "CallerCity": "SOUTH LAKE TAHOE", - "CallerCountry": "US", - "CallerName": "CA Wireless Call", - "CallerState": "CA", - "CallerZip": "89449", - "Direction": "inbound", - "From": "+15306666666", - "FromCity": "SOUTH LAKE TAHOE", - "FromCountry": "US", - "FromState": "CA", - "FromZip": "89449", - "To": "+15306384866", - "ToCity": "OAKLAND", - "ToCountry": "US", - "ToState": "CA", - "ToZip": "94612", - } - - expected = b("fF+xx6dTinOaCdZ0aIeNkHr/ZAA=") - - self.assertEquals(validator.compute_signature(uri, params), expected) - self.assertTrue(validator.validate(uri, params, expected)) diff --git a/tests/tools.py b/tests/tools.py deleted file mode 100644 index 070853ba67..0000000000 --- a/tests/tools.py +++ /dev/null @@ -1,9 +0,0 @@ -from __future__ import with_statement -from mock import Mock - - -def create_mock_json(path): - with open(path) as f: - resp = Mock() - resp.content = f.read() - return resp diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/tests/unit/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/base/__init__.py b/tests/unit/base/__init__.py new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/tests/unit/base/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/base/test_deprecation.py b/tests/unit/base/test_deprecation.py new file mode 100644 index 0000000000..46164e1174 --- /dev/null +++ b/tests/unit/base/test_deprecation.py @@ -0,0 +1,39 @@ +import unittest +import warnings + +from twilio.base.obsolete import deprecated_method + + +class DeprecatedMethodTest(unittest.TestCase): + def test_deprecation_decorator(self): + @deprecated_method + def old_method(): + return True + + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.simplefilter("always") + # Call function that should raise a warning, but still execute + self.assertTrue(old_method()) + self.assertTrue(len(caught_warnings)) + self.assertEqual( + str(caught_warnings[0].message), + "Function method .old_method() is deprecated", + ) + assert issubclass(caught_warnings[0].category, DeprecationWarning) + + def test_deprecation_decorator_with_new_method(self): + @deprecated_method("new_method") + def old_method(): + return True + + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.simplefilter("always") + + # Call function that should raise a warning, but still execute + self.assertTrue(old_method()) + self.assertTrue(len(caught_warnings)) + self.assertEqual( + str(caught_warnings[0].message), + "Function method .old_method() is deprecated in favor of .new_method()", + ) + assert issubclass(caught_warnings[0].category, DeprecationWarning) diff --git a/tests/unit/base/test_deserialize.py b/tests/unit/base/test_deserialize.py new file mode 100644 index 0000000000..33f627e838 --- /dev/null +++ b/tests/unit/base/test_deserialize.py @@ -0,0 +1,79 @@ +import datetime +import unittest +from decimal import Decimal + +from twilio.base import deserialize + + +class Iso8601DateTestCase(unittest.TestCase): + def test_parsable(self): + actual = deserialize.iso8601_date("2015-01-02") + expected = datetime.date(2015, 1, 2) + self.assertEqual(expected, actual) + + def test_not_parsable(self): + actual = deserialize.iso8601_date("not-a-date") + self.assertEqual("not-a-date", actual) + + +class Iso8601DateTimeTestCase(unittest.TestCase): + def test_parsable(self): + actual = deserialize.iso8601_datetime("2015-01-02T03:04:05Z") + expected = datetime.datetime(2015, 1, 2, 3, 4, 5, 0, datetime.timezone.utc) + self.assertEqual(expected, actual) + + def test_not_parsable(self): + actual = deserialize.iso8601_datetime("not-a-datetime") + self.assertEqual("not-a-datetime", actual) + + +class DecimalTestCase(unittest.TestCase): + def test_none(self): + self.assertEqual(None, deserialize.decimal(None)) + + def test_empty_string(self): + self.assertEqual("", deserialize.decimal("")) + + def test_zero_string(self): + self.assertEqual(Decimal("0.0000"), deserialize.decimal("0.0000")) + + def test_negative_string(self): + self.assertEqual(Decimal("-0.0123"), deserialize.decimal("-0.0123")) + + def test_positive_string(self): + self.assertEqual(Decimal("0.0123"), deserialize.decimal("0.0123")) + + def test_zero(self): + self.assertEqual(0, deserialize.decimal(0)) + + def test_negative(self): + self.assertEqual(-0.0123, deserialize.decimal(-0.0123)) + + def test_positive(self): + self.assertEqual(0.0123, deserialize.decimal(0.0123)) + + +class IntegerTestCase(unittest.TestCase): + def test_none(self): + self.assertEqual(None, deserialize.integer(None)) + + def test_empty_string(self): + self.assertEqual("", deserialize.integer("")) + + def test_zero_string(self): + self.assertEqual(0, deserialize.integer("0")) + + def test_negative_string(self): + self.assertEqual(-1, deserialize.integer("-1")) + + def test_positive_string(self): + self.assertEqual(1, deserialize.integer("1")) + + def test_zero(self): + self.assertEqual(0, deserialize.integer(0)) + + def test_negative(self): + self.assertEqual(-1, deserialize.integer(-1)) + + def test_positive(self): + self.assertEqual(1, deserialize.integer(1)) diff --git a/tests/unit/base/test_serialize.py b/tests/unit/base/test_serialize.py new file mode 100644 index 0000000000..57891a65b7 --- /dev/null +++ b/tests/unit/base/test_serialize.py @@ -0,0 +1,142 @@ +import datetime +import unittest + +from twilio.base import serialize, values + + +class Iso8601DateTestCase(unittest.TestCase): + def test_unset(self): + value = values.unset + actual = serialize.iso8601_date(value) + self.assertEqual(values.unset, actual) + + def test_datetime(self): + value = datetime.datetime(2015, 1, 2, 12, 0, 0, 0) + actual = serialize.iso8601_date(value) + self.assertEqual("2015-01-02", actual) + + def test_datetime_without_time(self): + value = datetime.datetime(2015, 1, 2) + actual = serialize.iso8601_date(value) + self.assertEqual("2015-01-02", actual) + + def test_date(self): + value = datetime.date(2015, 1, 2) + actual = serialize.iso8601_date(value) + self.assertEqual("2015-01-02", actual) + + def test_str(self): + actual = serialize.iso8601_date("2015-01-02") + self.assertEqual("2015-01-02", actual) + + +class Iso8601DateTimeTestCase(unittest.TestCase): + def test_unset(self): + value = values.unset + actual = serialize.iso8601_datetime(value) + self.assertEqual(values.unset, actual) + + def test_datetime(self): + value = datetime.datetime(2015, 1, 2, 3, 4, 5, 6) + actual = serialize.iso8601_datetime(value) + self.assertEqual("2015-01-02T03:04:05Z", actual) + + def test_datetime_without_time(self): + value = datetime.datetime(2015, 1, 2) + actual = serialize.iso8601_datetime(value) + self.assertEqual("2015-01-02T00:00:00Z", actual) + + def test_date(self): + value = datetime.date(2015, 1, 2) + actual = serialize.iso8601_datetime(value) + self.assertEqual("2015-01-02T00:00:00Z", actual) + + def test_str(self): + actual = serialize.iso8601_datetime("2015-01-02T03:04:05Z") + self.assertEqual("2015-01-02T03:04:05Z", actual) + + +class PrefixedCollapsibleMapTestCase(unittest.TestCase): + def test_unset(self): + value = values.unset + actual = serialize.prefixed_collapsible_map(value, "Prefix") + self.assertEqual({}, actual) + + def test_single_key(self): + value = {"foo": "bar"} + actual = serialize.prefixed_collapsible_map(value, "Prefix") + self.assertEqual({"Prefix.foo": "bar"}, actual) + + def test_nested_key(self): + value = {"foo": {"bar": "baz"}} + actual = serialize.prefixed_collapsible_map(value, "Prefix") + self.assertEqual({"Prefix.foo.bar": "baz"}, actual) + + def test_multiple_keys(self): + value = {"watson": {"language": "en", "alice": "bob"}, "foo": "bar"} + actual = serialize.prefixed_collapsible_map(value, "Prefix") + self.assertEqual( + { + "Prefix.watson.language": "en", + "Prefix.watson.alice": "bob", + "Prefix.foo": "bar", + }, + actual, + ) + + def test_list(self): + value = ["foo", "bar"] + actual = serialize.prefixed_collapsible_map(value, "Prefix") + self.assertEqual({}, actual) + + +class BooleanTestCase(unittest.TestCase): + def test_none(self): + value = None + actual = serialize.boolean_to_string(value) + self.assertIsNone(actual) + + def test_string(self): + value = "True" + actual = serialize.boolean_to_string(value) + self.assertEqual("true", actual) + + def test_bool_true(self): + value = True + actual = serialize.boolean_to_string(value) + self.assertEqual("true", actual) + + def test_bool_false(self): + value = False + actual = serialize.boolean_to_string(value) + self.assertEqual("false", actual) + + +class ObjectTestCase(unittest.TestCase): + def test_object(self): + actual = serialize.object({"twilio": "rocks"}) + self.assertEqual('{"twilio": "rocks"}', actual) + + def test_list(self): + actual = serialize.object(["twilio", "rocks"]) + self.assertEqual('["twilio", "rocks"]', actual) + + def test_does_not_change_other_types(self): + actual = serialize.object('{"attribute":"value"}') + self.assertEqual('{"attribute":"value"}', actual) + + +class MapTestCase(unittest.TestCase): + def test_maps_func_to_list(self): + actual = serialize.map([1, 2, 3], lambda e: e * 2) + self.assertEqual([2, 4, 6], actual) + + def test_does_not_change_other_types(self): + actual = serialize.map("abc", lambda e: e * 2) + self.assertEqual("abc", actual) + + actual = serialize.map(123, lambda e: e * 2) + self.assertEqual(123, actual) + + actual = serialize.map({"some": "val"}, lambda e: e * 2) + self.assertEqual({"some": "val"}, actual) diff --git a/tests/unit/base/test_version.py b/tests/unit/base/test_version.py new file mode 100644 index 0000000000..1f1f6395eb --- /dev/null +++ b/tests/unit/base/test_version.py @@ -0,0 +1,91 @@ +from tests import IntegrationTestCase +from tests.holodeck import Request +from twilio.base.page import Page +from twilio.http.response import Response + + +class TestPage(Page): + def get_instance(self, payload): + return payload + + +class StreamTestCase(IntegrationTestCase): + def setUp(self): + super(StreamTestCase, self).setUp() + + self.holodeck.mock( + Response( + 200, + """ + { + "next_page_uri": "/2010-04-01/Accounts/AC123/Messages.json?Page=1", + "messages": [{"body": "payload0"}, {"body": "payload1"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json" + ), + ) + + self.holodeck.mock( + Response( + 200, + """ + { + "next_page_uri": "/2010-04-01/Accounts/AC123/Messages.json?Page=2", + "messages": [{"body": "payload2"}, {"body": "payload3"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json?Page=1" + ), + ) + + self.holodeck.mock( + Response( + 200, + """ + { + "next_page_uri": null, + "messages": [{"body": "payload4"}] + } + """, + ), + Request( + url="https://api.twilio.com/2010-04-01/Accounts/AC123/Messages.json?Page=2" + ), + ) + + self.version = self.client.api.v2010 + self.response = self.version.page( + method="GET", uri="/Accounts/AC123/Messages.json" + ) + self.page = TestPage(self.version, self.response, {}) + + def test_stream(self): + messages = list(self.version.stream(self.page)) + + self.assertEqual(len(messages), 5) + + def test_stream_limit(self): + messages = list(self.version.stream(self.page, limit=3)) + + self.assertEqual(len(messages), 3) + + def test_stream_page_limit(self): + messages = list(self.version.stream(self.page, page_limit=1)) + + self.assertEqual(len(messages), 2) + + +class VersionTestCase(IntegrationTestCase): + def test_fetch_redirect(self): + self.holodeck.mock( + Response(307, '{"redirect_to": "some_place"}'), + Request(url="https://messaging.twilio.com/v1/Deactivations"), + ) + response = self.client.messaging.v1.fetch(method="GET", uri="/Deactivations") + + self.assertIsNotNone(response) diff --git a/tests/unit/http/__init__.py b/tests/unit/http/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/http/test_async_http_client.py b/tests/unit/http/test_async_http_client.py new file mode 100644 index 0000000000..23df35dc02 --- /dev/null +++ b/tests/unit/http/test_async_http_client.py @@ -0,0 +1,133 @@ +import aiounittest + +from aiohttp import ClientSession +from mock import patch, AsyncMock +from twilio.http.async_http_client import AsyncTwilioHttpClient + + +class MockResponse(object): + """ + A mock of the aiohttp.ClientResponse class + """ + + def __init__(self, text, status, method="GET"): + self._text = text + self.status = status + self.headers = {} + self.method = method + + async def text(self): + return self._text + + +class TestAsyncHttpClientRequest(aiounittest.AsyncTestCase): + def setUp(self): + self.session_mock = AsyncMock(wraps=ClientSession) + self.session_mock.request.return_value = MockResponse("test", 200) + + self.session_patcher = patch("twilio.http.async_http_client.ClientSession") + session_constructor_mock = self.session_patcher.start() + session_constructor_mock.return_value = self.session_mock + + self.client = AsyncTwilioHttpClient() + + def tearDown(self): + self.session_patcher.stop() + + async def test_request_called_with_method_and_url(self): + await self.client.request("GET", "https://mock.twilio.com") + + self.session_mock.request.assert_called() + request_args = self.session_mock.request.call_args.kwargs + self.assertIsNotNone(request_args) + self.assertEqual(request_args["method"], "GET") + self.assertEqual(request_args["url"], "https://mock.twilio.com") + + async def test_request_called_with_basic_auth(self): + await self.client.request( + "doesnt matter", "doesnt matter", auth=("account_sid", "auth_token") + ) + + self.session_mock.request.assert_called() + auth = self.session_mock.request.call_args.kwargs["auth"] + self.assertIsNotNone(auth) + self.assertEqual(auth.login, "account_sid") + self.assertEqual(auth.password, "auth_token") + + async def test_invalid_request_timeout_raises_exception(self): + with self.assertRaises(ValueError): + await self.client.request("doesnt matter", "doesnt matter", timeout=-1) + + +class TestAsyncHttpClientRetries(aiounittest.AsyncTestCase): + def setUp(self): + self.session_mock = AsyncMock(wraps=ClientSession) + self.session_mock.request.side_effect = [ + MockResponse("Error", 500), + MockResponse("Error", 500), + MockResponse("Success", 200), + ] + + self.session_patcher = patch("twilio.http.async_http_client.ClientSession") + session_constructor_mock = self.session_patcher.start() + session_constructor_mock.return_value = self.session_mock + + def tearDown(self): + self.session_patcher.stop() + + async def test_request_retries_until_success(self): + client = AsyncTwilioHttpClient(max_retries=99) + response = await client.request("doesnt matter", "doesnt matter") + + self.assertEqual(self.session_mock.request.call_count, 3) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.text, "Success") + + async def test_request_retries_until_max(self): + client = AsyncTwilioHttpClient(max_retries=2) + response = await client.request("doesnt matter", "doesnt matter") + + self.assertEqual(self.session_mock.request.call_count, 2) + self.assertEqual(response.status_code, 500) + self.assertEqual(response.text, "Error") + + +class TestAsyncHttpClientSession(aiounittest.AsyncTestCase): + def setUp(self): + self.session_patcher = patch("twilio.http.async_http_client.ClientSession") + self.session_constructor_mock = self.session_patcher.start() + + def tearDown(self): + self.session_patcher.stop() + + def _setup_session_response(self, value): + session_mock = AsyncMock(wraps=ClientSession) + session_mock.request.return_value = MockResponse(value, 200) + session_mock.close.return_value = None + self.session_constructor_mock.return_value = session_mock + + async def test_session_preserved(self): + self._setup_session_response("response_1") + + client = AsyncTwilioHttpClient() + response_1 = await client.request("GET", "https://api.twilio.com") + + self._setup_session_response("response_2") + response_2 = await client.request("GET", "https://api.twilio.com") + + # Used same session, response should be the same + self.assertEqual(response_1.content, "response_1") + self.assertEqual(response_2.content, "response_1") + + async def test_session_not_preserved(self): + self._setup_session_response("response_1") + + client = AsyncTwilioHttpClient(pool_connections=False) + response_1 = await client.request("GET", "https://api.twilio.com") + + self._setup_session_response("response_2") + response_2 = await client.request("GET", "https://api.twilio.com") + + # No session used, responses should be different (not cached) + self.assertEqual(response_1.content, "response_1") + self.assertEqual(response_2.content, "response_2") diff --git a/tests/unit/http/test_http_client.py b/tests/unit/http/test_http_client.py new file mode 100644 index 0000000000..8484e57b17 --- /dev/null +++ b/tests/unit/http/test_http_client.py @@ -0,0 +1,299 @@ +# -*- coding: utf-8 -*- +import os +import unittest +from collections import OrderedDict + +from mock import Mock, patch +from requests import Session + +from twilio.base.exceptions import TwilioRestException +from twilio.base.version import Version +from twilio.http.http_client import TwilioHttpClient +from twilio.http.response import Response + + +class TestHttpClientRequest(unittest.TestCase): + def setUp(self): + self.session_patcher = patch("twilio.http.http_client.Session") + + self.session_mock = Mock(wraps=Session()) + self.request_mock = Mock() + + self.session_mock.prepare_request.return_value = self.request_mock + self.session_mock.send.return_value = Response(200, "testing-unicode: Ω≈ç√, 💩") + self.request_mock.headers = {} + + session_constructor_mock = self.session_patcher.start() + session_constructor_mock.return_value = self.session_mock + + self.client = TwilioHttpClient() + + def tearDown(self): + self.session_patcher.stop() + + def test_request_sets_host_header_if_missing(self): + self.request_mock.url = "https://api.twilio.com/" + self.request_mock.headers = {"Host": "other.twilio.com"} + + self.client.request("doesnt matter", "doesnt matter") + + self.assertEqual("other.twilio.com", self.request_mock.headers["Host"]) + self.assertIsNotNone(self.client._test_only_last_request) + self.assertIsNotNone(self.client._test_only_last_response) + + def test_request_with_timeout(self): + self.request_mock.url = "https://api.twilio.com/" + self.request_mock.headers = {"Host": "other.twilio.com"} + + response = self.client.request( + "doesnt matter", "doesnt matter", None, None, None, None, 30 + ) + + self.assertEqual("other.twilio.com", self.request_mock.headers["Host"]) + self.assertEqual(200, response.status_code) + self.assertEqual("testing-unicode: Ω≈ç√, 💩", response.content) + + def test_request_where_method_timeout_equals_zero(self): + self.request_mock.url = "https://api.twilio.com/" + self.request_mock.headers = {"Host": "other.twilio.com"} + + try: + self.client.request( + "doesnt matter", "doesnt matter", None, None, None, None, 0 + ) + except Exception as e: + self.assertEqual(ValueError, type(e)) + + def test_request_where_class_timeout_manually_set(self): + self.request_mock.url = "https://api.twilio.com/" + self.request_mock.headers = {"Host": "other.twilio.com"} + self.client.timeout = 30 + + response = self.client.request("doesnt matter", "doesnt matter") + self.assertEqual("other.twilio.com", self.request_mock.headers["Host"]) + self.assertEqual(200, response.status_code) + self.assertEqual("testing-unicode: Ω≈ç√, 💩", response.content) + + def test_request_where_class_timeout_equals_zero(self): + self.request_mock.url = "https://api.twilio.com/" + self.request_mock.headers = {"Host": "other.twilio.com"} + self.client.timeout = 0 + + try: + self.client.request("doesnt matter", "doesnt matter") + except Exception as e: + self.assertEqual(type(e), ValueError) + + def test_request_where_class_timeout_and_method_timeout_set(self): + self.request_mock.url = "https://api.twilio.com/" + self.request_mock.headers = {"Host": "other.twilio.com"} + self.client.timeout = 30 + + response = self.client.request( + "doesnt matter", "doesnt matter", None, None, None, None, 15 + ) + + self.assertEqual("other.twilio.com", self.request_mock.headers["Host"]) + self.assertEqual(200, response.status_code) + self.assertEqual("testing-unicode: Ω≈ç√, 💩", response.content) + + def test_request_with_unicode_response(self): + self.request_mock.url = "https://api.twilio.com/" + self.request_mock.headers = {"Host": "other.twilio.com"} + + response = self.client.request("doesnt matter", "doesnt matter") + + self.assertEqual("other.twilio.com", self.request_mock.headers["Host"]) + self.assertEqual(200, response.status_code) + self.assertEqual("testing-unicode: Ω≈ç√, 💩", response.content) + + def test_last_request_last_response_exist(self): + self.request_mock.url = "https://api.twilio.com/" + self.request_mock.headers = {"Host": "other.twilio.com"} + + self.client.request( + "doesnt-matter-method", + "doesnt-matter-url", + {"params-value": "params-key"}, + {"data-value": "data-key"}, + {"headers-value": "headers-key"}, + ["a", "b"], + ) + + self.assertIsNotNone(self.client._test_only_last_request) + self.assertEqual("doesnt-matter-url", self.client._test_only_last_request.url) + self.assertEqual( + "DOESNT-MATTER-METHOD", self.client._test_only_last_request.method + ) + self.assertEqual( + {"params-value": "params-key"}, self.client._test_only_last_request.params + ) + self.assertEqual( + {"data-value": "data-key"}, self.client._test_only_last_request.data + ) + self.assertEqual( + {"headers-value": "headers-key"}, + self.client._test_only_last_request.headers, + ) + self.assertEqual(["a", "b"], self.client._test_only_last_request.auth) + + self.assertIsNotNone(self.client._test_only_last_response) + + if self.client._test_only_last_response is not None: + self.assertEqual(200, self.client._test_only_last_response.status_code) + self.assertEqual( + "testing-unicode: Ω≈ç√, 💩", self.client._test_only_last_response.text + ) + + def test_request_with_json(self): + self.request_mock.url = "https://api.twilio.com/" + self.request_mock.headers = {"Host": "other.twilio.com"} + + self.client.request( + "doesnt-matter-method", + "doesnt-matter-url", + {"params-value": "params-key"}, + {"json-key": "json-value"}, + {"Content-Type": "application/json"}, + ) + + self.assertIsNotNone(self.client._test_only_last_request) + self.assertEqual( + {"Content-Type": "application/json"}, + self.client._test_only_last_request.headers, + ) + + self.assertIsNotNone(self.client._test_only_last_response) + + if self.client._test_only_last_response is not None: + self.assertEqual(200, self.client._test_only_last_response.status_code) + self.assertEqual( + "testing-unicode: Ω≈ç√, 💩", self.client._test_only_last_response.text + ) + + def test_last_response_empty_on_error(self): + self.session_mock.send.side_effect = Exception("voltron") + + with self.assertRaises(Exception): + self.client.request("doesnt-matter", "doesnt-matter") + + self.assertIsNotNone(self.client._test_only_last_request) + self.assertIsNone(self.client._test_only_last_response) + + def test_request_behind_proxy(self): + self.request_mock.url = "https://api.twilio.com/" + proxies = OrderedDict( + [ + ("http", "http://proxy.twilio.com"), + ("https", "https://proxy.twilio.com"), + ] + ) + self.client = TwilioHttpClient(proxy=proxies) + self.client.request("doesnt matter", "doesnt matter") + self.session_mock.send.assert_called_once_with( + self.request_mock, + verify=True, + proxies=proxies, + stream=False, + cert=None, + allow_redirects=False, + timeout=None, + ) + + @patch.dict( + os.environ, + { + "HTTP_PROXY": "http://proxy.twilio.com", + "HTTPS_PROXY": "https://proxy.twilio.com", + }, + ) + def test_request_behind_proxy_from_environment(self): + self.request_mock.url = "https://api.twilio.com/" + self.client = TwilioHttpClient() + self.client.request("doesnt matter", "doesnt matter") + self.session_mock.send.assert_called_once_with( + self.request_mock, + verify=True, + proxies=OrderedDict( + [ + ("http", "http://proxy.twilio.com"), + ("https", "https://proxy.twilio.com"), + ] + ), + stream=False, + cert=None, + allow_redirects=False, + timeout=None, + ) + + def test_exception_with_details(self): + self.request_mock.url = "https://api.twilio.com/" + v1 = MyVersion(self.client) + error_text = """{ + "code": 20001, + "message": "Bad request", + "more_info": "https://www.twilio.com/docs/errors/20001", + "status": 400, + "details": { + "foo":"bar" + } + }""" + self.session_mock.send.return_value = Response(400, error_text) + try: + v1.fetch("get", "none", None, None, None, None, None) + self.fail("should not happen") + except TwilioRestException as err: + self.assertEqual(400, err.status) + self.assertEqual(20001, err.code) + self.assertEqual("get", err.method) + self.assertEqual("Unable to fetch record: Bad request", err.msg) + self.assertEqual({"foo": "bar"}, err.details) + + +class TestHttpClientSession(unittest.TestCase): + def setUp(self): + self.session_patcher = patch("twilio.http.http_client.Session") + self.session_constructor_mock = self.session_patcher.start() + + def tearDown(self): + self.session_patcher.stop() + + def _setup_session_response(self, value): + session_mock = Mock(wraps=Session()) + request_mock = Mock(url="https://api.twilio.com/") + + session_mock.prepare_request.return_value = request_mock + session_mock.send.return_value = Response(200, value) + self.session_constructor_mock.return_value = session_mock + + def test_session_preserved(self): + self._setup_session_response("response_1") + + client = TwilioHttpClient() + response_1 = client.request("GET", "https://api.twilio.com") + + self._setup_session_response("response_2") + response_2 = client.request("GET", "https://api.twilio.com") + + # Used same session, response should be the same + self.assertEqual(response_1.content, "response_1") + self.assertEqual(response_2.content, "response_1") + + def test_session_not_preserved(self): + self._setup_session_response("response_1") + + client = TwilioHttpClient(pool_connections=False) + response_1 = client.request("GET", "https://api.twilio.com") + + self._setup_session_response("response_2") + response_2 = client.request("GET", "https://api.twilio.com") + + # Used different session, responses should be different + self.assertEqual(response_1.content, "response_1") + self.assertEqual(response_2.content, "response_2") + + +class MyVersion(Version): + def __init__(self, domain): + super().__init__(domain, "v1") + self._credentials = None diff --git a/tests/unit/http/test_validation_client.py b/tests/unit/http/test_validation_client.py new file mode 100644 index 0000000000..5fdd4cb9fc --- /dev/null +++ b/tests/unit/http/test_validation_client.py @@ -0,0 +1,144 @@ +# -*- coding: utf-8 -*- + +import unittest + +from mock import patch, Mock +from requests import Request +from requests import Session + +from twilio.base.exceptions import TwilioRestException +from twilio.http.validation_client import ValidationClient +from twilio.http.response import Response + + +class TestValidationClientHelpers(unittest.TestCase): + def setUp(self): + self.request = Request( + "GET", + "https://api.twilio.com/2010-04-01/Accounts/AC123/Messages", + auth=("Username", "Password"), + ) + self.request = self.request.prepare() + self.client = ValidationClient("AC123", "SK123", "CR123", "private_key") + + def test_build_validation_payload_basic(self): + validation_payload = self.client._build_validation_payload(self.request) + self.assertEqual("GET", validation_payload.method) + self.assertEqual("/2010-04-01/Accounts/AC123/Messages", validation_payload.path) + self.assertEqual("", validation_payload.query_string) + self.assertEqual(["authorization", "host"], validation_payload.signed_headers) + self.assertEqual("", validation_payload.body) + + def test_build_validation_payload_query_string_parsed(self): + self.request.url = (self.request.url or "") + "?QueryParam=1&Other=true" + + validation_payload = self.client._build_validation_payload(self.request) + + self.assertEqual("GET", validation_payload.method) + self.assertEqual("/2010-04-01/Accounts/AC123/Messages", validation_payload.path) + self.assertEqual("QueryParam=1&Other=true", validation_payload.query_string) + self.assertEqual(["authorization", "host"], validation_payload.signed_headers) + self.assertEqual("", validation_payload.body) + + def test_build_validation_payload_body_parsed(self): + setattr(self.request, "body", "foobar") + + validation_payload = self.client._build_validation_payload(self.request) + + self.assertEqual("GET", validation_payload.method) + self.assertEqual("/2010-04-01/Accounts/AC123/Messages", validation_payload.path) + self.assertEqual("", validation_payload.query_string) + self.assertEqual(["authorization", "host"], validation_payload.signed_headers) + self.assertEqual("foobar", validation_payload.body) + + def test_build_validation_payload_complex(self): + setattr(self.request, "body", "foobar") + self.request.url = ( + self.request.url or "" + ) + "?QueryParam=Value&OtherQueryParam=OtherValue" + + validation_payload = self.client._build_validation_payload(self.request) + + self.assertEqual("GET", validation_payload.method) + self.assertEqual("/2010-04-01/Accounts/AC123/Messages", validation_payload.path) + self.assertEqual(["authorization", "host"], validation_payload.signed_headers) + self.assertEqual("foobar", validation_payload.body) + self.assertEqual( + "QueryParam=Value&OtherQueryParam=OtherValue", + validation_payload.query_string, + ) + + def test_get_host(self): + self.assertEqual("api.twilio.com", self.client._get_host(self.request)) + + +class TestValidationClientRequest(unittest.TestCase): + def setUp(self): + self.session_patcher = patch("twilio.http.validation_client.Session") + self.jwt_patcher = patch("twilio.http.validation_client.ClientValidationJwt") + + self.session_mock = Mock(wraps=Session()) + self.validation_token = self.jwt_patcher.start() + self.request_mock = Mock() + + self.session_mock.prepare_request.return_value = self.request_mock + self.session_mock.send.return_value = Response( + 200, "test, omega: Ω, pile of poop: 💩" + ) + self.validation_token.return_value.to_jwt.return_value = "test-token" + self.request_mock.headers = {} + + session_constructor_mock = self.session_patcher.start() + session_constructor_mock.return_value = self.session_mock + + self.client = ValidationClient("AC123", "SK123", "CR123", "private_key") + + def tearDown(self): + self.session_patcher.stop() + self.jwt_patcher.stop() + + def test_request_does_not_overwrite_host_header(self): + self.request_mock.url = "https://api.twilio.com/" + + self.client.request("doesnt matter", "doesnt matter") + + self.assertEqual("api.twilio.com", self.request_mock.headers["Host"]) + self.assertEqual( + "test-token", self.request_mock.headers["Twilio-Client-Validation"] + ) + + def test_request_sets_host_header_if_missing(self): + self.request_mock.url = "https://api.twilio.com/" + self.request_mock.headers = {"Host": "other.twilio.com"} + + self.client.request("doesnt matter", "doesnt matter") + + self.assertEqual("other.twilio.com", self.request_mock.headers["Host"]) + self.assertEqual( + "test-token", self.request_mock.headers["Twilio-Client-Validation"] + ) + + def test_request_with_unicode_response(self): + self.request_mock.url = "https://api.twilio.com/" + self.request_mock.headers = {"Host": "other.twilio.com"} + + response = self.client.request("doesnt matter", "doesnt matter") + + self.assertEqual("other.twilio.com", self.request_mock.headers["Host"]) + self.assertEqual( + "test-token", self.request_mock.headers["Twilio-Client-Validation"] + ) + self.assertEqual(200, response.status_code) + self.assertEqual("test, omega: Ω, pile of poop: 💩", response.content) + + @patch("twilio.http.validation_client") + def test_validate_ssl_certificate_success(self, http_client): + http_client.request.return_value = Response(200, "success") + self.client.validate_ssl_certificate(http_client) + + @patch("twilio.http.validation_client") + def test_validate_ssl_certificate_error(self, http_client): + http_client.request.return_value = Response(504, "error") + + with self.assertRaises(TwilioRestException): + self.client.validate_ssl_certificate(http_client) diff --git a/tests/unit/jwt/__init__.py b/tests/unit/jwt/__init__.py new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/tests/unit/jwt/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/jwt/test_access_token.py b/tests/unit/jwt/test_access_token.py new file mode 100644 index 0000000000..7f1e908b37 --- /dev/null +++ b/tests/unit/jwt/test_access_token.py @@ -0,0 +1,253 @@ +import time +import unittest +from datetime import datetime + +from twilio.jwt.access_token import AccessToken +from twilio.jwt.access_token.grants import ( + SyncGrant, + VoiceGrant, + VideoGrant, + TaskRouterGrant, + ChatGrant, + PlaybackGrant, +) + +ACCOUNT_SID = "AC123" +SIGNING_KEY_SID = "SK123" + + +# python2.6 support +def assert_is_not_none(obj): + assert obj is not None, "%r is None" % obj + + +def assert_in(obj1, obj2): + assert obj1 in obj2, "%r is not in %r" % (obj1, obj2) + + +def assert_greater_equal(obj1, obj2): + assert obj1 > obj2, "%r is not greater than or equal to %r" % (obj1, obj2) + + +class AccessTokenTest(unittest.TestCase): + def _validate_claims(self, payload): + assert SIGNING_KEY_SID == payload["iss"] + assert ACCOUNT_SID == payload["sub"] + + assert payload["exp"] is not None + assert payload["jti"] is not None + assert payload["grants"] is not None + + assert payload["exp"] >= int(time.time()) + + assert payload["iss"] in payload["jti"] + + def test_empty_grants(self): + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") + token = scat.to_jwt() + + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") + self._validate_claims(decoded_token.payload) + assert {} == decoded_token.payload["grants"] + + def test_region(self): + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret", region="foo") + token = scat.to_jwt() + decoded_token = AccessToken.from_jwt(token, "secret") + assert decoded_token.headers["twr"] == "foo" + + def test_empty_region(self): + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") + token = scat.to_jwt() + decoded_token = AccessToken.from_jwt(token, "secret") + self.assertRaises(KeyError, lambda: decoded_token.headers["twr"]) + + def test_nbf(self): + now = int(time.mktime(datetime.now().timetuple())) + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret", nbf=now) + token = scat.to_jwt() + + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") + self._validate_claims(decoded_token.payload) + assert now == decoded_token.nbf + + def test_headers(self): + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") + token = scat.to_jwt() + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") + self.assertEqual(decoded_token.headers["cty"], "twilio-fpa;v=1") + + def test_identity(self): + scat = AccessToken( + ACCOUNT_SID, SIGNING_KEY_SID, "secret", identity="test@twilio.com" + ) + token = scat.to_jwt() + + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") + self._validate_claims(decoded_token.payload) + assert {"identity": "test@twilio.com"} == decoded_token.payload["grants"] + + def test_conversations_grant(self): + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") + scat.add_grant(VoiceGrant(outgoing_application_sid="CP123")) + + token = scat.to_jwt() + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") + self._validate_claims(decoded_token.payload) + assert 1 == len(decoded_token.payload["grants"]) + assert {"outgoing": {"application_sid": "CP123"}} == decoded_token.payload[ + "grants" + ]["voice"] + + def test_video_grant(self): + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") + scat.add_grant(VideoGrant(room="RM123")) + + token = scat.to_jwt() + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") + self._validate_claims(decoded_token.payload) + assert 1 == len(decoded_token.payload["grants"]) + assert {"room": "RM123"} == decoded_token.payload["grants"]["video"] + + def test_chat_grant(self): + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") + scat.add_grant(ChatGrant(service_sid="IS123", push_credential_sid="CR123")) + + token = scat.to_jwt() + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") + self._validate_claims(decoded_token.payload) + assert 1 == len(decoded_token.payload["grants"]) + assert { + "service_sid": "IS123", + "push_credential_sid": "CR123", + } == decoded_token.payload["grants"]["chat"] + + def test_sync_grant(self): + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") + scat.identity = "bender" + scat.add_grant(SyncGrant(service_sid="IS123", endpoint_id="blahblahendpoint")) + + token = scat.to_jwt() + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") + self._validate_claims(decoded_token.payload) + assert 2 == len(decoded_token.payload["grants"]) + assert "bender" == decoded_token.payload["grants"]["identity"] + assert { + "service_sid": "IS123", + "endpoint_id": "blahblahendpoint", + } == decoded_token.payload["grants"]["data_sync"] + + def test_grants(self): + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") + scat.add_grant(VideoGrant()) + scat.add_grant(ChatGrant()) + + token = scat.to_jwt() + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") + self._validate_claims(decoded_token.payload) + assert 2 == len(decoded_token.payload["grants"]) + assert {} == decoded_token.payload["grants"]["video"] + assert {} == decoded_token.payload["grants"]["chat"] + + def test_programmable_voice_grant(self): + grant = VoiceGrant( + outgoing_application_sid="AP123", outgoing_application_params={"foo": "bar"} + ) + + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") + scat.add_grant(grant) + + token = scat.to_jwt() + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") + self._validate_claims(decoded_token.payload) + assert 1 == len(decoded_token.payload["grants"]) + assert { + "outgoing": {"application_sid": "AP123", "params": {"foo": "bar"}} + } == decoded_token.payload["grants"]["voice"] + + def test_programmable_voice_grant_incoming(self): + grant = VoiceGrant(incoming_allow=True) + + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") + scat.add_grant(grant) + + token = scat.to_jwt() + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") + self._validate_claims(decoded_token.payload) + assert 1 == len(decoded_token.payload["grants"]) + assert {"incoming": {"allow": True}} == decoded_token.payload["grants"]["voice"] + + def test_task_router_grant(self): + grant = TaskRouterGrant( + workspace_sid="WS123", worker_sid="WK123", role="worker" + ) + + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") + scat.add_grant(grant) + + token = scat.to_jwt() + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") + self._validate_claims(decoded_token.payload) + assert 1 == len(decoded_token.payload["grants"]) + assert { + "workspace_sid": "WS123", + "worker_sid": "WK123", + "role": "worker", + } == decoded_token.payload["grants"]["task_router"] + + def test_playback_grant(self): + """Test that PlaybackGrants are created and decoded correctly.""" + grant = { + "requestCredentials": None, + "playbackUrl": "https://000.us-east-1.playback.live-video.net/api/video/v1/us-east-000.channel.000?token=xxxxx", + "playerStreamerSid": "VJXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", + } + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") + scat.add_grant(PlaybackGrant(grant=grant)) + token = scat.to_jwt() + assert token is not None + decoded_token = AccessToken.from_jwt(token, "secret") + self._validate_claims(decoded_token.payload) + assert 1 == len(decoded_token.payload["grants"]) + assert grant == decoded_token.payload["grants"]["player"] + + def test_pass_grants_in_constructor(self): + grants = [VideoGrant(), ChatGrant()] + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret", grants=grants) + + token = scat.to_jwt() + assert token is not None + + decoded_token = AccessToken.from_jwt(token, "secret") + self._validate_claims(decoded_token.payload) + assert 2 == len(decoded_token.payload["grants"]) + assert {} == decoded_token.payload["grants"]["video"] + assert {} == decoded_token.payload["grants"]["chat"] + + def test_constructor_validates_grants(self): + grants = [VideoGrant, "GrantMeAccessToEverything"] + self.assertRaises( + ValueError, + AccessToken, + ACCOUNT_SID, + SIGNING_KEY_SID, + "secret", + grants=grants, + ) + + def test_add_grant_validates_grant(self): + scat = AccessToken(ACCOUNT_SID, SIGNING_KEY_SID, "secret") + scat.add_grant(VideoGrant()) + self.assertRaises(ValueError, scat.add_grant, "GrantRootAccess") diff --git a/tests/unit/jwt/test_client.py b/tests/unit/jwt/test_client.py new file mode 100644 index 0000000000..3fa90de9f8 --- /dev/null +++ b/tests/unit/jwt/test_client.py @@ -0,0 +1,119 @@ +import time +import unittest + +from twilio.jwt import Jwt +from twilio.jwt.client import ClientCapabilityToken, ScopeURI + + +class ClientCapabilityTokenTest(unittest.TestCase): + def assertIn(self, foo, bar, msg=None): + """backport for 2.6""" + assert foo in bar, msg or "%s not found in %s" % (foo, bar) + + def now(self): + return int(time.time()) + + def test_no_permissions(self): + token = ClientCapabilityToken("AC123", "XXXXX") + assert len(token._generate_payload()) == 1 + assert token._generate_payload()["scope"] == "" + + def test_inbound_permissions(self): + token = ClientCapabilityToken("AC123", "XXXXX") + token.allow_client_incoming("andy") + + eurl = "scope:client:incoming?clientName=andy" + assert len(token._generate_payload()) == 1 + assert token._generate_payload()["scope"] == eurl + + def test_outbound_permissions(self): + token = ClientCapabilityToken("AC123", "XXXXX") + token.allow_client_outgoing("AP123") + + eurl = "scope:client:outgoing?appSid=AP123" + + assert len(token._generate_payload()) == 1 + self.assertIn(eurl, token._generate_payload()["scope"]) + + def test_outbound_permissions_params(self): + token = ClientCapabilityToken("AC123", "XXXXX") + token.allow_client_outgoing("AP123", foobar=3) + + eurl = "scope:client:outgoing?appParams=foobar%3D3&appSid=AP123" + assert token.payload["scope"] == eurl + + def test_events(self): + token = ClientCapabilityToken("AC123", "XXXXX") + token.allow_event_stream() + + event_uri = "scope:stream:subscribe?path=%2F2010-04-01%2FEvents" + assert token.payload["scope"] == event_uri + + def test_events_with_filters(self): + token = ClientCapabilityToken("AC123", "XXXXX") + token.allow_event_stream(foobar="hey") + + event_uri = ( + "scope:stream:subscribe?params=foobar%3Dhey&path=%2F2010-04-01%2FEvents" + ) + assert token.payload["scope"] == event_uri + + def test_decode(self): + token = ClientCapabilityToken("AC123", "XXXXX") + token.allow_client_outgoing("AP123", foobar=3) + token.allow_client_incoming("andy") + token.allow_event_stream() + + outgoing_uri = ( + "scope:client:outgoing?appParams=foobar%3D3&appSid=AP123&clientName=andy" + ) + incoming_uri = "scope:client:incoming?clientName=andy" + event_uri = "scope:stream:subscribe?path=%2F2010-04-01%2FEvents" + + result = Jwt.from_jwt(token.to_jwt(), "XXXXX") + scope = result.payload["scope"].split(" ") + + self.assertIn(outgoing_uri, scope) + self.assertIn(incoming_uri, scope) + self.assertIn(event_uri, scope) + + def test_encode_full_payload(self): + token = ClientCapabilityToken("AC123", "XXXXX") + token.allow_event_stream(foobar="hey") + token.allow_client_incoming("andy") + + event_uri = ( + "scope:stream:subscribe?params=foobar%3Dhey&path=%2F2010-04-01%2FEvents" + ) + incoming_uri = "scope:client:incoming?clientName=andy" + + self.assertIn(event_uri, token.payload["scope"]) + self.assertIn(incoming_uri, token.payload["scope"]) + self.assertEqual(token.payload["iss"], "AC123") + self.assertGreaterEqual(token.payload["exp"], self.now()) + + def test_pass_scopes_in_constructor(self): + token = ClientCapabilityToken( + "AC123", + "XXXXX", + allow_client_outgoing={"application_sid": "AP123", "param1": "val1"}, + ) + outgoing_uri = "scope:client:outgoing?appParams=param1%3Dval1&appSid=AP123" + result = Jwt.from_jwt(token.to_jwt(), "XXXXX") + self.assertEqual(outgoing_uri, result.payload["scope"]) + + +class ScopeURITest(unittest.TestCase): + def test_to_payload_no_params(self): + scope_uri = ScopeURI("service", "godmode") + self.assertEqual("scope:service:godmode", scope_uri.to_payload()) + + def test_to_payload_with_params(self): + scope_uri = ScopeURI("service", "godmode", {"key": "val"}) + self.assertEqual("scope:service:godmode?key=val", scope_uri.to_payload()) + + def test_to_payload_with_params_encoded(self): + scope_uri = ScopeURI("service", "godmode", {"key with space": "val"}) + self.assertEqual( + "scope:service:godmode?key+with+space=val", scope_uri.to_payload() + ) diff --git a/tests/unit/jwt/test_client_validation.py b/tests/unit/jwt/test_client_validation.py new file mode 100644 index 0000000000..56d70d8152 --- /dev/null +++ b/tests/unit/jwt/test_client_validation.py @@ -0,0 +1,321 @@ +import time +import unittest + +from cryptography.hazmat.backends import default_backend +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.hazmat.primitives.serialization import ( + Encoding, + PublicFormat, + PrivateFormat, + NoEncryption, +) + +from twilio.http.validation_client import ValidationPayload +from twilio.jwt.validation import ClientValidationJwt + + +class ClientValidationJwtTest(unittest.TestCase): + def test_generate_payload_basic(self): + vp = ValidationPayload( + method="GET", + path="https://api.twilio.com/", + query_string="q1=v1", + signed_headers=["headerb", "headera"], + all_headers={"head": "toe", "headera": "vala", "headerb": "valb"}, + body="me=letop&you=leworst", + ) + + expected_payload = "\n".join( + [ + "GET", + "https://api.twilio.com/", + "q1=v1", + "headera:vala", + "headerb:valb", + "", + "headera;headerb", + "{}".format(ClientValidationJwt._hash("me=letop&you=leworst")), + ] + ) + expected_payload = ClientValidationJwt._hash(expected_payload) + + jwt = ClientValidationJwt("AC123", "SK123", "CR123", "secret", vp) + + actual_payload = jwt._generate_payload() + self.assertEqual("headera;headerb", actual_payload["hrh"]) + self.assertEqual(expected_payload, actual_payload["rqh"]) + + def test_generate_payload_complex(self): + vp = ValidationPayload( + method="GET", + path="https://api.twilio.com/", + query_string="q1=v1&q2=v2&a=b", + signed_headers=["headerb", "headera"], + all_headers={"head": "toe", "Headerb": "valb", "yeezy": "weezy"}, + body="me=letop&you=leworst", + ) + + expected_payload = "\n".join( + [ + "GET", + "https://api.twilio.com/", + "a=b&q1=v1&q2=v2", + "headerb:valb", + "", + "headera;headerb", + "{}".format(ClientValidationJwt._hash("me=letop&you=leworst")), + ] + ) + expected_payload = ClientValidationJwt._hash(expected_payload) + + jwt = ClientValidationJwt("AC123", "SK123", "CR123", "secret", vp) + + actual_payload = jwt._generate_payload() + self.assertEqual("headera;headerb", actual_payload["hrh"]) + self.assertEqual(expected_payload, actual_payload["rqh"]) + + def test_generate_payload_no_query_string(self): + vp = ValidationPayload( + method="GET", + path="https://api.twilio.com/", + query_string="", + signed_headers=["headerb", "headera"], + all_headers={"head": "toe", "Headerb": "valb", "yeezy": "weezy"}, + body="me=letop&you=leworst", + ) + + expected_payload = "\n".join( + [ + "GET", + "https://api.twilio.com/", + "", + "headerb:valb", + "", + "headera;headerb", + "{}".format(ClientValidationJwt._hash("me=letop&you=leworst")), + ] + ) + expected_payload = ClientValidationJwt._hash(expected_payload) + + jwt = ClientValidationJwt("AC123", "SK123", "CR123", "secret", vp) + + actual_payload = jwt._generate_payload() + self.assertEqual("headera;headerb", actual_payload["hrh"]) + self.assertEqual(expected_payload, actual_payload["rqh"]) + + def test_generate_payload_no_req_body(self): + vp = ValidationPayload( + method="GET", + path="https://api.twilio.com/", + query_string="q1=v1", + signed_headers=["headerb", "headera"], + all_headers={"head": "toe", "headera": "vala", "headerb": "valb"}, + body="", + ) + + expected_payload = "\n".join( + [ + "GET", + "https://api.twilio.com/", + "q1=v1", + "headera:vala", + "headerb:valb", + "", + "headera;headerb", + "", + ] + ) + expected_payload = ClientValidationJwt._hash(expected_payload) + + jwt = ClientValidationJwt("AC123", "SK123", "CR123", "secret", vp) + + actual_payload = jwt._generate_payload() + self.assertEqual("headera;headerb", actual_payload["hrh"]) + self.assertEqual(expected_payload, actual_payload["rqh"]) + + def test_generate_payload_header_keys_lowercased(self): + vp = ValidationPayload( + method="GET", + path="https://api.twilio.com/", + query_string="q1=v1", + signed_headers=["headerb", "headera"], + all_headers={"head": "toe", "Headera": "vala", "Headerb": "valb"}, + body="me=letop&you=leworst", + ) + + expected_payload = "\n".join( + [ + "GET", + "https://api.twilio.com/", + "q1=v1", + "headera:vala", + "headerb:valb", + "", + "headera;headerb", + "{}".format(ClientValidationJwt._hash("me=letop&you=leworst")), + ] + ) + expected_payload = ClientValidationJwt._hash(expected_payload) + + jwt = ClientValidationJwt("AC123", "SK123", "CR123", "secret", vp) + + actual_payload = jwt._generate_payload() + self.assertEqual("headera;headerb", actual_payload["hrh"]) + self.assertEqual(expected_payload, actual_payload["rqh"]) + + def test_generate_payload_no_headers(self): + vp = ValidationPayload( + method="GET", + path="https://api.twilio.com/", + query_string="q1=v1", + signed_headers=["headerb", "headera"], + all_headers={}, + body="me=letop&you=leworst", + ) + + expected_payload = "\n".join( + [ + "GET", + "https://api.twilio.com/", + "q1=v1", + "", + "headera;headerb", + "{}".format(ClientValidationJwt._hash("me=letop&you=leworst")), + ] + ) + expected_payload = ClientValidationJwt._hash(expected_payload) + + jwt = ClientValidationJwt("AC123", "SK123", "CR123", "secret", vp) + + actual_payload = jwt._generate_payload() + self.assertEqual("headera;headerb", actual_payload["hrh"]) + self.assertEqual(expected_payload, actual_payload["rqh"]) + + def test_generate_payload_schema_correct_1(self): + """Test against a known good rqh payload hash""" + vp = ValidationPayload( + method="GET", + path="/Messages", + query_string="PageSize=5&Limit=10", + signed_headers=["authorization", "host"], + all_headers={"authorization": "foobar", "host": "api.twilio.com"}, + body="foobar", + ) + + expected_hash = ( + "4dc9b67bed579647914587b0e22a1c65c1641d8674797cd82de65e766cce5f80" + ) + + jwt = ClientValidationJwt("AC123", "SK123", "CR123", "secret", vp) + + actual_payload = jwt._generate_payload() + self.assertEqual("authorization;host", actual_payload["hrh"]) + self.assertEqual(expected_hash, actual_payload["rqh"]) + + def test_generate_payload_schema_correct_2(self): + """Test against a known good rqh payload hash""" + vp = ValidationPayload( + method="POST", + path="/Messages", + query_string="", + signed_headers=["authorization", "host"], + all_headers={"authorization": "foobar", "host": "api.twilio.com"}, + body="testbody", + ) + + expected_hash = ( + "bd792c967c20d546c738b94068f5f72758a10d26c12979677501e1eefe58c65a" + ) + + jwt = ClientValidationJwt("AC123", "SK123", "CR123", "secret", vp) + + actual_payload = jwt._generate_payload() + self.assertEqual("authorization;host", actual_payload["hrh"]) + self.assertEqual(expected_hash, actual_payload["rqh"]) + + def test_jwt_payload(self): + vp = ValidationPayload( + method="GET", + path="/Messages", + query_string="PageSize=5&Limit=10", + signed_headers=["authorization", "host"], + all_headers={"authorization": "foobar", "host": "api.twilio.com"}, + body="foobar", + ) + expected_hash = ( + "4dc9b67bed579647914587b0e22a1c65c1641d8674797cd82de65e766cce5f80" + ) + + jwt = ClientValidationJwt("AC123", "SK123", "CR123", "secret", vp) + + self.assertEqual( + jwt.payload, + { + **jwt.payload, + **{ + "hrh": "authorization;host", + "rqh": expected_hash, + "iss": "SK123", + "sub": "AC123", + }, + }, + ) + self.assertGreaterEqual( + jwt.payload["exp"], time.time(), "JWT exp is before now" + ) + self.assertLessEqual( + jwt.payload["exp"], time.time() + 301, "JWT exp is after now + 5mins" + ) + self.assertDictEqual( + {"alg": "RS256", "typ": "JWT", "cty": "twilio-pkrv;v=1", "kid": "CR123"}, + jwt.headers, + ) + + def test_jwt_signing(self): + vp = ValidationPayload( + method="GET", + path="/Messages", + query_string="PageSize=5&Limit=10", + signed_headers=["authorization", "host"], + all_headers={"authorization": "foobar", "host": "api.twilio.com"}, + body="foobar", + ) + expected_hash = ( + "4dc9b67bed579647914587b0e22a1c65c1641d8674797cd82de65e766cce5f80" + ) + + private_key = rsa.generate_private_key( + public_exponent=65537, key_size=2048, backend=default_backend() + ) + public_key = private_key.public_key().public_bytes( + Encoding.PEM, PublicFormat.PKCS1 + ) + private_key = private_key.private_bytes( + Encoding.PEM, PrivateFormat.PKCS8, NoEncryption() + ) + + jwt = ClientValidationJwt("AC123", "SK123", "CR123", private_key, vp) + decoded = ClientValidationJwt.from_jwt(jwt.to_jwt(), public_key) + + self.assertEqual( + decoded.payload, + { + **decoded.payload, + **{ + "hrh": "authorization;host", + "rqh": expected_hash, + "iss": "SK123", + "sub": "AC123", + }, + }, + ) + self.assertGreaterEqual( + decoded.payload["exp"], time.time(), "JWT exp is before now" + ) + self.assertLessEqual( + decoded.payload["exp"], time.time() + 501, "JWT exp is after now + 5m" + ) + self.assertDictEqual( + {"alg": "RS256", "typ": "JWT", "cty": "twilio-pkrv;v=1", "kid": "CR123"}, + decoded.headers, + ) diff --git a/tests/unit/jwt/test_jwt.py b/tests/unit/jwt/test_jwt.py new file mode 100644 index 0000000000..2f5aba62d7 --- /dev/null +++ b/tests/unit/jwt/test_jwt.py @@ -0,0 +1,302 @@ +import time as real_time +import unittest + +import jwt as jwt_lib +from mock import patch + +from twilio.jwt import Jwt, JwtDecodeError + + +class DummyJwt(Jwt): + """Jwt implementation that allows setting arbitrary payload and headers for testing.""" + + ALGORITHM = "HS256" + + def __init__( + self, + secret_key, + issuer, + subject=None, + algorithm=None, + nbf=Jwt.GENERATE, + ttl=3600, + valid_until=None, + headers=None, + payload=None, + ): + super(DummyJwt, self).__init__( + secret_key=secret_key, + issuer=issuer, + subject=subject, + algorithm=algorithm or self.ALGORITHM, + nbf=nbf, + ttl=ttl, + valid_until=valid_until, + ) + self._payload = payload or {} + self._headers = headers or {} + + def _generate_payload(self): + return self._payload + + def _generate_headers(self): + return self._headers + + +class JwtTest(unittest.TestCase): + def assertIn(self, foo, bar, msg=None): + """backport for 2.6""" + assert foo in bar, msg or "%s not found in %s" % (foo, bar) + + def now(self): + return int(real_time.time()) + + def assertJwtsEqual(self, jwt, key, expected_payload=None, expected_headers=None): + expected_headers = expected_headers or {} + expected_payload = expected_payload or {} + + decoded_payload = jwt_lib.decode( + jwt, key, algorithms=["HS256"], options={"verify_signature": False} + ) + decoded_headers = jwt_lib.get_unverified_header(jwt) + + self.assertEqual(expected_headers, decoded_headers) + self.assertEqual(expected_payload, decoded_payload) + + @patch("time.time") + def test_basic_encode(self, time_mock): + time_mock.return_value = 0.0 + + jwt = DummyJwt("secret_key", "issuer", headers={}, payload={}) + + self.assertJwtsEqual( + jwt.to_jwt(), + "secret_key", + expected_headers={"typ": "JWT", "alg": "HS256"}, + expected_payload={"iss": "issuer", "exp": 3600, "nbf": 0}, + ) + + @patch("time.time") + def test_encode_with_subject(self, time_mock): + time_mock.return_value = 0.0 + + jwt = DummyJwt( + "secret_key", "issuer", subject="subject", headers={}, payload={} + ) + + self.assertJwtsEqual( + jwt.to_jwt(), + "secret_key", + expected_headers={"typ": "JWT", "alg": "HS256"}, + expected_payload={"iss": "issuer", "exp": 3600, "nbf": 0, "sub": "subject"}, + ) + + @patch("time.time") + def test_encode_without_nbf(self, time_mock): + time_mock.return_value = 0.0 + + jwt = DummyJwt( + "secret_key", "issuer", subject="subject", headers={}, payload={}, nbf=None + ) + + self.assertJwtsEqual( + jwt.to_jwt(), + "secret_key", + expected_headers={"typ": "JWT", "alg": "HS256"}, + expected_payload={"iss": "issuer", "exp": 3600, "sub": "subject"}, + ) + + @patch("time.time") + def test_encode_custom_ttl(self, time_mock): + time_mock.return_value = 0.0 + + jwt = DummyJwt("secret_key", "issuer", ttl=10, headers={}, payload={}) + + self.assertJwtsEqual( + jwt.to_jwt(), + "secret_key", + expected_headers={"typ": "JWT", "alg": "HS256"}, + expected_payload={"iss": "issuer", "exp": 10, "nbf": 0}, + ) + + @patch("time.time") + def test_encode_ttl_added_to_current_time(self, time_mock): + time_mock.return_value = 50.0 + + jwt = DummyJwt("secret_key", "issuer", ttl=10, headers={}, payload={}) + + self.assertJwtsEqual( + jwt.to_jwt(), + "secret_key", + expected_headers={"typ": "JWT", "alg": "HS256"}, + expected_payload={"iss": "issuer", "exp": 60, "nbf": 50}, + ) + + @patch("time.time") + def test_encode_override_ttl(self, time_mock): + time_mock.return_value = 0.0 + + jwt = DummyJwt("secret_key", "issuer", ttl=10, headers={}, payload={}) + + self.assertJwtsEqual( + jwt.to_jwt(ttl=20), + "secret_key", + expected_headers={"typ": "JWT", "alg": "HS256"}, + expected_payload={"iss": "issuer", "exp": 20, "nbf": 0}, + ) + + @patch("time.time") + def test_encode_valid_until_overrides_ttl(self, time_mock): + time_mock.return_value = 0.0 + + jwt = DummyJwt( + "secret_key", "issuer", ttl=10, valid_until=70, headers={}, payload={} + ) + + self.assertJwtsEqual( + jwt.to_jwt(), + "secret_key", + expected_headers={"typ": "JWT", "alg": "HS256"}, + expected_payload={"iss": "issuer", "exp": 70, "nbf": 0}, + ) + + @patch("time.time") + def test_encode_custom_nbf(self, time_mock): + time_mock.return_value = 0.0 + + jwt = DummyJwt("secret_key", "issuer", ttl=10, nbf=5, headers={}, payload={}) + + self.assertJwtsEqual( + jwt.to_jwt(), + "secret_key", + expected_headers={"typ": "JWT", "alg": "HS256"}, + expected_payload={"iss": "issuer", "exp": 10, "nbf": 5}, + ) + + @patch("time.time") + def test_encode_with_headers(self, time_mock): + time_mock.return_value = 0.0 + + jwt = DummyJwt("secret_key", "issuer", headers={"sooper": "secret"}, payload={}) + + self.assertJwtsEqual( + jwt.to_jwt(), + "secret_key", + expected_headers={"typ": "JWT", "alg": "HS256", "sooper": "secret"}, + expected_payload={"iss": "issuer", "exp": 3600, "nbf": 0}, + ) + + @patch("time.time") + def test_encode_with_payload(self, time_mock): + time_mock.return_value = 0.0 + + jwt = DummyJwt("secret_key", "issuer", payload={"root": "true"}) + + self.assertJwtsEqual( + jwt.to_jwt(), + "secret_key", + expected_headers={"typ": "JWT", "alg": "HS256"}, + expected_payload={"iss": "issuer", "exp": 3600, "nbf": 0, "root": "true"}, + ) + + @patch("time.time") + def test_encode_with_payload_and_headers(self, time_mock): + time_mock.return_value = 0.0 + + jwt = DummyJwt( + "secret_key", "issuer", headers={"yes": "oui"}, payload={"pay": "me"} + ) + + self.assertJwtsEqual( + jwt.to_jwt(), + "secret_key", + expected_headers={"typ": "JWT", "alg": "HS256", "yes": "oui"}, + expected_payload={"iss": "issuer", "exp": 3600, "nbf": 0, "pay": "me"}, + ) + + def test_encode_no_key_fails(self): + jwt = DummyJwt(None, "issuer") + self.assertRaises(ValueError, jwt.to_jwt) + + def test_encode_decode(self): + test_start = self.now() + + jwt = DummyJwt("secret_key", "issuer", subject="hey", payload={"sick": "sick"}) + decoded_jwt = Jwt.from_jwt(jwt.to_jwt(), "secret_key") + + self.assertGreaterEqual(decoded_jwt.valid_until, self.now() + 3600) + self.assertGreaterEqual(decoded_jwt.nbf, test_start) + self.assertEqual(decoded_jwt.issuer, "issuer") + self.assertEqual(decoded_jwt.secret_key, "secret_key") + self.assertEqual(decoded_jwt.algorithm, "HS256") + self.assertEqual(decoded_jwt.subject, "hey") + + self.assertEqual(decoded_jwt.headers, {"typ": "JWT", "alg": "HS256"}) + self.assertEqual( + decoded_jwt.payload, + { + **decoded_jwt.payload, + **{ + "iss": "issuer", + "sub": "hey", + "sick": "sick", + }, + }, + ) + + def test_encode_decode_mismatched_algorithms(self): + jwt = DummyJwt( + "secret_key", + "issuer", + algorithm="HS512", + subject="hey", + payload={"sick": "sick"}, + ) + self.assertRaises(JwtDecodeError, Jwt.from_jwt, jwt.to_jwt()) + + def test_decode_bad_secret(self): + jwt = DummyJwt("secret_key", "issuer") + self.assertRaises(JwtDecodeError, Jwt.from_jwt, jwt.to_jwt(), "letmeinplz") + + def test_decode_modified_jwt_fails(self): + jwt = DummyJwt("secret_key", "issuer") + example_jwt = jwt.to_jwt() + example_jwt = "ABC" + example_jwt[3:] + + self.assertRaises(JwtDecodeError, Jwt.from_jwt, example_jwt, "secret_key") + + def test_decode_validates_expiration(self): + expired_jwt = DummyJwt("secret_key", "issuer", valid_until=self.now()) + real_time.sleep(1) + self.assertRaises( + JwtDecodeError, Jwt.from_jwt, expired_jwt.to_jwt(), "secret_key" + ) + + def test_decode_validates_nbf(self): + expired_jwt = DummyJwt( + "secret_key", "issuer", nbf=self.now() + 3600 + ) # valid 1hr from now + self.assertRaises( + JwtDecodeError, Jwt.from_jwt, expired_jwt.to_jwt(), "secret_key" + ) + + def test_decodes_valid_jwt(self): + expiry_time = self.now() + 1000 + example_jwt = jwt_lib.encode( + {"hello": "world", "iss": "me", "sub": "being awesome", "exp": expiry_time}, + "secret", + ) + + decoded_jwt = Jwt.from_jwt(example_jwt, "secret") + self.assertEqual(decoded_jwt.issuer, "me") + self.assertEqual(decoded_jwt.subject, "being awesome") + self.assertEqual(decoded_jwt.valid_until, expiry_time) + self.assertIn("hello", decoded_jwt.payload) + self.assertEqual(decoded_jwt.payload["hello"], "world") + + def test_decode_allows_skip_verification(self): + jwt = DummyJwt("secret", "issuer", payload={"get": "rekt"}) + decoded_jwt = Jwt.from_jwt(jwt.to_jwt(), key=None) + self.assertEqual(decoded_jwt.issuer, "issuer") + self.assertEqual(decoded_jwt.payload["get"], "rekt") + self.assertIsNone(decoded_jwt.secret_key) diff --git a/tests/unit/jwt/test_task_router.py b/tests/unit/jwt/test_task_router.py new file mode 100644 index 0000000000..f2333ef327 --- /dev/null +++ b/tests/unit/jwt/test_task_router.py @@ -0,0 +1,516 @@ +import unittest + +import time + +from twilio.jwt.taskrouter.capabilities import ( + WorkerCapabilityToken, + TaskQueueCapabilityToken, + WorkspaceCapabilityToken, +) + + +class TaskQueueCapabilityTokenTest(unittest.TestCase): + def setUp(self): + self.account_sid = "AC123" + self.auth_token = "foobar" + self.workspace_sid = "WS456" + self.taskqueue_sid = "WQ789" + self.capability = TaskQueueCapabilityToken( + self.account_sid, self.auth_token, self.workspace_sid, self.taskqueue_sid + ) + + def test_generate_token(self): + token = self.capability.to_jwt() + self.assertNotEqual(None, token) + + decoded = TaskQueueCapabilityToken.from_jwt(token, self.auth_token) + self.assertNotEqual(None, decoded) + + self.assertEqual(decoded.payload["iss"], self.account_sid) + self.assertEqual(decoded.payload["account_sid"], self.account_sid) + self.assertEqual(decoded.payload["workspace_sid"], self.workspace_sid) + self.assertEqual(decoded.payload["taskqueue_sid"], self.taskqueue_sid) + self.assertEqual(decoded.payload["channel"], self.taskqueue_sid) + self.assertEqual(decoded.payload["version"], "v1") + self.assertEqual(decoded.payload["friendly_name"], self.taskqueue_sid) + + def test_generate_token_with_default_ttl(self): + token = self.capability.to_jwt() + self.assertNotEqual(None, token) + + decoded = TaskQueueCapabilityToken.from_jwt(token, self.auth_token) + self.assertNotEqual(None, decoded) + + self.assertAlmostEqual(int(time.time()) + 3600, decoded.valid_until, delta=5) + + def test_generate_token_with_custom_ttl(self): + ttl = 10000 + + token = self.capability.to_jwt(ttl=ttl) + self.assertNotEqual(None, token) + + decoded = TaskQueueCapabilityToken.from_jwt(token, self.auth_token) + self.assertNotEqual(None, decoded) + + self.assertAlmostEqual(int(time.time()) + 10000, decoded.valid_until, delta=5) + + def test_default(self): + token = self.capability.to_jwt() + self.assertNotEqual(None, token) + + decoded = TaskQueueCapabilityToken.from_jwt(token, self.auth_token) + self.assertNotEqual(None, decoded) + + policies = decoded.payload["policies"] + self.assertEqual(len(policies), 3) + + # websocket GET + get_policy = policies[0] + self.assertEqual( + "https://event-bridge.twilio.com/v1/wschannels/AC123/WQ789", + get_policy["url"], + ) + self.assertEqual("GET", get_policy["method"]) + self.assertTrue(get_policy["allow"]) + self.assertEqual({}, get_policy["query_filter"]) + self.assertEqual({}, get_policy["post_filter"]) + + # websocket POST + post_policy = policies[1] + self.assertEqual( + "https://event-bridge.twilio.com/v1/wschannels/AC123/WQ789", + post_policy["url"], + ) + self.assertEqual("POST", post_policy["method"]) + self.assertTrue(post_policy["allow"]) + self.assertEqual({}, post_policy["query_filter"]) + self.assertEqual({}, post_policy["post_filter"]) + + # fetch GET + fetch_policy = policies[2] + self.assertEqual( + "https://taskrouter.twilio.com/v1/Workspaces/WS456/TaskQueues/WQ789", + fetch_policy["url"], + ) + self.assertEqual("GET", fetch_policy["method"]) + self.assertTrue(fetch_policy["allow"]) + self.assertEqual({}, fetch_policy["query_filter"]) + self.assertEqual({}, fetch_policy["post_filter"]) + + def test_allow_fetch_subresources(self): + self.capability.allow_fetch_subresources() + + token = self.capability.to_jwt() + self.assertNotEqual(None, token) + + decoded = TaskQueueCapabilityToken.from_jwt(token, self.auth_token) + self.assertNotEqual(None, decoded) + + policies = decoded.payload["policies"] + self.assertEqual(len(policies), 4) + + # confirm the additional policy generated with allow_fetch_subresources() + policy = policies[3] + + self.assertEqual( + policy["url"], + "https://taskrouter.twilio.com/v1/Workspaces/WS456/TaskQueues/WQ789/**", + ) + self.assertEqual(policy["method"], "GET") + self.assertTrue(policy["allow"]) + self.assertEqual({}, policy["query_filter"]) + self.assertEqual({}, policy["post_filter"]) + + def test_allow_updates_subresources(self): + self.capability.allow_update_subresources() + + token = self.capability.to_jwt() + self.assertNotEqual(None, token) + + decoded = TaskQueueCapabilityToken.from_jwt(token, self.auth_token) + self.assertNotEqual(None, decoded) + + policies = decoded.payload["policies"] + self.assertEqual(len(policies), 4) + + # confirm the additional policy generated with allow_updates_subresources() + policy = policies[3] + + self.assertEqual( + policy["url"], + "https://taskrouter.twilio.com/v1/Workspaces/WS456/TaskQueues/WQ789/**", + ) + self.assertEqual(policy["method"], "POST") + self.assertTrue(policy["allow"]) + self.assertEqual({}, policy["query_filter"]) + self.assertEqual({}, policy["post_filter"]) + + def test_pass_policy_in_constructor(self): + self.capability = TaskQueueCapabilityToken( + self.account_sid, + self.auth_token, + self.workspace_sid, + self.taskqueue_sid, + allow_update_subresources=True, + ) + + token = self.capability.to_jwt() + self.assertNotEqual(None, token) + + decoded = TaskQueueCapabilityToken.from_jwt(token, self.auth_token) + self.assertNotEqual(None, decoded) + + policies = decoded.payload["policies"] + self.assertEqual(len(policies), 4) + + # confirm the additional policy generated with allow_updates_subresources() + policy = policies[3] + + self.assertEqual( + policy["url"], + "https://taskrouter.twilio.com/v1/Workspaces/WS456/TaskQueues/WQ789/**", + ) + self.assertEqual(policy["method"], "POST") + self.assertTrue(policy["allow"]) + self.assertEqual({}, policy["query_filter"]) + self.assertEqual({}, policy["post_filter"]) + + +class WorkerCapabilityTokenTest(unittest.TestCase): + def check_policy(self, method, url, policy): + self.assertEqual(url, policy["url"]) + self.assertEqual(method, policy["method"]) + self.assertTrue(policy["allow"]) + self.assertEqual({}, policy["query_filter"]) + self.assertEqual({}, policy["post_filter"]) + + def check_decoded( + self, decoded, account_sid, workspace_sid, channel_id, channel_sid=None + ): + self.assertEqual(decoded["iss"], account_sid) + self.assertEqual(decoded["account_sid"], account_sid) + self.assertEqual(decoded["workspace_sid"], workspace_sid) + self.assertEqual(decoded["channel"], channel_id) + self.assertEqual(decoded["version"], "v1") + self.assertEqual(decoded["friendly_name"], channel_id) + + if "worker_sid" in decoded.keys(): + self.assertEqual(decoded["worker_sid"], channel_sid) + if "taskqueue_sid" in decoded.keys(): + self.assertEqual(decoded["taskqueue_sid"], channel_sid) + + def setUp(self): + self.account_sid = "AC123" + self.auth_token = "foobar" + self.workspace_sid = "WS456" + self.worker_sid = "WK789" + self.capability = WorkerCapabilityToken( + self.account_sid, self.auth_token, self.workspace_sid, self.worker_sid + ) + + def test_generate_token(self): + token = self.capability.to_jwt() + self.assertNotEqual(None, token) + + decoded = WorkerCapabilityToken.from_jwt(token, self.auth_token) + self.assertNotEqual(None, decoded) + + self.check_decoded( + decoded.payload, + self.account_sid, + self.workspace_sid, + self.worker_sid, + self.worker_sid, + ) + + def test_generate_token_with_default_ttl(self): + token = self.capability.to_jwt() + self.assertNotEqual(None, token) + + decoded = WorkerCapabilityToken.from_jwt(token, self.auth_token) + self.assertNotEqual(None, decoded) + self.assertAlmostEqual(int(time.time()) + 3600, decoded.valid_until, delta=5) + + def test_generate_token_with_custom_ttl(self): + ttl = 10000 + + token = self.capability.to_jwt(ttl=ttl) + self.assertNotEqual(None, token) + + decoded = WorkerCapabilityToken.from_jwt(token, self.auth_token) + self.assertNotEqual(None, decoded) + self.assertAlmostEqual(int(time.time()) + 10000, decoded.valid_until, delta=5) + + def test_defaults(self): + token = self.capability.to_jwt() + self.assertNotEqual(None, token) + + decoded = WorkerCapabilityToken.decode(token, self.auth_token) + self.assertNotEqual(None, decoded) + + websocket_url = "https://event-bridge.twilio.com/v1/wschannels/{0}/{1}".format( + self.account_sid, self.worker_sid + ) + + # expect 6 policies + policies = decoded.payload["policies"] + self.assertEqual(len(policies), 6) + + # should expect 6 policies + for method, url, policy in [ + ("GET", websocket_url, policies[0]), + ("POST", websocket_url, policies[1]), + ( + "GET", + "https://taskrouter.twilio.com/v1/Workspaces/WS456/Workers/WK789", + policies[2], + ), + ( + "GET", + "https://taskrouter.twilio.com/v1/Workspaces/WS456/Activities", + policies[3], + ), + ( + "GET", + "https://taskrouter.twilio.com/v1/Workspaces/WS456/Tasks/**", + policies[4], + ), + ( + "GET", + "https://taskrouter.twilio.com/v1/Workspaces/WS456/Workers/WK789/Reservations/**", + policies[5], + ), + ]: + yield self.check_policy, method, url, policy + + def test_allow_activity_updates(self): + # allow activity updates to the worker + self.capability.allow_update_activities() + + token = self.capability.to_jwt() + self.assertNotEqual(None, token) + + decoded = WorkerCapabilityToken.from_jwt(token, self.auth_token) + self.assertNotEqual(None, decoded) + + policies = decoded.payload["policies"] + self.assertEqual(len(policies), 7) + policy = policies[6] + + url = "https://taskrouter.twilio.com/v1/Workspaces/{0}/Workers/{1}".format( + self.workspace_sid, self.worker_sid + ) + + self.assertEqual(url, policy["url"]) + self.assertEqual("POST", policy["method"]) + self.assertTrue(policy["allow"]) + self.assertNotEqual(None, policy["post_filter"]) + self.assertEqual({}, policy["query_filter"]) + self.assertTrue(policy["post_filter"]["ActivitySid"]) + + def test_allow_reservation_updates(self): + # allow reservation updates + self.capability.allow_update_reservations() + + token = self.capability.to_jwt() + self.assertNotEqual(None, token) + + decoded = WorkerCapabilityToken.from_jwt(token, self.auth_token) + self.assertNotEqual(None, decoded) + + policies = decoded.payload["policies"] + self.assertEqual(len(policies), 8) + + taskPolicy = policies[6] + tasksUrl = "https://taskrouter.twilio.com/v1/Workspaces/{0}/Tasks/**".format( + self.workspace_sid + ) + self.check_policy("POST", tasksUrl, taskPolicy) + + workerReservationsPolicy = policies[7] + reservationsUrl = "https://taskrouter.twilio.com/v1/Workspaces/{0}/Workers/{1}/Reservations/**".format( + self.workspace_sid, self.worker_sid + ) + self.check_policy("POST", reservationsUrl, workerReservationsPolicy) + + def test_pass_policies_in_constructor(self): + # allow reservation updates + self.capability = WorkerCapabilityToken( + self.account_sid, + self.auth_token, + self.workspace_sid, + self.worker_sid, + allow_update_reservations=True, + ) + + token = self.capability.to_jwt() + self.assertNotEqual(None, token) + + decoded = WorkerCapabilityToken.from_jwt(token, self.auth_token) + self.assertNotEqual(None, decoded) + + policies = decoded.payload["policies"] + self.assertEqual(len(policies), 8) + + taskPolicy = policies[6] + tasksUrl = "https://taskrouter.twilio.com/v1/Workspaces/{0}/Tasks/**".format( + self.workspace_sid + ) + self.check_policy("POST", tasksUrl, taskPolicy) + + workerReservationsPolicy = policies[7] + reservationsUrl = "https://taskrouter.twilio.com/v1/Workspaces/{0}/Workers/{1}/Reservations/**".format( + self.workspace_sid, self.worker_sid + ) + self.check_policy("POST", reservationsUrl, workerReservationsPolicy) + + +class WorkspaceCapabilityTokenTest(unittest.TestCase): + def check_policy(self, method, url, policy): + self.assertEqual(url, policy["url"]) + self.assertEqual(method, policy["method"]) + self.assertTrue(policy["allow"]) + self.assertEqual({}, policy["query_filter"]) + self.assertEqual({}, policy["post_filter"]) + + def check_decoded( + self, decoded, account_sid, workspace_sid, channel_id, channel_sid=None + ): + self.assertEqual(decoded["iss"], account_sid) + self.assertEqual(decoded["account_sid"], account_sid) + self.assertEqual(decoded["workspace_sid"], workspace_sid) + self.assertEqual(decoded["channel"], channel_id) + self.assertEqual(decoded["version"], "v1") + self.assertEqual(decoded["friendly_name"], channel_id) + + if "worker_sid" in decoded.keys(): + self.assertEqual(decoded["worker_sid"], channel_sid) + if "taskqueue_sid" in decoded.keys(): + self.assertEqual(decoded["taskqueue_sid"], channel_sid) + + def setUp(self): + self.account_sid = "AC123" + self.auth_token = "foobar" + self.workspace_sid = "WS456" + self.capability = WorkspaceCapabilityToken( + self.account_sid, self.auth_token, self.workspace_sid + ) + + def test_generate_token(self): + token = self.capability.to_jwt() + self.assertNotEqual(None, token) + + decoded = WorkspaceCapabilityToken.from_jwt(token, self.auth_token) + self.assertNotEqual(None, decoded) + + self.check_decoded( + decoded.payload, self.account_sid, self.workspace_sid, self.workspace_sid + ) + + def test_generate_token_with_default_ttl(self): + token = self.capability.to_jwt() + self.assertNotEqual(None, token) + + decoded = WorkspaceCapabilityToken.from_jwt(token, self.auth_token) + self.assertNotEqual(None, decoded) + + self.assertAlmostEqual(int(time.time()) + 3600, decoded.valid_until, delta=5) + + def test_generate_token_with_custom_ttl(self): + ttl = 10000 + + token = self.capability.to_jwt(ttl=ttl) + self.assertNotEqual(None, token) + + decoded = WorkspaceCapabilityToken.from_jwt(token, self.auth_token) + self.assertNotEqual(None, decoded) + + self.assertAlmostEqual(int(time.time()) + 10000, decoded.valid_until, delta=5) + + def test_default(self): + token = self.capability.to_jwt() + self.assertNotEqual(None, token) + + decoded = WorkspaceCapabilityToken.from_jwt(token, self.auth_token) + self.assertNotEqual(None, decoded) + + policies = decoded.payload["policies"] + self.assertEqual(len(policies), 3) + + for method, url, policy in [ + ( + "GET", + "https://event-bridge.twilio.com/v1/wschannels/AC123/WS456", + policies[0], + ), + ( + "POST", + "https://event-bridge.twilio.com/v1/wschannels/AC123/WS456", + policies[1], + ), + ("GET", "https://taskrouter.twilio.com/v1/Workspaces/WS456", policies[2]), + ]: + yield self.check_policy, method, url, policy + + def test_allow_fetch_subresources(self): + self.capability.allow_fetch_subresources() + + token = self.capability.to_jwt() + self.assertNotEqual(None, token) + + decoded = WorkspaceCapabilityToken.from_jwt(token, self.auth_token) + self.assertNotEqual(None, decoded) + + policies = decoded.payload["policies"] + self.assertEqual(len(policies), 4) + + # confirm the additional policy generated with allow_fetch_subresources() + policy = policies[3] + self.check_policy( + "GET", "https://taskrouter.twilio.com/v1/Workspaces/WS456/**", policy + ) + + def test_allow_updates_subresources(self): + self.capability.allow_update_subresources() + + token = self.capability.to_jwt() + self.assertNotEqual(None, token) + + decoded = WorkspaceCapabilityToken.from_jwt(token, self.auth_token) + self.assertNotEqual(None, decoded) + + policies = decoded.payload["policies"] + self.assertEqual(len(policies), 4) + + # confirm the additional policy generated with allow_update_subresources() + policy = policies[3] + self.check_policy( + "POST", "https://taskrouter.twilio.com/v1/Workspaces/WS456/**", policy + ) + + def test_pass_policy_in_constructor(self): + self.capability = WorkspaceCapabilityToken( + self.account_sid, + self.auth_token, + self.workspace_sid, + allow_update_subresources=True, + ) + + token = self.capability.to_jwt() + self.assertNotEqual(None, token) + + decoded = WorkspaceCapabilityToken.from_jwt(token, self.auth_token) + self.assertNotEqual(None, decoded) + + policies = decoded.payload["policies"] + self.assertEqual(len(policies), 4) + + # confirm the additional policy generated with allow_update_subresources() + policy = policies[3] + self.check_policy( + "POST", "https://taskrouter.twilio.com/v1/Workspaces/WS456/**", policy + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/rest/test_client.py b/tests/unit/rest/test_client.py new file mode 100644 index 0000000000..9623dc52ad --- /dev/null +++ b/tests/unit/rest/test_client.py @@ -0,0 +1,142 @@ +import unittest +import aiounittest + +from mock import AsyncMock, Mock +from twilio.http.response import Response +from twilio.rest import Client + + +class TestRegionEdgeClients(unittest.TestCase): + def setUp(self): + self.client = Client("username", "password") + + def test_set_client_edge_default_region(self): + self.client.edge = "edge" + self.assertEqual( + self.client.get_hostname("https://api.twilio.com"), + "https://api.edge.us1.twilio.com", + ) + + def test_set_client_region(self): + self.client.region = "region" + self.assertEqual( + self.client.get_hostname("https://api.twilio.com"), + "https://api.region.twilio.com", + ) + + def test_set_uri_region(self): + self.assertEqual( + self.client.get_hostname("https://api.region.twilio.com"), + "https://api.region.twilio.com", + ) + + def test_set_client_edge_region(self): + self.client.edge = "edge" + self.client.region = "region" + self.assertEqual( + self.client.get_hostname("https://api.twilio.com"), + "https://api.edge.region.twilio.com", + ) + + def test_set_client_edge_uri_region(self): + self.client.edge = "edge" + self.assertEqual( + self.client.get_hostname("https://api.region.twilio.com"), + "https://api.edge.region.twilio.com", + ) + + def test_set_client_region_uri_edge_region(self): + self.client.region = "region" + self.assertEqual( + self.client.get_hostname("https://api.edge.uriRegion.twilio.com"), + "https://api.edge.region.twilio.com", + ) + + def test_set_client_edge_uri_edge_region(self): + self.client.edge = "edge" + self.assertEqual( + self.client.get_hostname("https://api.uriEdge.region.twilio.com"), + "https://api.edge.region.twilio.com", + ) + + def test_set_uri_edge_region(self): + self.assertEqual( + self.client.get_hostname("https://api.edge.region.twilio.com"), + "https://api.edge.region.twilio.com", + ) + + def test_periods_in_query(self): + self.client.region = "region" + self.client.edge = "edge" + self.assertEqual( + self.client.get_hostname( + "https://api.twilio.com/path/to/something.json?foo=12.34" + ), + "https://api.edge.region.twilio.com/path/to/something.json?foo=12.34", + ) + + +class TestUserAgentClients(unittest.TestCase): + def setUp(self): + self.client = Client("username", "password") + + def tearDown(self): + self.client.http_client.session.close() + + def test_set_default_user_agent(self): + self.client.request("GET", "https://api.twilio.com/") + request_header = self.client.http_client._test_only_last_request.headers[ + "User-Agent" + ] + self.assertRegex( + request_header, + r"^twilio-python\/[0-9.]+(-rc\.[0-9]+)?\s\(\w+\s\w+\)\sPython\/[^\s]+$", + ) + + def test_set_user_agent_extensions(self): + expected_user_agent_extensions = ["twilio-run/2.0.0-test", "flex-plugin/3.4.0"] + self.client.user_agent_extensions = expected_user_agent_extensions + self.client.request("GET", "https://api.twilio.com/") + user_agent_headers = self.client.http_client._test_only_last_request.headers[ + "User-Agent" + ] + user_agent_extensions = user_agent_headers.split(" ")[ + -len(expected_user_agent_extensions) : + ] + self.assertEqual(user_agent_extensions, expected_user_agent_extensions) + + +class TestClientAsyncRequest(aiounittest.AsyncTestCase): + def setUp(self): + self.mock_async_http_client = AsyncMock() + self.mock_async_http_client.request.return_value = Response(200, "test") + self.mock_async_http_client.is_async = True + self.client = Client( + "username", "password", http_client=self.mock_async_http_client + ) + + async def test_raise_error_if_client_not_marked_async(self): + mock_http_client = Mock() + mock_http_client.request.return_value = Response(200, "doesnt matter") + mock_http_client.is_async = None + + client = Client("username", "password", http_client=mock_http_client) + with self.assertRaises(RuntimeError): + await client.request_async("doesnt matter", "doesnt matter") + + async def test_raise_error_if_client_is_not_async(self): + mock_http_client = Mock() + mock_http_client.request.return_value = Response(200, "doesnt matter") + mock_http_client.is_async = False + + client = Client("username", "password", http_client=mock_http_client) + with self.assertRaises(RuntimeError): + await client.request_async("doesnt matter", "doesnt matter") + + async def test_request_async_called_with_method_and_url(self): + await self.client.request_async("GET", "http://mock.twilio.com") + self.assertEqual(self.mock_async_http_client.request.call_args.args[0], "GET") + self.assertEqual( + self.mock_async_http_client.request.call_args.args[1], + "http://mock.twilio.com", + ) diff --git a/tests/unit/test_request_validator.py b/tests/unit/test_request_validator.py new file mode 100644 index 0000000000..2159d4c910 --- /dev/null +++ b/tests/unit/test_request_validator.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +import unittest + +from django.conf import settings +from django.http import QueryDict +from multidict import MultiDict + +from twilio.request_validator import RequestValidator + + +class ValidationTest(unittest.TestCase): + def setUp(self): + if not settings.configured: + settings.configure() + + token = "12345" + self.validator = RequestValidator(token) + + self.uri = "https://mycompany.com/myapp.php?foo=1&bar=2" + self.params = { + "CallSid": "CA1234567890ABCDE", + "Digits": "1234", + "From": "+14158675309", + "To": "+18005551212", + "Caller": "+14158675309", + } + self.expected = "RSOYDt4T1cUTdK1PDd93/VVr8B8=" + self.body = '{"property": "value", "boolean": true}' + self.bodyHash = ( + "0a1ff7634d9ab3b95db5c9a2dfe9416e41502b283a80c7cf19632632f96e6620" + ) + self.uriWithBody = self.uri + "&bodySHA256=" + self.bodyHash + self.duplicate_expected = "IK+Dwps556ElfBT0I3Rgjkr1wJU=" + + def test_compute_signature(self): + expected = self.expected + signature = self.validator.compute_signature(self.uri, self.params) + assert signature == expected + + def test_compute_hash_unicode(self): + expected = self.bodyHash + body_hash = self.validator.compute_hash(self.body) + + assert expected == body_hash + + def test_compute_signature_duplicate_multi_dict(self): + expected = self.duplicate_expected + params = MultiDict( + [ + ("Sid", "CA123"), + ("SidAccount", "AC123"), + ("Digits", "5678"), # Ensure keys are sorted. + ("Digits", "1234"), # Ensure values are sorted. + ("Digits", "1234"), # Ensure duplicates are removed. + ] + ) + signature = self.validator.compute_signature(self.uri, params) + assert signature == expected + + def test_compute_signature_duplicate_query_dict(self): + expected = self.duplicate_expected + params = QueryDict( + "Sid=CA123&SidAccount=AC123&Digits=5678&Digits=1234&Digits=1234", + encoding="utf-8", + ) + signature = self.validator.compute_signature(self.uri, params) + assert signature == expected + + def test_validation(self): + assert self.validator.validate(self.uri, self.params, self.expected) + + def test_validation_removes_port_on_https(self): + uri = self.uri.replace(".com", ".com:1234") + assert self.validator.validate(uri, self.params, self.expected) + + def test_validation_removes_port_on_http(self): + expected = "Zmvh+3yNM1Phv2jhDCwEM3q5ebU=" # hash of http uri with port 1234 + uri = self.uri.replace(".com", ".com:1234").replace("https", "http") + assert self.validator.validate(uri, self.params, expected) + + def test_validation_adds_port_on_https(self): + expected = "kvajT1Ptam85bY51eRf/AJRuM3w=" # hash of uri with port 443 + assert self.validator.validate(self.uri, self.params, expected) + + def test_validation_adds_port_on_http(self): + uri = self.uri.replace("https", "http") + expected = "0ZXoZLH/DfblKGATFgpif+LLRf4=" # hash of uri with port 80 + assert self.validator.validate(uri, self.params, expected) + + def test_validation_of_body_succeeds(self): + uri = self.uriWithBody + is_valid = self.validator.validate( + uri, self.body, "a9nBmqA0ju/hNViExpshrM61xv4=" + ) + assert is_valid diff --git a/tests/unit/twiml/__init__.py b/tests/unit/twiml/__init__.py new file mode 100644 index 0000000000..cb78511a51 --- /dev/null +++ b/tests/unit/twiml/__init__.py @@ -0,0 +1,60 @@ +import unittest + +from pytest import raises + +from twilio.twiml import format_language, lower_camel, TwiMLException, TwiML + + +class TwilioTest(unittest.TestCase): + def strip(self, xml): + return str(xml) + + def test_append_fail(self): + with raises(TwiMLException): + t = TwiML() + t.append(12345) + + def test_format_language_none(self): + language = None + self.assertEqual(language, format_language(language)) + + def test_format_language_valid(self): + language = "en-US" + self.assertEqual(language, format_language(language)) + + def test_format_language_coerced(self): + language = "EN_us" + self.assertEqual("en-US", format_language(language)) + + def test_format_language_fail(self): + with raises(TwiMLException): + format_language("this is invalid") + + def test_lower_camel_empty_string(self): + self.assertEqual("", lower_camel("")) + + def test_lower_camel_none(self): + self.assertEqual(None, lower_camel(None)) + + def test_lower_camel_single_word(self): + self.assertEqual("foo", lower_camel("foo")) + + def test_lower_camel_double_word(self): + self.assertEqual("fooBar", lower_camel("foo_bar")) + + def test_lower_camel_multi_word(self): + self.assertEqual("fooBarBaz", lower_camel("foo_bar_baz")) + + def test_lower_camel_multi_word_mixed_case(self): + self.assertEqual("fooBarBaz", lower_camel("foO_Bar_baz")) + + def test_lower_camel_camel_cased(self): + self.assertEqual("fooBar", lower_camel("fooBar")) + + def test_utf8_encoding(self): + t = TwiML() + t.value = "An utf-8 character: ñ" + self.assertEqual( + t.to_xml(), + '<?xml version="1.0" encoding="UTF-8"?><TwiML>An utf-8 character: ñ</TwiML>', + ) diff --git a/tests/unit/twiml/test_messaging_response.py b/tests/unit/twiml/test_messaging_response.py new file mode 100644 index 0000000000..286b5ba770 --- /dev/null +++ b/tests/unit/twiml/test_messaging_response.py @@ -0,0 +1,128 @@ +from tests.unit.twiml import TwilioTest +from twilio.twiml.messaging_response import MessagingResponse, Body, Media + + +class TestResponse(TwilioTest): + def test_empty_response(self): + r = MessagingResponse() + assert self.strip(r) == '<?xml version="1.0" encoding="UTF-8"?><Response />' + + def test_response(self): + r = MessagingResponse() + r.message("Hello") + r.redirect(url="example.com") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Message>Hello</Message><Redirect>example.com</Redirect></Response>' + ) + + def test_response_chain(self): + with MessagingResponse() as r: + r.message("Hello") + r.redirect(url="example.com") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Message>Hello</Message><Redirect>example.com</Redirect></Response>' + ) + + def test_nested_verbs(self): + with MessagingResponse() as r: + with r.message("Hello") as m: + m.media("example.com") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Message>Hello<Media>example.com</Media></Message></Response>' + ) + + def test_child_node(self): + with MessagingResponse() as r: + with r.add_child("message", tag="global") as mod: + mod.add_child("bold", "Hello") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><message tag="global"><bold>Hello</bold></message></Response>' + ) + + def test_mixed(self): + r = MessagingResponse() + + r.append("before") + r.add_child("Child").append("content") + r.append("after") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response>before<Child>content</Child>after</Response>' + ) + + +class TestMessage(TwilioTest): + def test_body(self): + r = MessagingResponse() + r.message("Hello") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Message>Hello</Message></Response>' + ) + + def test_nested_body(self): + b = Body("Hello World") + + r = MessagingResponse() + r.append(b) + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Body>Hello World</Body></Response>' + ) + + def test_nested_body_media(self): + b = Body("Hello World") + m = Media("hey.jpg") + + r = MessagingResponse() + r.append(b) + r.append(m) + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Body>Hello World</Body><Media>hey.jpg</Media></Response>' + ) + + +class TestRedirect(TwilioTest): + def test_redirect(self): + r = MessagingResponse() + r.redirect(url="example.com") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Redirect>example.com</Redirect></Response>' + ) + + +class TestText(TwilioTest): + def test_text(self): + r = MessagingResponse() + r.append("No tags!") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response>No tags!</Response>' + ) + + def text_mixed(self): + r = MessagingResponse() + r.append("before") + r.append(Body("Content")) + r.append("after") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response>before<Body>Content</Body>after</Response>' + ) diff --git a/tests/unit/twiml/test_voice_response.py b/tests/unit/twiml/test_voice_response.py new file mode 100644 index 0000000000..df10fc7d62 --- /dev/null +++ b/tests/unit/twiml/test_voice_response.py @@ -0,0 +1,629 @@ +# -*- coding: utf-8 -*- +from tests.unit.twiml import TwilioTest +from twilio.twiml.voice_response import VoiceResponse, Dial, Enqueue, Gather + + +class TestResponse(TwilioTest): + def test_empty_response(self): + r = VoiceResponse() + assert self.strip(r) == '<?xml version="1.0" encoding="UTF-8"?><Response />' + + def test_response(self): + r = VoiceResponse() + r.hangup() + r.leave() + r.sms("twilio sms", to="+11234567890", from_="+10987654321") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Hangup /><Leave />' + '<Sms from="+10987654321" to="+11234567890">twilio sms</Sms></Response>' + ) + + def test_response_chain(self): + with VoiceResponse() as r: + r.hangup() + r.leave() + r.sms("twilio sms", to="+11234567890", from_="+10987654321") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Hangup /><Leave />' + '<Sms from="+10987654321" to="+11234567890">twilio sms</Sms></Response>' + ) + + def test_nested_verbs(self): + with VoiceResponse() as r: + with r.gather() as g: + g.say("Hello", voice="man") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Gather><Say voice="man">Hello</Say></Gather></Response>' + ) + + +class TestSay(TwilioTest): + def test_empty_say(self): + """should be a say with no text""" + r = VoiceResponse() + r.say("") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Say /></Response>' + ) + + def test_say_hello_world(self): + """should say hello world""" + r = VoiceResponse() + r.say("Hello World") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Say>Hello World</Say></Response>' + ) + + def test_say_french(self): + """should say hello monkey""" + r = VoiceResponse() + r.say("n\xe9cessaire et d'autres") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Say>nécessaire et d\'autres</Say></Response>' + ) + + def test_say_loop(self): + """should say hello monkey and loop 3 times""" + r = VoiceResponse() + r.say("Hello Monkey", loop=3) + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Say loop="3">Hello Monkey</Say></Response>' + ) + + def test_say_loop_gb(self): + """should say have a woman say hello monkey and loop 3 times""" + r = VoiceResponse() + r.say("Hello Monkey", language="en-gb") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Say language="en-gb">Hello Monkey</Say></Response>' + ) + + def test_say_loop_woman(self): + """should say have a woman say hello monkey and loop 3 times""" + r = VoiceResponse() + r.say("Hello Monkey", loop=3, voice="woman") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Say loop="3" voice="woman">Hello Monkey</Say></Response>' + ) + + def test_say_all(self): + """convenience method: should say have a woman say hello monkey and loop 3 times and be in french""" + r = VoiceResponse() + r.say("Hello Monkey", loop=3, voice="man", language="fr") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Say language="fr" loop="3" voice="man">' + "Hello Monkey</Say></Response>" + ) + + +class TestPlay(TwilioTest): + def test_empty_play(self): + """should play hello monkey""" + r = VoiceResponse() + r.play() + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Play /></Response>' + ) + + def test_play_hello(self): + """should play hello monkey""" + r = VoiceResponse() + r.play(url="http://hellomonkey.mp3") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Play>http://hellomonkey.mp3</Play></Response>' + ) + + def test_play_hello_loop(self): + """should play hello monkey loop""" + r = VoiceResponse() + r.play(url="http://hellomonkey.mp3", loop=3) + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Play loop="3">http://hellomonkey.mp3</Play></Response>' + ) + + def test_play_digits(self): + """should play digits""" + r = VoiceResponse() + r.play(digits="w123") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Play digits="w123" /></Response>' + ) + + +class TestRecord(TwilioTest): + def test_record_empty(self): + """should record""" + r = VoiceResponse() + r.record() + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Record /></Response>' + ) + + def test_record_action_method(self): + """should record with an action and a get method""" + r = VoiceResponse() + r.record(action="example.com", method="GET") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Record action="example.com" method="GET" /></Response>' + ) + + def test_record_max_length_finish_timeout(self): + """should record with an maxLength, finishOnKey, and timeout""" + r = VoiceResponse() + r.record(timeout=4, finish_on_key="#", max_length=30) + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Record finishOnKey="#" maxLength="30" timeout="4" /></Response>' + ) + + def test_record_transcribe(self): + """should record with a transcribe and transcribeCallback""" + r = VoiceResponse() + r.record(transcribe_callback="example.com") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Record transcribeCallback="example.com" /></Response>' + ) + + +class TestRedirect(TwilioTest): + def test_redirect_empty(self): + r = VoiceResponse() + r.redirect("") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Redirect /></Response>' + ) + + def test_redirect_method(self): + r = VoiceResponse() + r.redirect("example.com", method="POST") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Redirect method="POST">example.com</Redirect></Response>' + ) + + def test_redirect_method_params(self): + r = VoiceResponse() + r.redirect("example.com?id=34&action=hey", method="POST") + + assert ( + self.strip(r) == '<?xml version="1.0" encoding="UTF-8"?><Response>' + '<Redirect method="POST">example.com?id=34&action=hey</Redirect></Response>' + ) + + +class TestHangup(TwilioTest): + def test_hangup(self): + """convenience: should Hangup to a url via POST""" + r = VoiceResponse() + r.hangup() + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Hangup /></Response>' + ) + + +class TestLeave(TwilioTest): + def test_leave(self): + """convenience: should Hangup to a url via POST""" + r = VoiceResponse() + r.leave() + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Leave /></Response>' + ) + + +class TestReject(TwilioTest): + def test_reject(self): + """should be a Reject with default reason""" + r = VoiceResponse() + r.reject() + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Reject /></Response>' + ) + + +class TestSms(TwilioTest): + def test_empty(self): + """Test empty sms verb""" + r = VoiceResponse() + r.sms("") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Sms /></Response>' + ) + + def test_body(self): + """Test hello world""" + r = VoiceResponse() + r.sms("Hello, World") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Sms>Hello, World</Sms></Response>' + ) + + def test_to_from_action(self): + """Test the to, from, and status callback""" + r = VoiceResponse() + r.sms( + "Hello, World", + to=1231231234, + from_=3453453456, + status_callback="example.com?id=34&action=hey", + ) + + assert ( + self.strip(r) == '<?xml version="1.0" encoding="UTF-8"?><Response>' + '<Sms from="3453453456" statusCallback="example.com?id=34&action=hey" to="1231231234">' + "Hello, World</Sms></Response>" + ) + + def test_action_method(self): + """Test the action and method parameters on Sms""" + r = VoiceResponse() + r.sms("Hello", method="POST", action="example.com?id=34&action=hey") + + assert ( + self.strip(r) == '<?xml version="1.0" encoding="UTF-8"?><Response>' + '<Sms action="example.com?id=34&action=hey" method="POST">Hello</Sms></Response>' + ) + + +class TestConference(TwilioTest): + def test_conference(self): + d = Dial() + d.conference( + "TestConferenceAttributes", + beep=False, + wait_url="", + start_conference_on_enter=True, + end_conference_on_exit=True, + ) + + r = VoiceResponse() + r.append(d) + + assert ( + self.strip(r) == '<?xml version="1.0" encoding="UTF-8"?><Response><Dial>' + '<Conference beep="false" endConferenceOnExit="true" startConferenceOnEnter="true" waitUrl="">' + "TestConferenceAttributes</Conference></Dial></Response>" + ) + + def test_muted_conference(self): + d = Dial() + d.conference( + "TestConferenceMutedAttribute", + beep=False, + muted=True, + wait_url="", + start_conference_on_enter=True, + end_conference_on_exit=True, + ) + + r = VoiceResponse() + r.append(d) + + assert ( + self.strip(r) == '<?xml version="1.0" encoding="UTF-8"?><Response><Dial>' + '<Conference beep="false" endConferenceOnExit="true" muted="true" startConferenceOnEnter="true" waitUrl="">' + "TestConferenceMutedAttribute</Conference></Dial></Response>" + ) + + +class TestQueue(TwilioTest): + def test_queue(self): + d = Dial() + d.queue("TestQueueAttribute", url="", method="GET") + + r = VoiceResponse() + r.append(d) + + assert ( + self.strip(r) == '<?xml version="1.0" encoding="UTF-8"?><Response><Dial>' + '<Queue method="GET" url="">TestQueueAttribute</Queue></Dial></Response>' + ) + + +class TestEcho(TwilioTest): + def test_echo(self): + r = VoiceResponse() + r.echo() + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Echo /></Response>' + ) + + +class TestEnqueue(TwilioTest): + def test_enqueue(self): + r = VoiceResponse() + r.enqueue( + "TestEnqueueAttribute", + action="act", + method="GET", + wait_url="wait", + wait_url_method="POST", + ) + + assert ( + self.strip(r) == '<?xml version="1.0" encoding="UTF-8"?><Response>' + '<Enqueue action="act" method="GET" waitUrl="wait" waitUrlMethod="POST">TestEnqueueAttribute</Enqueue>' + "</Response>" + ) + + def test_task_string(self): + e = Enqueue(None, workflowSid="123123123") + e.task('{"account_sid": "AC123123123"}') + + r = VoiceResponse() + r.append(e) + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Enqueue workflowSid="123123123">' + '<Task>{"account_sid": "AC123123123"}</Task></Enqueue></Response>' + ) + + def test_task_dict(self): + e = Enqueue(None, workflowSid="123123123") + e.task({"account_sid": "AC123123123"}) + + r = VoiceResponse() + r.append(e) + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Enqueue workflowSid="123123123">' + '<Task>{"account_sid": "AC123123123"}</Task></Enqueue></Response>' + ) + + +class TestDial(TwilioTest): + def test_dial(self): + """should redirect the call""" + r = VoiceResponse() + r.dial("1231231234") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Dial>1231231234</Dial></Response>' + ) + + def test_sim(self): + d = Dial() + d.sim("123123123") + + r = VoiceResponse() + r.append(d) + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Dial><Sim>123123123</Sim></Dial></Response>' + ) + + def test_sip(self): + """should redirect the call""" + d = Dial() + d.sip("foo@example.com") + + r = VoiceResponse() + r.append(d) + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Dial><Sip>foo@example.com</Sip></Dial></Response>' + ) + + def test_sip_username_password(self): + """should redirect the call""" + d = Dial() + d.sip("foo@example.com", username="foo", password="bar") + + r = VoiceResponse() + r.append(d) + + assert ( + self.strip(r) == '<?xml version="1.0" encoding="UTF-8"?><Response><Dial>' + '<Sip password="bar" username="foo">foo@example.com</Sip></Dial></Response>' + ) + + def test_add_number(self): + """add a number to a dial""" + d = Dial() + d.number("1231231234") + + r = VoiceResponse() + r.append(d) + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Dial><Number>1231231234</Number></Dial></Response>' + ) + + def test_add_number_status_callback_event(self): + """add a number to a dial with status callback events""" + d = Dial() + d.number( + "1231231234", + status_callback="http://example.com", + status_callback_event="initiated completed", + ) + + r = VoiceResponse() + r.append(d) + + assert ( + self.strip(r) == '<?xml version="1.0" encoding="UTF-8"?><Response><Dial>' + '<Number statusCallback="http://example.com" statusCallbackEvent="initiated completed">1231231234</Number>' + "</Dial></Response>" + ) + + def test_add_conference(self): + """add a conference to a dial""" + d = Dial() + d.conference("My Room") + + r = VoiceResponse() + r.append(d) + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Dial><Conference>My Room</Conference></Dial></Response>' + ) + + def test_add_queue(self): + """add a queue to a dial""" + d = Dial() + d.queue("The Cute Queue") + + r = VoiceResponse() + r.append(d) + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Dial><Queue>The Cute Queue</Queue></Dial></Response>' + ) + + def test_add_empty_client(self): + """add an empty client to a dial""" + d = Dial() + d.client("") + + r = VoiceResponse() + r.append(d) + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Dial><Client /></Dial></Response>' + ) + + def test_add_client(self): + """add a client to a dial""" + d = Dial() + d.client("alice") + + r = VoiceResponse() + r.append(d) + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Dial><Client>alice</Client></Dial></Response>' + ) + + +class TestGather(TwilioTest): + def test_empty(self): + """a gather with nothing inside""" + r = VoiceResponse() + r.gather() + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Gather /></Response>' + ) + + def test_gather_say(self): + g = Gather() + g.say("Hello") + + r = VoiceResponse() + r.append(g) + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Gather><Say>Hello</Say></Gather></Response>' + ) + + def test_nested_say_play_pause(self): + """a gather with a say, play, and pause""" + g = Gather() + g.say("Hey") + g.play(url="hey.mp3") + g.pause() + + r = VoiceResponse() + r.append(g) + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><Gather><Say>Hey</Say><Play>hey.mp3</Play>' + "<Pause /></Gather></Response>" + ) + + +class TestText(TwilioTest): + def test_text(self): + r = VoiceResponse() + r.append("No tags!") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response>No tags!</Response>' + ) + + def text_mixed(self): + r = VoiceResponse() + r.append("before") + r.say("Content") + r.append("after") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response>before<Say>Content</Say>after</Response>' + ) + + def test_add_child(self): + with VoiceResponse() as r: + with r.add_child("alexa", omnipresent="true") as alexa: + alexa.add_child("purchase", "Kindle") + + assert ( + self.strip(r) + == '<?xml version="1.0" encoding="UTF-8"?><Response><alexa omnipresent="true">' + "<purchase>Kindle</purchase></alexa></Response>" + ) diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000000..7db6cfc6fc --- /dev/null +++ b/tox.ini @@ -0,0 +1,9 @@ +[tox] +env_list = py3{7,8,9,10,11}, pypy +skip_missing_interpreters = true + +[testenv] +deps = -r{tox_root}/tests/requirements.txt +commands = + pytest \ + [] diff --git a/twilio/__init__.py b/twilio/__init__.py index f2bca0674d..5ce3ed13d0 100644 --- a/twilio/__init__.py +++ b/twilio/__init__.py @@ -1,18 +1,2 @@ -__version_info__ = ('3', '4', '5') -__version__ = '.'.join(__version_info__) - - -class TwilioException(Exception): - pass - - -class TwilioRestException(TwilioException): - - def __init__(self, status, uri, msg="", code=None): - self.uri = uri - self.status = status - self.msg = msg - self.code = code - - def __str__(self): - return "HTTP ERROR %s: %s \n %s" % (self.status, self.msg, self.uri) +__version_info__ = ("9", "6", "3") +__version__ = ".".join(__version_info__) diff --git a/twilio/auth_strategy/__init__.py b/twilio/auth_strategy/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/twilio/auth_strategy/auth_strategy.py b/twilio/auth_strategy/auth_strategy.py new file mode 100644 index 0000000000..223cbff08f --- /dev/null +++ b/twilio/auth_strategy/auth_strategy.py @@ -0,0 +1,19 @@ +from twilio.auth_strategy.auth_type import AuthType +from abc import abstractmethod + + +class AuthStrategy(object): + def __init__(self, auth_type: AuthType): + self._auth_type = auth_type + + @property + def auth_type(self) -> AuthType: + return self._auth_type + + @abstractmethod + def get_auth_string(self) -> str: + """Return the authentication string.""" + + @abstractmethod + def requires_authentication(self) -> bool: + """Return True if authentication is required, else False.""" diff --git a/twilio/auth_strategy/auth_type.py b/twilio/auth_strategy/auth_type.py new file mode 100644 index 0000000000..61886f925d --- /dev/null +++ b/twilio/auth_strategy/auth_type.py @@ -0,0 +1,12 @@ +from enum import Enum + + +class AuthType(Enum): + ORGS_TOKEN = "orgs_stoken" + NO_AUTH = "noauth" + BASIC = "basic" + API_KEY = "api_key" + CLIENT_CREDENTIALS = "client_credentials" + + def __str__(self): + return self.value diff --git a/twilio/auth_strategy/no_auth_strategy.py b/twilio/auth_strategy/no_auth_strategy.py new file mode 100644 index 0000000000..a5bfd6d27f --- /dev/null +++ b/twilio/auth_strategy/no_auth_strategy.py @@ -0,0 +1,13 @@ +from auth_type import AuthType +from twilio.auth_strategy.auth_strategy import AuthStrategy + + +class NoAuthStrategy(AuthStrategy): + def __init__(self): + super().__init__(AuthType.NO_AUTH) + + def get_auth_string(self) -> str: + return "" + + def requires_authentication(self) -> bool: + return False diff --git a/twilio/auth_strategy/token_auth_strategy.py b/twilio/auth_strategy/token_auth_strategy.py new file mode 100644 index 0000000000..33a8d385cb --- /dev/null +++ b/twilio/auth_strategy/token_auth_strategy.py @@ -0,0 +1,55 @@ +import jwt +import threading +import logging +from datetime import datetime, timezone + +from twilio.auth_strategy.auth_type import AuthType +from twilio.auth_strategy.auth_strategy import AuthStrategy +from twilio.http.token_manager import TokenManager + + +class TokenAuthStrategy(AuthStrategy): + def __init__(self, token_manager: TokenManager): + super().__init__(AuthType.ORGS_TOKEN) + self.token_manager = token_manager + self.token = None + self.lock = threading.Lock() + logging.basicConfig(level=logging.INFO) + self.logger = logging.getLogger(__name__) + + def get_auth_string(self) -> str: + self.fetch_token() + return f"Bearer {self.token}" + + def requires_authentication(self) -> bool: + return True + + def fetch_token(self): + if self.token is None or self.token == "" or self.is_token_expired(self.token): + with self.lock: + if ( + self.token is None + or self.token == "" + or self.is_token_expired(self.token) + ): + self.logger.info("New token fetched for accessing organization API") + self.token = self.token_manager.fetch_access_token() + + def is_token_expired(self, token): + try: + decoded = jwt.decode(token, options={"verify_signature": False}) + exp = decoded.get("exp") + + if exp is None: + return True # No expiration time present, consider it expired + + # Check if the expiration time has passed by using time-zone + return datetime.fromtimestamp(exp, tz=timezone.utc) < datetime.now( + timezone.utc + ) + + except jwt.DecodeError: + return True # Token is invalid + except Exception as e: + print(f"An error occurred: {e}") + return True diff --git a/twilio/base/__init__.py b/twilio/base/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/twilio/base/client_base.py b/twilio/base/client_base.py new file mode 100644 index 0000000000..b16f85bf5b --- /dev/null +++ b/twilio/base/client_base.py @@ -0,0 +1,271 @@ +import os +import platform +from typing import Dict, List, MutableMapping, Optional, Tuple +from urllib.parse import urlparse, urlunparse + +from twilio import __version__ +from twilio.http import HttpClient +from twilio.http.http_client import TwilioHttpClient +from twilio.http.response import Response +from twilio.credential.credential_provider import CredentialProvider + + +class ClientBase(object): + """A client for accessing the Twilio API.""" + + def __init__( + self, + username: Optional[str] = None, + password: Optional[str] = None, + account_sid: Optional[str] = None, + region: Optional[str] = None, + http_client: Optional[HttpClient] = None, + environment: Optional[MutableMapping[str, str]] = None, + edge: Optional[str] = None, + user_agent_extensions: Optional[List[str]] = None, + credential_provider: Optional[CredentialProvider] = None, + ): + """ + Initializes the Twilio Client + + :param username: Username to authenticate with + :param password: Password to authenticate with + :param account_sid: Account SID, defaults to Username + :param region: Twilio Region to make requests to, defaults to 'us1' if an edge is provided + :param http_client: HttpClient, defaults to TwilioHttpClient + :param environment: Environment to look for auth details, defaults to os.environ + :param edge: Twilio Edge to make requests to, defaults to None + :param user_agent_extensions: Additions to the user agent string + :param credential_provider: credential provider for authentication method that needs to be used + """ + + 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.edge = edge or environment.get("TWILIO_EDGE") + """ :type : str """ + self.region = region or environment.get("TWILIO_REGION") + """ :type : str """ + self.user_agent_extensions = user_agent_extensions or [] + """ :type : list[str] """ + self.credential_provider = credential_provider or None + """ :type : CredentialProvider """ + + self.account_sid = account_sid or self.username + """ :type : str """ + self.auth = (self.username, self.password) + """ :type : tuple(str, str) """ + self.http_client: HttpClient = http_client or TwilioHttpClient() + """ :type : HttpClient """ + + def request( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Makes a request to the Twilio API using the configured http client + Authentication information is automatically added if none is provided + + :param method: HTTP Method + :param uri: Fully qualified url + :param params: Query string parameters + :param data: POST body data + :param headers: HTTP Headers + :param auth: Authentication + :param timeout: Timeout in seconds + :param allow_redirects: Should the client follow redirects + + :returns: Response from the Twilio API + """ + headers = self.get_headers(method, headers) + + if self.credential_provider: + + auth_strategy = self.credential_provider.to_auth_strategy() + headers["Authorization"] = auth_strategy.get_auth_string() + elif self.username is not None and self.password is not None: + auth = self.get_auth(auth) + else: + auth = None + + if method == "DELETE": + del headers["Accept"] + + uri = self.get_hostname(uri) + filtered_data = self.copy_non_none_values(data) + return self.http_client.request( + method, + uri, + params=params, + data=filtered_data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + async def request_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Asynchronously makes a request to the Twilio API using the configured http client + The configured http client must be an asynchronous http client + Authentication information is automatically added if none is provided + + :param method: HTTP Method + :param uri: Fully qualified url + :param params: Query string parameters + :param data: POST body data + :param headers: HTTP Headers + :param auth: Authentication + :param timeout: Timeout in seconds + :param allow_redirects: Should the client follow redirects + + :returns: Response from the Twilio API + """ + if not self.http_client.is_async: + raise RuntimeError( + "http_client must be asynchronous to support async API requests" + ) + + headers = self.get_headers(method, headers) + if method == "DELETE": + del headers["Accept"] + + if self.credential_provider: + auth_strategy = self.credential_provider.to_auth_strategy() + headers["Authorization"] = auth_strategy.get_auth_string() + elif self.username is not None and self.password is not None: + auth = self.get_auth(auth) + else: + auth = None + + uri = self.get_hostname(uri) + filtered_data = self.copy_non_none_values(data) + return await self.http_client.request( + method, + uri, + params=params, + data=filtered_data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + def copy_non_none_values(self, data): + if isinstance(data, dict): + return { + k: self.copy_non_none_values(v) + for k, v in data.items() + if v is not None + } + elif isinstance(data, list): + return [ + self.copy_non_none_values(item) for item in data if item is not None + ] + return data + + def get_auth(self, auth: Optional[Tuple[str, str]]) -> Tuple[str, str]: + """ + Get the request authentication object + :param auth: Authentication (username, password) + :returns: The authentication object + """ + return auth or self.auth + + def get_headers( + self, method: str, headers: Optional[Dict[str, str]] + ) -> Dict[str, str]: + """ + Get the request headers including user-agent, extensions, encoding, content-type, MIME type + :param method: HTTP method + :param headers: HTTP headers + :returns: HTTP headers + """ + headers = headers or {} + + # Set User-Agent + pkg_version = __version__ + os_name = platform.system() + os_arch = platform.machine() + python_version = platform.python_version() + headers["User-Agent"] = "twilio-python/{} ({} {}) Python/{}".format( + pkg_version, + os_name, + os_arch, + python_version, + ) + # Extensions + for extension in self.user_agent_extensions: + headers["User-Agent"] += " {}".format(extension) + headers["X-Twilio-Client"] = "python-{}".format(__version__) + + # Types, encodings, etc. + headers["Accept-Charset"] = "utf-8" + if (method == "POST" or method == "PUT") and ("Content-Type" not in headers): + headers["Content-Type"] = "application/x-www-form-urlencoded" + if "Accept" not in headers: + headers["Accept"] = "application/json" + + return headers + + def get_hostname(self, uri: str) -> str: + """ + Determines the proper hostname given edge and region preferences + via client configuration or uri. + + :param uri: Fully qualified url + + :returns: The final uri used to make the request + """ + if not self.edge and not self.region: + return uri + + parsed_url = urlparse(uri) + pieces = parsed_url.netloc.split(".") + prefix = pieces[0] + suffix = ".".join(pieces[-2:]) + region = None + edge = None + if len(pieces) == 4: + # product.region.twilio.com + region = pieces[1] + elif len(pieces) == 5: + # product.edge.region.twilio.com + edge = pieces[1] + region = pieces[2] + + edge = self.edge or edge + region = self.region or region or (edge and "us1") + + parsed_url = parsed_url._replace( + netloc=".".join([part for part in [prefix, edge, region, suffix] if part]) + ) + return str(urlunparse(parsed_url)) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio {}>".format(self.account_sid) diff --git a/twilio/base/deserialize.py b/twilio/base/deserialize.py new file mode 100644 index 0000000000..71226c08f8 --- /dev/null +++ b/twilio/base/deserialize.py @@ -0,0 +1,75 @@ +import datetime +from decimal import BasicContext, Decimal +from email.utils import parsedate +from typing import Optional, Union + +ISO8601_DATE_FORMAT = "%Y-%m-%d" +ISO8601_DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ" + + +def iso8601_date(s: str) -> Union[datetime.date, str]: + """ + Parses an ISO 8601 date string and returns a UTC date object or the string + if the parsing failed. + :param s: ISO 8601-formatted date string (2015-01-25) + :return: + """ + try: + return ( + datetime.datetime.strptime(s, ISO8601_DATE_FORMAT) + .replace(tzinfo=datetime.timezone.utc) + .date() + ) + except (TypeError, ValueError): + return s + + +def iso8601_datetime( + s: str, +) -> Union[datetime.datetime, str]: + """ + Parses an ISO 8601 datetime string and returns a UTC datetime object, + or the string if parsing failed. + :param s: ISO 8601-formatted datetime string (2015-01-25T12:34:56Z) + """ + try: + return datetime.datetime.strptime(s, ISO8601_DATETIME_FORMAT).replace( + tzinfo=datetime.timezone.utc + ) + except (TypeError, ValueError): + return s + + +def rfc2822_datetime(s: str) -> Optional[datetime.datetime]: + """ + Parses an RFC 2822 date string and returns a UTC datetime object, + or the string if parsing failed. + :param s: RFC 2822-formatted string date + :return: datetime or str + """ + date_tuple = parsedate(s) + if date_tuple is None: + return None + return datetime.datetime(*date_tuple[:6]).replace(tzinfo=datetime.timezone.utc) + + +def decimal(d: Optional[str]) -> Union[Decimal, str]: + """ + Parses a decimal string into a Decimal + :param d: decimal string + """ + if not d: + return d + return Decimal(d, BasicContext) + + +def integer(i: str) -> Union[int, str]: + """ + Parses an integer string into an int + :param i: integer string + :return: int + """ + try: + return int(i) + except (TypeError, ValueError): + return i diff --git a/twilio/base/domain.py b/twilio/base/domain.py new file mode 100644 index 0000000000..4f8395ddf2 --- /dev/null +++ b/twilio/base/domain.py @@ -0,0 +1,93 @@ +from typing import Dict, Optional, Tuple +from twilio.http.response import Response +from twilio.rest import Client + + +class Domain(object): + """ + This represents at Twilio API subdomain. + + Like, `api.twilio.com` or `lookups.twilio.com'. + """ + + def __init__(self, twilio: Client, base_url: str): + self.twilio = twilio + self.base_url = base_url + + def absolute_url(self, uri: str) -> str: + """ + Converts a relative `uri` to an absolute url. + :param string uri: The relative uri to make absolute. + :return: An absolute url (based off this domain) + """ + return "{}/{}".format(self.base_url.strip("/"), uri.strip("/")) + + def request( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Makes an HTTP request to this domain. + :param method: The HTTP method. + :param uri: The HTTP uri. + :param params: Query parameters. + :param data: The request body. + :param headers: The HTTP headers. + :param auth: Basic auth tuple of (username, password) + :param timeout: The request timeout. + :param allow_redirects: True if the client should follow HTTP + redirects. + """ + url = self.absolute_url(uri) + return self.twilio.request( + method, + url, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + async def request_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Makes an asynchronous HTTP request to this domain. + :param method: The HTTP method. + :param uri: The HTTP uri. + :param params: Query parameters. + :param data: The request body. + :param headers: The HTTP headers. + :param auth: Basic auth tuple of (username, password) + :param timeout: The request timeout. + :param allow_redirects: True if the client should follow HTTP + redirects. + """ + url = self.absolute_url(uri) + return await self.twilio.request_async( + method, + url, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) diff --git a/twilio/base/exceptions.py b/twilio/base/exceptions.py new file mode 100644 index 0000000000..8f3b7cc7a1 --- /dev/null +++ b/twilio/base/exceptions.py @@ -0,0 +1,82 @@ +# -*- coding: utf-8 -*- +import sys +from typing import Optional + + +class TwilioException(Exception): + pass + + +class TwilioRestException(TwilioException): + """A generic 400 or 500 level exception from the Twilio API + + :param int status: the HTTP status that was returned for the exception + :param str uri: The URI that caused the exception + :param str msg: A human-readable message for the error + :param int|None code: A Twilio-specific error code for the error. This is + not available for all errors. + :param method: The HTTP method used to make the request + :param details: Additional error details returned for the exception + """ + + def __init__( + self, + status: int, + uri: str, + msg: str = "", + code: Optional[int] = None, + method: str = "GET", + details: Optional[object] = None, + ): + self.uri = uri + self.status = status + self.msg = msg + self.code = code + self.method = method + self.details = details + + def __str__(self) -> str: + """Try to pretty-print the exception, if this is going on screen.""" + + def red(words: str) -> str: + return "\033[31m\033[49m%s\033[0m" % words + + def white(words: str) -> str: + return "\033[37m\033[49m%s\033[0m" % words + + def blue(words: str) -> str: + return "\033[34m\033[49m%s\033[0m" % words + + def teal(words: str) -> str: + return "\033[36m\033[49m%s\033[0m" % words + + def get_uri(code: int) -> str: + return "https://www.twilio.com/docs/errors/{0}".format(code) + + # If it makes sense to print a human readable error message, try to + # do it. The one problem is that someone might catch this error and + # try to display the message from it to an end user. + if hasattr(sys.stderr, "isatty") and sys.stderr.isatty(): + msg = ( + "\n{red_error} {request_was}\n\n{http_line}" + "\n\n{twilio_returned}\n\n{message}\n".format( + red_error=red("HTTP Error"), + request_was=white("Your request was:"), + http_line=teal("%s %s" % (self.method, self.uri)), + twilio_returned=white("Twilio returned the following information:"), + message=blue(str(self.msg)), + ) + ) + if self.code: + msg = "".join( + [ + msg, + "\n{more_info}\n\n{uri}\n\n".format( + more_info=white("More information may be available here:"), + uri=blue(get_uri(self.code)), + ), + ] + ) + return msg + else: + return "HTTP {0} error: {1}".format(self.status, self.msg) diff --git a/twilio/base/instance_context.py b/twilio/base/instance_context.py new file mode 100644 index 0000000000..44ff9a384b --- /dev/null +++ b/twilio/base/instance_context.py @@ -0,0 +1,6 @@ +from twilio.base.version import Version + + +class InstanceContext(object): + def __init__(self, version: Version): + self._version = version diff --git a/twilio/base/instance_resource.py b/twilio/base/instance_resource.py new file mode 100644 index 0000000000..a05aac373e --- /dev/null +++ b/twilio/base/instance_resource.py @@ -0,0 +1,6 @@ +from twilio.base.version import Version + + +class InstanceResource(object): + def __init__(self, version: Version): + self._version = version diff --git a/twilio/base/list_resource.py b/twilio/base/list_resource.py new file mode 100644 index 0000000000..e3eb176d96 --- /dev/null +++ b/twilio/base/list_resource.py @@ -0,0 +1,6 @@ +from twilio.base.version import Version + + +class ListResource(object): + def __init__(self, version: Version): + self._version = version diff --git a/twilio/base/obsolete.py b/twilio/base/obsolete.py new file mode 100644 index 0000000000..e0f4a0339d --- /dev/null +++ b/twilio/base/obsolete.py @@ -0,0 +1,47 @@ +import warnings +import functools + + +class ObsoleteException(Exception): + """Base class for warnings about obsolete features.""" + + +def obsolete_client(func): + """This is a decorator which can be used to mark Client classes as + obsolete. It will result in an error being emitted when the class is + instantiated.""" + + @functools.wraps(func) + def new_func(*args, **kwargs): + raise ObsoleteException( + "{} has been removed from this version of the library. " + "Please refer to current documentation for guidance.".format(func.__name__) + ) + + return new_func + + +def deprecated_method(new_func=None): + """ + This is a decorator which can be used to mark deprecated methods. + It will report in a DeprecationWarning being emitted to stderr when the deprecated method is used. + """ + + def deprecated_method_wrapper(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + msg = "Function method .{}() is deprecated".format(func.__name__) + msg += ( + " in favor of .{}()".format(new_func) + if isinstance(new_func, str) + else "" + ) + warnings.warn(msg, DeprecationWarning) + return func(*args, **kwargs) + + return wrapper + + if callable(new_func): + return deprecated_method_wrapper(new_func) + + return deprecated_method_wrapper diff --git a/twilio/base/page.py b/twilio/base/page.py new file mode 100644 index 0000000000..b5b2da7b26 --- /dev/null +++ b/twilio/base/page.py @@ -0,0 +1,173 @@ +import json +from typing import Any, Dict, Optional + +from twilio.base.exceptions import TwilioException +from twilio.http.response import Response + + +class Page(object): + """ + Represents a page of records in a collection. + + A `Page` lets you iterate over its records and fetch the next and previous + pages in the collection. + """ + + META_KEYS = { + "end", + "first_page_uri", + "next_page_uri", + "last_page_uri", + "page", + "page_size", + "previous_page_uri", + "total", + "num_pages", + "start", + "uri", + } + + def __init__(self, version, response: Response, solution={}): + payload = self.process_response(response) + + self._version = version + self._payload = payload + self._solution = solution + self._records = iter(self.load_page(payload)) + + def __iter__(self): + """ + A `Page` is a valid iterator. + """ + return self + + def __next__(self): + return self.next() + + def next(self): + """ + Returns the next record in the `Page`. + """ + return self.get_instance(next(self._records)) + + @classmethod + def process_response(cls, response: Response) -> Any: + """ + Load a JSON response. + + :param response: The HTTP response. + :return The JSON-loaded content. + """ + if response.status_code != 200: + raise TwilioException("Unable to fetch page", response) + + return json.loads(response.text) + + def load_page(self, payload: Dict[str, Any]): + """ + Parses the collection of records out of a list payload. + + :param 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()] + if "Resources" in payload: + return payload["Resources"] + + raise TwilioException("Page Records can not be deserialized") + + @property + def previous_page_url(self) -> Optional[str]: + """ + :return str: Returns a link to the previous_page_url or None if doesn't exist. + """ + if "meta" in self._payload and "previous_page_url" in self._payload["meta"]: + return self._payload["meta"]["previous_page_url"] + elif ( + "previous_page_uri" in self._payload and self._payload["previous_page_uri"] + ): + return self._version.domain.absolute_url(self._payload["previous_page_uri"]) + + return None + + @property + def next_page_url(self) -> Optional[str]: + """ + :return str: Returns a link to the next_page_url or None if doesn't exist. + """ + if "meta" in self._payload and "next_page_url" in self._payload["meta"]: + return self._payload["meta"]["next_page_url"] + elif "next_page_uri" in self._payload and self._payload["next_page_uri"]: + return self._version.domain.absolute_url(self._payload["next_page_uri"]) + + return None + + def get_instance(self, payload: Dict[str, Any]) -> Any: + """ + :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" + ) + + def next_page(self) -> Optional["Page"]: + """ + Return the `Page` after this one. + :return The next page. + """ + if not self.next_page_url: + return None + + response = self._version.domain.twilio.request("GET", self.next_page_url) + cls = type(self) + return cls(self._version, response, self._solution) + + async def next_page_async(self) -> Optional["Page"]: + """ + Asynchronously return the `Page` after this one. + :return The next page. + """ + if not self.next_page_url: + return None + + response = await self._version.domain.twilio.request_async( + "GET", self.next_page_url + ) + cls = type(self) + return cls(self._version, response, self._solution) + + def previous_page(self) -> Optional["Page"]: + """ + Return the `Page` before this one. + :return The previous page. + """ + if not self.previous_page_url: + return None + + response = self._version.domain.twilio.request("GET", self.previous_page_url) + cls = type(self) + return cls(self._version, response, self._solution) + + async def previous_page_async(self) -> Optional["Page"]: + """ + Asynchronously return the `Page` before this one. + :return The previous page. + """ + if not self.previous_page_url: + return None + + response = await self._version.domain.twilio.request_async( + "GET", self.previous_page_url + ) + cls = type(self) + return cls(self._version, response, self._solution) + + def __repr__(self) -> str: + return "<Page>" diff --git a/twilio/base/serialize.py b/twilio/base/serialize.py new file mode 100644 index 0000000000..cea91b04c7 --- /dev/null +++ b/twilio/base/serialize.py @@ -0,0 +1,93 @@ +import datetime +import json + +from twilio.base import values + + +def iso8601_date(d): + """ + Return a string representation of a date that the Twilio API understands + Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date + """ + if d == values.unset: + return d + elif isinstance(d, datetime.datetime): + return str(d.date()) + elif isinstance(d, datetime.date): + return str(d) + elif isinstance(d, str): + return d + + +def iso8601_datetime(d): + """ + Return a string representation of a date that the Twilio API understands + Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date + """ + if d == values.unset: + return d + elif isinstance(d, datetime.datetime) or isinstance(d, datetime.date): + return d.strftime("%Y-%m-%dT%H:%M:%SZ") + elif isinstance(d, str): + return d + + +def prefixed_collapsible_map(m, prefix): + """ + Return a dict of params corresponding to those in m with the added prefix + """ + if m == values.unset: + return {} + + def flatten_dict(d, result=None, prv_keys=None): + if result is None: + result = {} + + if prv_keys is None: + prv_keys = [] + + for k, v in d.items(): + if isinstance(v, dict): + flatten_dict(v, result, prv_keys + [k]) + else: + result[".".join(prv_keys + [k])] = v + + return result + + if isinstance(m, dict): + flattened = flatten_dict(m) + return {"{}.{}".format(prefix, k): v for k, v in flattened.items()} + + return {} + + +def boolean_to_string(bool_or_str): + if bool_or_str == values.unset: + return bool_or_str + + if bool_or_str is None: + return bool_or_str + + if isinstance(bool_or_str, str): + return bool_or_str.lower() + + return "true" if bool_or_str else "false" + + +def object(obj): + """ + Return a jsonified string represenation of obj if obj is jsonifiable else + return obj untouched + """ + if isinstance(obj, dict) or isinstance(obj, list): + return json.dumps(obj) + return obj + + +def map(lst, serialize_func): + """ + Applies serialize_func to every element in lst + """ + if not isinstance(lst, list): + return lst + return [serialize_func(e) for e in lst] diff --git a/twilio/base/values.py b/twilio/base/values.py new file mode 100644 index 0000000000..16032b1120 --- /dev/null +++ b/twilio/base/values.py @@ -0,0 +1,13 @@ +from typing import Dict + +unset = object() + + +def of(d: Dict[str, object]) -> Dict[str, object]: + """ + Remove unset values from a dict. + + :param d: A dict to strip. + :return A dict with unset values removed. + """ + return {k: v for k, v in d.items() if v != unset} diff --git a/twilio/base/version.py b/twilio/base/version.py new file mode 100644 index 0000000000..ed7e86f499 --- /dev/null +++ b/twilio/base/version.py @@ -0,0 +1,489 @@ +import json +from typing import Any, AsyncIterator, Dict, Iterator, Optional, Tuple + +from twilio.base import values +from twilio.base.domain import Domain +from twilio.base.exceptions import TwilioRestException +from twilio.base.page import Page +from twilio.http.response import Response + + +class Version(object): + """ + Represents an API version. + """ + + def __init__(self, domain: Domain, version: str): + self.domain = domain + self.version = version + + def absolute_url(self, uri: str) -> str: + """ + Turns a relative uri into an absolute url. + """ + return self.domain.absolute_url(self.relative_uri(uri)) + + def relative_uri(self, uri: str) -> str: + """ + Turns a relative uri into a versioned relative uri. + """ + return "{}/{}".format(self.version.strip("/"), uri.strip("/")) + + def request( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Make an HTTP request. + """ + url = self.relative_uri(uri) + return self.domain.request( + method, + url, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + async def request_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Make an asynchronous HTTP request + """ + url = self.relative_uri(uri) + return await self.domain.request_async( + method, + url, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + @classmethod + def exception( + cls, method: str, uri: str, response: Response, message: str + ) -> TwilioRestException: + """ + Wraps an exceptional response in a `TwilioRestException`. + """ + # noinspection PyBroadException + try: + error_payload = json.loads(response.text) + if "message" in error_payload: + message = "{}: {}".format(message, error_payload["message"]) + details = error_payload.get("details") + code = error_payload.get("code", response.status_code) + return TwilioRestException( + response.status_code, uri, message, code, method, details + ) + except Exception: + return TwilioRestException( + response.status_code, uri, message, response.status_code, method + ) + + def _parse_fetch(self, method: str, uri: str, response: Response) -> Any: + """ + Parses fetch response JSON + """ + # Note that 3XX response codes are allowed for fetches. + if response.status_code < 200 or response.status_code >= 400: + raise self.exception(method, uri, response, "Unable to fetch record") + + return json.loads(response.text) + + def fetch( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Any: + """ + Fetch a resource instance. + """ + response = self.request( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + return self._parse_fetch(method, uri, response) + + async def fetch_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Any: + """ + Asynchronously fetch a resource instance. + """ + response = await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + return self._parse_fetch(method, uri, response) + + def _parse_update(self, method: str, uri: str, response: Response) -> Any: + """ + Parses update response JSON + """ + if response.status_code < 200 or response.status_code >= 300: + raise self.exception(method, uri, response, "Unable to update record") + + return json.loads(response.text) + + def update( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Any: + """ + Update a resource instance. + """ + response = self.request( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + return self._parse_update(method, uri, response) + + async def update_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Any: + """ + Asynchronously update a resource instance. + """ + response = await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + return self._parse_update(method, uri, response) + + def _parse_delete(self, method: str, uri: str, response: Response) -> bool: + """ + Parses delete response JSON + """ + if response.status_code < 200 or response.status_code >= 300: + raise self.exception(method, uri, response, "Unable to delete record") + + return response.status_code == 204 + + def delete( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> bool: + """ + Delete a resource. + """ + response = self.request( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + return self._parse_delete(method, uri, response) + + async def delete_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> bool: + """ + Asynchronously delete a resource. + """ + response = await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + return self._parse_delete(method, uri, response) + + def read_limits( + self, limit: Optional[int] = None, page_size: Optional[int] = None + ) -> Dict[str, object]: + """ + Takes a limit on the max number of records to read and a max page_size + and calculates the max number of pages to read. + + :param limit: Max number of records to read. + :param page_size: Max page size. + :return A dictionary of paging limits. + """ + if limit is not None and page_size is None: + page_size = limit + + return { + "limit": limit or values.unset, + "page_size": page_size or values.unset, + } + + def page( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Makes an HTTP request. + """ + return self.request( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + async def page_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Makes an asynchronous HTTP request. + """ + return await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + + def stream( + self, + page: Optional[Page], + limit: Optional[int] = None, + page_limit: Optional[int] = None, + ) -> Iterator[Any]: + """ + Generates records one a time from a page, stopping at prescribed limits. + + :param page: The page to stream. + :param limit: The max number of records to read. + :param page_limit: The max number of pages to read. + """ + current_record = 1 + current_page = 1 + + while page is not None: + for record in page: + yield record + current_record += 1 + if limit and limit is not values.unset and limit < current_record: + return + + current_page += 1 + if ( + page_limit + and page_limit is not values.unset + and page_limit < current_page + ): + return + + page = page.next_page() + + async def stream_async( + self, + page: Optional[Page], + limit: Optional[int] = None, + page_limit: Optional[int] = None, + ) -> AsyncIterator[Any]: + """ + Generates records one a time from a page, stopping at prescribed limits. + + :param page: The page to stream. + :param limit: The max number of records to read. + :param page_limit: The max number of pages to read. + """ + current_record = 1 + current_page = 1 + + while page is not None: + for record in page: + yield record + current_record += 1 + if limit and limit is not values.unset and limit < current_record: + return + + current_page += 1 + if ( + page_limit + and page_limit is not values.unset + and page_limit < current_page + ): + return + + page = await page.next_page_async() + + def _parse_create(self, method: str, uri: str, response: Response) -> Any: + """ + Parse create response JSON + """ + if response.status_code < 200 or response.status_code >= 300: + raise self.exception(method, uri, response, "Unable to create record") + + return json.loads(response.text) + + def create( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Any: + """ + Create a resource instance. + """ + response = self.request( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + return self._parse_create(method, uri, response) + + async def create_async( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Any: + """ + Asynchronously create a resource instance. + """ + response = await self.request_async( + method, + uri, + params=params, + data=data, + headers=headers, + auth=auth, + timeout=timeout, + allow_redirects=allow_redirects, + ) + return self._parse_create(method, uri, response) diff --git a/twilio/compat/__init__.py b/twilio/compat/__init__.py deleted file mode 100644 index 640a677746..0000000000 --- a/twilio/compat/__init__.py +++ /dev/null @@ -1,20 +0,0 @@ - -# Those are not supported by the six library and needs to be done manually -from six import binary_type - -try: - # python 3 - from urllib.parse import urlencode, urlparse, urljoin -except ImportError: - # python 2 backward compatibility - #noinspection PyUnresolvedReferences - from urllib import urlencode - #noinspection PyUnresolvedReferences - from urlparse import urlparse, urljoin - -try: - # python 2 - from itertools import izip -except ImportError: - # python 3 - izip = zip diff --git a/twilio/credential/__init__.py b/twilio/credential/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/twilio/credential/client_credential_provider.py b/twilio/credential/client_credential_provider.py new file mode 100644 index 0000000000..656d446395 --- /dev/null +++ b/twilio/credential/client_credential_provider.py @@ -0,0 +1,28 @@ +from twilio.http.client_token_manager import ClientTokenManager +from twilio.base.exceptions import TwilioException +from twilio.credential.credential_provider import CredentialProvider +from twilio.auth_strategy.auth_type import AuthType +from twilio.auth_strategy.token_auth_strategy import TokenAuthStrategy + + +class ClientCredentialProvider(CredentialProvider): + def __init__(self, client_id: str, client_secret: str, token_manager=None): + super().__init__(AuthType.CLIENT_CREDENTIALS) + + if client_id is None or client_secret is None: + raise TwilioException("Client id and Client secret are mandatory") + + self.grant_type = "client_credentials" + self.client_id = client_id + self.client_secret = client_secret + self.token_manager = token_manager + self.auth_strategy = None + + def to_auth_strategy(self): + if self.token_manager is None: + self.token_manager = ClientTokenManager( + self.grant_type, self.client_id, self.client_secret + ) + if self.auth_strategy is None: + self.auth_strategy = TokenAuthStrategy(self.token_manager) + return self.auth_strategy diff --git a/twilio/credential/credential_provider.py b/twilio/credential/credential_provider.py new file mode 100644 index 0000000000..72aafeed47 --- /dev/null +++ b/twilio/credential/credential_provider.py @@ -0,0 +1,13 @@ +from twilio.auth_strategy.auth_type import AuthType + + +class CredentialProvider: + def __init__(self, auth_type: AuthType): + self._auth_type = auth_type + + @property + def auth_type(self) -> AuthType: + return self._auth_type + + def to_auth_strategy(self): + raise NotImplementedError("Subclasses must implement this method") diff --git a/twilio/credential/orgs_credential_provider.py b/twilio/credential/orgs_credential_provider.py new file mode 100644 index 0000000000..e623f52322 --- /dev/null +++ b/twilio/credential/orgs_credential_provider.py @@ -0,0 +1,28 @@ +from twilio.http.orgs_token_manager import OrgTokenManager +from twilio.base.exceptions import TwilioException +from twilio.credential.credential_provider import CredentialProvider +from twilio.auth_strategy.auth_type import AuthType +from twilio.auth_strategy.token_auth_strategy import TokenAuthStrategy + + +class OrgsCredentialProvider(CredentialProvider): + def __init__(self, client_id: str, client_secret: str, token_manager=None): + super().__init__(AuthType.CLIENT_CREDENTIALS) + + if client_id is None or client_secret is None: + raise TwilioException("Client id and Client secret are mandatory") + + self.grant_type = "client_credentials" + self.client_id = client_id + self.client_secret = client_secret + self.token_manager = token_manager + self.auth_strategy = None + + def to_auth_strategy(self): + if self.token_manager is None: + self.token_manager = OrgTokenManager( + self.grant_type, self.client_id, self.client_secret + ) + if self.auth_strategy is None: + self.auth_strategy = TokenAuthStrategy(self.token_manager) + return self.auth_strategy diff --git a/twilio/http/__init__.py b/twilio/http/__init__.py new file mode 100644 index 0000000000..3e24827035 --- /dev/null +++ b/twilio/http/__init__.py @@ -0,0 +1,104 @@ +from logging import Logger +from typing import Any, Dict, Optional, Tuple +from urllib.parse import urlencode + +from requests import Response + +from twilio.base.exceptions import TwilioException +from twilio.http.request import Request as TwilioRequest +from twilio.http.response import Response as TwilioResponse + + +class HttpClient(object): + def __init__(self, logger: Logger, is_async: bool, timeout: Optional[float] = None): + """ + Constructor for the abstract HTTP client + + :param logger + :param is_async: Whether the client supports async request calls. + :param timeout: Timeout for the requests. + Timeout should never be zero (0) or less. + """ + self.logger = logger + self.is_async = is_async + + if timeout is not None and timeout <= 0: + raise ValueError(timeout) + self.timeout = timeout + + self._test_only_last_request: Optional[TwilioRequest] = None + self._test_only_last_response: Optional[TwilioResponse] = None + + """ + An abstract class representing an HTTP client. + """ + + def request( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> TwilioResponse: + """ + Make an HTTP request. + """ + raise TwilioException("HttpClient is an abstract class") + + def log_request(self, kwargs: Dict[str, Any]) -> None: + """ + Logs the HTTP request + """ + self.logger.info("-- BEGIN Twilio API Request --") + + if kwargs["params"]: + self.logger.info( + "{} Request: {}?{}".format( + kwargs["method"], kwargs["url"], urlencode(kwargs["params"]) + ) + ) + self.logger.info("Query Params: {}".format(kwargs["params"])) + else: + self.logger.info("{} Request: {}".format(kwargs["method"], kwargs["url"])) + + if kwargs["headers"]: + self.logger.info("Headers:") + for key, value in kwargs["headers"].items(): + # Do not log authorization headers + if "authorization" not in key.lower(): + self.logger.info("{} : {}".format(key, value)) + + self.logger.info("-- END Twilio API Request --") + + def log_response(self, status_code: int, response: Response) -> None: + """ + Logs the HTTP response + """ + self.logger.info("Response Status Code: {}".format(status_code)) + self.logger.info("Response Headers: {}".format(response.headers)) + + +class AsyncHttpClient(HttpClient): + """ + An abstract class representing an asynchronous HTTP client. + """ + + async def request( + self, + method: str, + uri: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> TwilioResponse: + """ + Make an asynchronous HTTP request. + """ + raise TwilioException("AsyncHttpClient is an abstract class") diff --git a/twilio/http/async_http_client.py b/twilio/http/async_http_client.py new file mode 100644 index 0000000000..ecd5d4de95 --- /dev/null +++ b/twilio/http/async_http_client.py @@ -0,0 +1,135 @@ +import logging +from typing import Dict, Optional, Tuple + +from aiohttp import BasicAuth, ClientSession +from aiohttp_retry import ExponentialRetry, RetryClient + +from twilio.http import AsyncHttpClient +from twilio.http.request import Request as TwilioRequest +from twilio.http.response import Response + +_logger = logging.getLogger("twilio.async_http_client") + + +class AsyncTwilioHttpClient(AsyncHttpClient): + """ + General purpose asynchronous HTTP Client for interacting with the Twilio API + """ + + def __init__( + self, + pool_connections: bool = True, + trace_configs=None, + timeout: Optional[float] = None, + logger: logging.Logger = _logger, + proxy_url: Optional[str] = None, + max_retries: Optional[int] = None, + ): + """ + Constructor for the AsyncTwilioHttpClient + + :param pool_connections: Creates a client session for making requests from. + :param trace_configs: Configuration used to trace request lifecycle events. See aiohttp library TraceConfig + documentation for more info. + :param timeout: Timeout for the requests (seconds) + :param logger + :param proxy_url: Proxy URL + :param max_retries: Maximum number of retries each request should attempt + """ + super().__init__(logger, True, timeout) + self.proxy_url = proxy_url + self.trace_configs = trace_configs + self.session = ( + ClientSession(trace_configs=self.trace_configs) + if pool_connections + else None + ) + if max_retries is not None: + retry_options = ExponentialRetry(attempts=max_retries) + self.session = RetryClient( + client_session=self.session, retry_options=retry_options + ) + + async def request( + self, + method: str, + url: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Make an asynchronous HTTP Request with parameters provided. + + :param method: The HTTP method to use + :param url: The URL to request + :param params: Query parameters to append to the URL + :param data: Parameters to go in the body of the HTTP request + :param headers: HTTP Headers to send with the request + :param auth: Basic Auth arguments (username, password entries) + :param timeout: Socket/Read timeout for the request. Overrides the timeout if set on the client. + :param allow_redirects: Whether or not to allow redirects + See the requests documentation for explanation of all these parameters + + :return: An http response + """ + if timeout is not None and timeout <= 0: + raise ValueError(timeout) + + basic_auth = None + if auth is not None: + basic_auth = BasicAuth(login=auth[0], password=auth[1]) + + kwargs = { + "method": method.upper(), + "url": url, + "params": params, + "data": data, + "headers": headers, + "auth": basic_auth, + "timeout": timeout, + "allow_redirects": allow_redirects, + } + + self.log_request(kwargs) + self._test_only_last_response = None + + temp = False + session = None + if self.session: + session = self.session + else: + session = ClientSession() + temp = True + self._test_only_last_request = TwilioRequest(**kwargs) + response = await session.request(**kwargs) + self.log_response(response.status, response) + self._test_only_last_response = Response( + response.status, await response.text(), response.headers + ) + if temp: + await session.close() + return self._test_only_last_response + + async def close(self): + """ + Closes the HTTP client session + """ + if self.session: + await self.session.close() + + async def __aenter__(self): + """ + Async context manager setup + """ + return self + + async def __aexit__(self, *excinfo): + """ + Async context manager exit + """ + if self.session: + await self.session.close() diff --git a/twilio/http/client_token_manager.py b/twilio/http/client_token_manager.py new file mode 100644 index 0000000000..0d42428a2f --- /dev/null +++ b/twilio/http/client_token_manager.py @@ -0,0 +1,41 @@ +from twilio.http.token_manager import TokenManager +from twilio.rest import Client + + +class ClientTokenManager(TokenManager): + """ + Client Token Manager + """ + + def __init__( + self, + grant_type: str, + client_id: str, + client_secret: str, + code: str = None, + redirect_uri: str = None, + audience: str = None, + refreshToken: str = None, + scope: str = None, + ): + self.grant_type = grant_type + self.client_id = client_id + self.client_secret = client_secret + self.code = code + self.redirect_uri = redirect_uri + self.audience = audience + self.refreshToken = refreshToken + self.scope = scope + self.client = Client() + + def fetch_access_token(self): + token_instance = self.client.iam.v1.token.create( + grant_type=self.grant_type, + client_id=self.client_id, + client_secret=self.client_secret, + code=self.code, + redirect_uri=self.redirect_uri, + audience=self.audience, + scope=self.scope, + ) + return token_instance.access_token diff --git a/twilio/http/http_client.py b/twilio/http/http_client.py new file mode 100644 index 0000000000..2f2d363535 --- /dev/null +++ b/twilio/http/http_client.py @@ -0,0 +1,119 @@ +import os +import logging +from typing import Dict, Optional, Tuple + +from requests import Request, Session, hooks +from requests.adapters import HTTPAdapter + +from twilio.http import HttpClient +from twilio.http.request import Request as TwilioRequest +from twilio.http.response import Response + +_logger = logging.getLogger("twilio.http_client") + + +class TwilioHttpClient(HttpClient): + """ + General purpose HTTP Client for interacting with the Twilio API + """ + + def __init__( + self, + pool_connections: bool = True, + request_hooks: Optional[Dict[str, object]] = None, + timeout: Optional[float] = None, + logger: logging.Logger = _logger, + proxy: Optional[Dict[str, str]] = None, + max_retries: Optional[int] = None, + ): + """ + Constructor for the TwilioHttpClient + :param pool_connections + :param request_hooks + :param timeout: Timeout for the requests. + Timeout should never be zero (0) or less + :param logger + :param proxy: Http proxy for the requests session + :param max_retries: Maximum number of retries each request should attempt + """ + super().__init__(logger, False, timeout) + self.session = Session() if pool_connections else None + if self.session and max_retries is not None: + self.session.mount("https://", HTTPAdapter(max_retries=max_retries)) + elif self.session is not None: + self.session.mount( + "https://", HTTPAdapter(pool_maxsize=min(32, os.cpu_count() + 4)) + ) + self.request_hooks = request_hooks or hooks.default_hooks() + self.proxy = proxy if proxy else {} + + def request( + self, + method: str, + url: str, + params: Optional[Dict[str, object]] = None, + data: Optional[Dict[str, object]] = None, + headers: Optional[Dict[str, str]] = None, + auth: Optional[Tuple[str, str]] = None, + timeout: Optional[float] = None, + allow_redirects: bool = False, + ) -> Response: + """ + Make an HTTP Request with parameters provided. + + :param method: The HTTP method to use + :param url: The URL to request + :param params: Query parameters to append to the URL + :param data: Parameters to go in the body of the HTTP request + :param headers: HTTP Headers to send with the request + :param auth: Basic Auth arguments + :param timeout: Socket/Read timeout for the request + :param allow_redirects: Whether to allow redirects + See the requests documentation for explanation of all these parameters + + :return: An HTTP response + """ + if timeout is None: + timeout = self.timeout + elif timeout <= 0: + raise ValueError(timeout) + + kwargs = { + "method": method.upper(), + "url": url, + "params": params, + "headers": headers, + "auth": auth, + "hooks": self.request_hooks, + } + if headers and headers.get("Content-Type") == "application/json": + kwargs["json"] = data + elif headers and headers.get("Content-Type") == "application/scim+json": + kwargs["json"] = data + else: + kwargs["data"] = data + self.log_request(kwargs) + self._test_only_last_response = None + session = self.session or Session() + request = Request(**kwargs) + self._test_only_last_request = TwilioRequest(**kwargs) + + prepped_request = session.prepare_request(request) + + settings = session.merge_environment_settings( + prepped_request.url, self.proxy, None, None, None + ) + response = session.send( + prepped_request, + allow_redirects=allow_redirects, + timeout=timeout, + **settings, + ) + + self.log_response(response.status_code, response) + + self._test_only_last_response = Response( + int(response.status_code), response.text, response.headers + ) + + return self._test_only_last_response diff --git a/twilio/http/orgs_token_manager.py b/twilio/http/orgs_token_manager.py new file mode 100644 index 0000000000..76fad5213f --- /dev/null +++ b/twilio/http/orgs_token_manager.py @@ -0,0 +1,41 @@ +from twilio.http.token_manager import TokenManager +from twilio.rest import Client + + +class OrgTokenManager(TokenManager): + """ + Orgs Token Manager + """ + + def __init__( + self, + grant_type: str, + client_id: str, + client_secret: str, + code: str = None, + redirect_uri: str = None, + audience: str = None, + refreshToken: str = None, + scope: str = None, + ): + self.grant_type = grant_type + self.client_id = client_id + self.client_secret = client_secret + self.code = code + self.redirect_uri = redirect_uri + self.audience = audience + self.refreshToken = refreshToken + self.scope = scope + self.client = Client() + + def fetch_access_token(self): + token_instance = self.client.iam.v1.token.create( + grant_type=self.grant_type, + client_id=self.client_id, + client_secret=self.client_secret, + code=self.code, + redirect_uri=self.redirect_uri, + audience=self.audience, + scope=self.scope, + ) + return token_instance.access_token diff --git a/twilio/http/request.py b/twilio/http/request.py new file mode 100644 index 0000000000..e75cf12b0d --- /dev/null +++ b/twilio/http/request.py @@ -0,0 +1,91 @@ +from enum import Enum +from typing import Any, Dict, Tuple, Union +from urllib.parse import urlencode + + +class Match(Enum): + ANY = "*" + + +class Request(object): + """ + An HTTP request. + """ + + def __init__( + self, + method: Union[str, Match] = Match.ANY, + url: Union[str, Match] = Match.ANY, + auth: Union[Tuple[str, str], Match] = Match.ANY, + params: Union[Dict[str, str], Match] = Match.ANY, + data: Union[Dict[str, str], Match] = Match.ANY, + headers: Union[Dict[str, str], Match] = Match.ANY, + **kwargs: Any + ): + self.method = method + if method and method is not Match.ANY: + self.method = method.upper() + self.url = url + self.auth = auth + self.params = params + self.data = data + self.headers = headers + + @classmethod + def attribute_equal(cls, lhs, rhs) -> bool: + if lhs == Match.ANY or rhs == Match.ANY: + # ANY matches everything + return True + + lhs = lhs or None + rhs = rhs or None + + return lhs == rhs + + def __eq__(self, other) -> bool: + if not isinstance(other, Request): + return False + + return ( + self.attribute_equal(self.method, other.method) + and self.attribute_equal(self.url, other.url) + and self.attribute_equal(self.auth, other.auth) + and self.attribute_equal(self.params, other.params) + and self.attribute_equal(self.data, other.data) + and self.attribute_equal(self.headers, other.headers) + ) + + def __str__(self) -> str: + auth = "" + if self.auth and self.auth != Match.ANY: + auth = "{} ".format(self.auth) + + params = "" + if self.params and self.params != Match.ANY: + params = "?{}".format(urlencode(self.params, doseq=True)) + + data = "" + if self.data and self.data != Match.ANY: + if self.method == "GET": + data = "\n -G" + data += "\n{}".format( + "\n".join(' -d "{}={}"'.format(k, v) for k, v in self.data.items()) + ) + + headers = "" + if self.headers and self.headers != Match.ANY: + headers = "\n{}".format( + "\n".join(' -H "{}: {}"'.format(k, v) for k, v in self.headers.items()) + ) + + return "{auth}{method} {url}{params}{data}{headers}".format( + auth=auth, + method=self.method, + url=self.url, + params=params, + data=data, + headers=headers, + ) + + def __repr__(self) -> str: + return str(self) diff --git a/twilio/http/response.py b/twilio/http/response.py new file mode 100644 index 0000000000..af5a3b1706 --- /dev/null +++ b/twilio/http/response.py @@ -0,0 +1,22 @@ +from typing import Any, Optional + + +class Response(object): + def __init__( + self, + status_code: int, + text: str, + headers: Optional[Any] = None, + ): + self.content = text + self.headers = headers + self.cached = False + self.status_code = status_code + self.ok = self.status_code < 400 + + @property + def text(self) -> str: + return self.content + + def __repr__(self) -> str: + return "HTTP {} {}".format(self.status_code, self.content) diff --git a/twilio/http/token_manager.py b/twilio/http/token_manager.py new file mode 100644 index 0000000000..28cc731019 --- /dev/null +++ b/twilio/http/token_manager.py @@ -0,0 +1,7 @@ +from twilio.base.version import Version + + +class TokenManager: + + def fetch_access_token(self, version: Version): + pass diff --git a/twilio/http/validation_client.py b/twilio/http/validation_client.py new file mode 100644 index 0000000000..1a4a83f0a5 --- /dev/null +++ b/twilio/http/validation_client.py @@ -0,0 +1,138 @@ +from collections import namedtuple + +from requests import Request, Session + +from twilio.base.exceptions import TwilioRestException +from urllib.parse import urlparse +from twilio.http import HttpClient +from twilio.http.response import Response +from twilio.jwt.validation import ClientValidationJwt + + +ValidationPayload = namedtuple( + "ValidationPayload", + ["method", "path", "query_string", "all_headers", "signed_headers", "body"], +) + + +class ValidationClient(HttpClient): + __SIGNED_HEADERS = ["authorization", "host"] + + def __init__( + self, + account_sid, + api_key_sid, + credential_sid, + private_key, + pool_connections=True, + ): + """ + Build a ValidationClient which signs requests with private_key and allows Twilio to + validate request has not been tampered with. + + :param str account_sid: A Twilio Account Sid starting with 'AC' + :param str api_key_sid: A Twilio API Key Sid starting with 'SK' + :param str credential_sid: A Credential Sid starting with 'CR', + corresponds to public key Twilio will use to verify the JWT. + :param str private_key: The private key used to sign the Client Validation JWT. + """ + self.account_sid = account_sid + self.credential_sid = credential_sid + self.api_key_sid = api_key_sid + self.private_key = private_key + self.session = Session() if pool_connections else None + + def request( + self, + method, + url, + params=None, + data=None, + headers=None, + auth=None, + timeout=None, + allow_redirects=False, + ): + """ + Make a signed HTTP Request + + :param str method: The HTTP method to use + :param str url: The URL to request + :param dict params: Query parameters to append to the URL + :param dict data: Parameters to go in the body of the HTTP request + :param dict headers: HTTP Headers to send with the request + :param tuple auth: Basic Auth arguments + :param float timeout: Socket/Read timeout for the request + :param boolean allow_redirects: Whether or not to allow redirects + See the requests documentation for explanation of all these parameters + + :return: An http response + :rtype: A :class:`Response <twilio.rest.http.response.Response>` object + """ + session = self.session or Session() + request = Request( + method.upper(), url, params=params, data=data, headers=headers, auth=auth + ) + prepared_request = session.prepare_request(request) + + if ( + "Host" not in prepared_request.headers + and "host" not in prepared_request.headers + ): + prepared_request.headers["Host"] = self._get_host(prepared_request) + + validation_payload = self._build_validation_payload(prepared_request) + jwt = ClientValidationJwt( + self.account_sid, + self.api_key_sid, + self.credential_sid, + self.private_key, + validation_payload, + ) + prepared_request.headers["Twilio-Client-Validation"] = jwt.to_jwt() + + response = session.send( + prepared_request, + allow_redirects=allow_redirects, + timeout=timeout, + ) + + return Response(int(response.status_code), response.text) + + def _build_validation_payload(self, request): + """ + Extract relevant information from request to build a ClientValidationJWT + :param PreparedRequest request: request we will extract information from. + :return: ValidationPayload + """ + parsed = urlparse(request.url) + path = parsed.path + query_string = parsed.query or "" + + return ValidationPayload( + method=request.method, + path=path, + query_string=query_string, + all_headers=request.headers, + signed_headers=ValidationClient.__SIGNED_HEADERS, + body=request.body or "", + ) + + def _get_host(self, request): + """Pull the Host out of the request""" + parsed = urlparse(request.url) + return str(parsed.netloc) + + def validate_ssl_certificate(self, client): + """ + Validate that a request to the new SSL certificate is successful + :return: null on success, raise TwilioRestException if the request fails + """ + response = client.request("GET", "https://tls-test.twilio.com:443") + + if response.status_code < 200 or response.status_code >= 300: + raise TwilioRestException( + response.status_code, + "https://tls-test.twilio.com:443", + "Failed to validate SSL certificate", + ) diff --git a/twilio/jwt/__init__.py b/twilio/jwt/__init__.py index edb4062433..7a51ea70d5 100644 --- a/twilio/jwt/__init__.py +++ b/twilio/jwt/__init__.py @@ -1,79 +1,161 @@ -""" JSON Web Token implementation +import jwt as jwt_lib +import time -Minimum implementation based on this spec: -http://self-issued.info/docs/draft-jones-json-web-token-01.html -""" -import base64 -import hashlib -import hmac -from six import text_type, b +__all__ = ["Jwt", "JwtDecodeError"] -# default text to binary representation conversion -def binary(txt): - return txt.encode('utf-8') -try: - import json -except ImportError: - import simplejson as json - - -__all__ = ['encode', 'decode', 'DecodeError'] +class JwtDecodeError(Exception): + pass -class DecodeError(Exception): - pass +class Jwt(object): + """Base class for building a Json Web Token""" + + GENERATE = object() + ALGORITHM = "HS256" + + def __init__( + self, + secret_key, + issuer, + subject=None, + algorithm=None, + nbf=GENERATE, + ttl=3600, + valid_until=None, + ): + self.secret_key = secret_key + """:type str: The secret used to encode the JWT""" + self.issuer = issuer + """:type str: The issuer of this JWT""" + self.subject = subject + """:type str: The subject of this JWT, omitted from payload by default""" + self.algorithm = algorithm or self.ALGORITHM + """:type str: The algorithm used to encode the JWT, defaults to 'HS256'""" + self.nbf = nbf + """:type int: Time in secs since epoch before which this JWT is invalid. Defaults to now.""" + self.ttl = ttl + """:type int: Time to live of the JWT in seconds, defaults to 1 hour""" + self.valid_until = valid_until + """:type int: Time in secs since epoch this JWT is valid for. Overrides ttl if provided.""" + + self.__decoded_payload = None + self.__decoded_headers = None + + def _generate_payload(self): + """:rtype: dict the payload of the JWT to send""" + raise NotImplementedError("Subclass must provide a payload.") + + def _generate_headers(self): + """:rtype dict: Additional headers to include in the JWT, defaults to an empty dict""" + return {} + + @classmethod + def _from_jwt(cls, headers, payload, key=None): + """ + Class specific implementation of from_jwt which should take jwt components and return + and instance of this Class with jwt information loaded. + :return: Jwt object containing the headers, payload and key + """ + jwt = Jwt( + secret_key=key, + issuer=payload.get("iss", None), + subject=payload.get("sub", None), + algorithm=headers.get("alg", None), + valid_until=payload.get("exp", None), + nbf=payload.get("nbf", None), + ) + jwt.__decoded_payload = payload + jwt.__decoded_headers = headers + return jwt + + @property + def payload(self): + if self.__decoded_payload: + return self.__decoded_payload + + payload = self._generate_payload().copy() + payload["iss"] = self.issuer + payload["exp"] = int(time.time()) + self.ttl + if self.nbf is not None: + if self.nbf == self.GENERATE: + payload["nbf"] = int(time.time()) + else: + payload["nbf"] = self.nbf + if self.valid_until: + payload["exp"] = self.valid_until + if self.subject: + payload["sub"] = self.subject + + return payload + + @property + def headers(self): + if self.__decoded_headers: + return self.__decoded_headers + + headers = self._generate_headers().copy() + headers["typ"] = "JWT" + headers["alg"] = self.algorithm + return headers + + def to_jwt(self, ttl=None): + """ + Encode this JWT object into a JWT string + :param int ttl: override the ttl configured in the constructor + :rtype: str The JWT string + """ + + if not self.secret_key: + raise ValueError("JWT does not have a signing key configured.") + + headers = self.headers.copy() + + payload = self.payload.copy() + if ttl: + payload["exp"] = int(time.time()) + ttl + + return jwt_lib.encode( + payload, self.secret_key, algorithm=self.algorithm, headers=headers + ) + + @classmethod + def from_jwt(cls, jwt, key=""): + """ + Decode a JWT string into a Jwt object + :param str jwt: JWT string + :param Optional[str] key: key used to verify JWT signature, if not provided then validation + is skipped. + :raises JwtDecodeError if decoding JWT fails for any reason. + :return: A DecodedJwt object containing the jwt information. + """ + verify = True if key else False -signing_methods = { - 'HS256': lambda msg, key: hmac.new(key, msg, hashlib.sha256).digest(), - 'HS384': lambda msg, key: hmac.new(key, msg, hashlib.sha384).digest(), - 'HS512': lambda msg, key: hmac.new(key, msg, hashlib.sha512).digest(), -} - - -def base64url_decode(input): - input += b('=') * (4 - (len(input) % 4)) - return base64.urlsafe_b64decode(input) - - -def base64url_encode(input): - return base64.urlsafe_b64encode(input).decode('utf-8').replace('=', '') - - -def encode(payload, key, algorithm='HS256'): - segments = [] - header = {"typ": "JWT", "alg": algorithm} - segments.append(base64url_encode(binary(json.dumps(header)))) - segments.append(base64url_encode(binary(json.dumps(payload)))) - sign_input = '.'.join(segments) - try: - signature = signing_methods[algorithm](binary(sign_input), binary(key)) - except KeyError: - raise NotImplementedError("Algorithm not supported") - segments.append(base64url_encode(signature)) - return '.'.join(segments) - - -def decode(jwt, key='', verify=True): - try: - signing_input, crypto_segment = jwt.rsplit('.', 1) - header_segment, payload_segment = signing_input.split('.', 1) - except ValueError: - raise DecodeError("Not enough segments") - try: - header_raw = base64url_decode(binary(header_segment)).decode('utf-8') - payload_raw = base64url_decode(binary(payload_segment)).decode('utf-8') - header = json.loads(header_raw) - payload = json.loads(payload_raw) - signature = base64url_decode(binary(crypto_segment)) - except (ValueError, TypeError): - raise DecodeError("Invalid segment encoding") - if verify: try: - method = signing_methods[header['alg']] - if not signature == method(binary(signing_input), binary(key)): - raise DecodeError("Signature verification failed") - except KeyError: - raise DecodeError("Algorithm not supported") - return payload + headers = jwt_lib.get_unverified_header(jwt) + + alg = headers.get("alg") + if alg != cls.ALGORITHM: + raise ValueError( + f"Incorrect decoding algorithm {alg}, " + f"expecting {cls.ALGORITHM}." + ) + + payload = jwt_lib.decode( + jwt, + key, + algorithms=[cls.ALGORITHM], + options={ + "verify_signature": verify, + "verify_exp": True, + "verify_nbf": True, + }, + ) + except Exception as e: + raise JwtDecodeError(getattr(e, "message", str(e))) + + return cls._from_jwt(headers, payload, key) + + def __str__(self): + return "<JWT {}>".format(self.to_jwt()) diff --git a/twilio/jwt/access_token/__init__.py b/twilio/jwt/access_token/__init__.py new file mode 100644 index 0000000000..764b2a028c --- /dev/null +++ b/twilio/jwt/access_token/__init__.py @@ -0,0 +1,81 @@ +import time + +from twilio.jwt import Jwt + + +class AccessTokenGrant(object): + """A Grant giving access to a Twilio Resource""" + + @property + def key(self): + """:rtype str Grant's twilio specific key""" + raise NotImplementedError("Grant must have a key property.") + + def to_payload(self): + """:return: dict something""" + raise NotImplementedError("Grant must implement to_payload.") + + def __str__(self): + return "<{} {}>".format(self.__class__.__name__, self.to_payload()) + + +class AccessToken(Jwt): + """Access Token containing one or more AccessTokenGrants used to access Twilio Resources""" + + ALGORITHM = "HS256" + + def __init__( + self, + account_sid, + signing_key_sid, + secret, + grants=None, + identity=None, + nbf=Jwt.GENERATE, + ttl=3600, + valid_until=None, + region=None, + ): + grants = grants or [] + if any(not isinstance(g, AccessTokenGrant) for g in grants): + raise ValueError("Grants must be instances of AccessTokenGrant.") + + self.account_sid = account_sid + self.signing_key_sid = signing_key_sid + self.identity = identity + self.region = region + self.grants = grants + super(AccessToken, self).__init__( + secret_key=secret, + algorithm=self.ALGORITHM, + issuer=signing_key_sid, + subject=self.account_sid, + nbf=nbf, + ttl=ttl, + valid_until=valid_until, + ) + + def add_grant(self, grant): + """Add a grant to this AccessToken""" + if not isinstance(grant, AccessTokenGrant): + raise ValueError("Grant must be an instance of AccessTokenGrant.") + self.grants.append(grant) + + def _generate_headers(self): + headers = {"cty": "twilio-fpa;v=1"} + if self.region and isinstance(self.region, str): + headers["twr"] = self.region + return headers + + def _generate_payload(self): + now = int(time.time()) + payload = { + "jti": "{}-{}".format(self.signing_key_sid, now), + "grants": {grant.key: grant.to_payload() for grant in self.grants}, + } + if self.identity: + payload["grants"]["identity"] = self.identity + return payload + + def __str__(self): + return "<{} {}>".format(self.__class__.__name__, self.to_jwt()) diff --git a/twilio/jwt/access_token/grants.py b/twilio/jwt/access_token/grants.py new file mode 100644 index 0000000000..16d19aa383 --- /dev/null +++ b/twilio/jwt/access_token/grants.py @@ -0,0 +1,183 @@ +from twilio.jwt.access_token import AccessTokenGrant +import warnings +import functools + + +def deprecated(func): + """This is a decorator which can be used to mark functions + as deprecated. It will result in a warning being emitted + when the function is used.""" + + @functools.wraps(func) + def new_func(*args, **kwargs): + warnings.simplefilter("always", DeprecationWarning) + warnings.warn( + "Call to deprecated function {}.".format(func.__name__), + category=DeprecationWarning, + stacklevel=2, + ) + warnings.simplefilter("default", DeprecationWarning) + return func(*args, **kwargs) + + return new_func + + +class ChatGrant(AccessTokenGrant): + """Grant to access Twilio Chat""" + + def __init__( + self, + service_sid=None, + endpoint_id=None, + deployment_role_sid=None, + push_credential_sid=None, + ): + self.service_sid = service_sid + self.endpoint_id = endpoint_id + self.deployment_role_sid = deployment_role_sid + self.push_credential_sid = push_credential_sid + + @property + def key(self): + return "chat" + + def to_payload(self): + grant = {} + if self.service_sid: + grant["service_sid"] = self.service_sid + if self.endpoint_id: + grant["endpoint_id"] = self.endpoint_id + if self.deployment_role_sid: + grant["deployment_role_sid"] = self.deployment_role_sid + if self.push_credential_sid: + grant["push_credential_sid"] = self.push_credential_sid + + return grant + + +class SyncGrant(AccessTokenGrant): + """Grant to access Twilio Sync""" + + def __init__(self, service_sid=None, endpoint_id=None): + self.service_sid = service_sid + self.endpoint_id = endpoint_id + + @property + def key(self): + return "data_sync" + + def to_payload(self): + grant = {} + if self.service_sid: + grant["service_sid"] = self.service_sid + if self.endpoint_id: + grant["endpoint_id"] = self.endpoint_id + + return grant + + +class VoiceGrant(AccessTokenGrant): + """Grant to access Twilio Programmable Voice""" + + def __init__( + self, + incoming_allow=None, + outgoing_application_sid=None, + outgoing_application_params=None, + push_credential_sid=None, + endpoint_id=None, + ): + self.incoming_allow = incoming_allow + """ :type : bool """ + self.outgoing_application_sid = outgoing_application_sid + """ :type : str """ + self.outgoing_application_params = outgoing_application_params + """ :type : dict """ + self.push_credential_sid = push_credential_sid + """ :type : str """ + self.endpoint_id = endpoint_id + """ :type : str """ + + @property + def key(self): + return "voice" + + def to_payload(self): + grant = {} + if self.incoming_allow is True: + grant["incoming"] = {} + grant["incoming"]["allow"] = True + + if self.outgoing_application_sid: + grant["outgoing"] = {} + grant["outgoing"]["application_sid"] = self.outgoing_application_sid + + if self.outgoing_application_params: + grant["outgoing"]["params"] = self.outgoing_application_params + + if self.push_credential_sid: + grant["push_credential_sid"] = self.push_credential_sid + + if self.endpoint_id: + grant["endpoint_id"] = self.endpoint_id + + return grant + + +class VideoGrant(AccessTokenGrant): + """Grant to access Twilio Video""" + + def __init__(self, room=None): + self.room = room + + @property + def key(self): + return "video" + + def to_payload(self): + grant = {} + if self.room: + grant["room"] = self.room + + return grant + + +class TaskRouterGrant(AccessTokenGrant): + """Grant to access Twilio TaskRouter""" + + def __init__(self, workspace_sid=None, worker_sid=None, role=None): + self.workspace_sid = workspace_sid + self.worker_sid = worker_sid + self.role = role + + @property + def key(self): + return "task_router" + + def to_payload(self): + grant = {} + if self.workspace_sid: + grant["workspace_sid"] = self.workspace_sid + if self.worker_sid: + grant["worker_sid"] = self.worker_sid + if self.role: + grant["role"] = self.role + + return grant + + +class PlaybackGrant(AccessTokenGrant): + """Grant to access Twilio Live stream""" + + def __init__(self, grant=None): + """Initialize a PlaybackGrant with a grant retrieved from the Twilio API.""" + self.grant = grant + + @property + def key(self): + """Return the grant's key.""" + return "player" + + def to_payload(self): + """Return the grant.""" + return self.grant diff --git a/twilio/jwt/client/__init__.py b/twilio/jwt/client/__init__.py new file mode 100644 index 0000000000..d5c38c4729 --- /dev/null +++ b/twilio/jwt/client/__init__.py @@ -0,0 +1,117 @@ +from twilio.jwt import Jwt + +from urllib.parse import urlencode + + +class ClientCapabilityToken(Jwt): + """A token to control permissions with Twilio Client""" + + ALGORITHM = "HS256" + + def __init__( + self, + account_sid, + auth_token, + nbf=Jwt.GENERATE, + ttl=3600, + valid_until=None, + **kwargs + ): + """ + :param str account_sid: The account sid to which this token is granted access. + :param str auth_token: The secret key used to sign the token. Note, this auth token is not + visible to the user of the token. + :param int nbf: Time in secs from epic before which this token is considered invalid. + :param int ttl: the amount of time in seconds from generation that this token is valid for. + :param kwargs: + + + :returns: A new CapabilityToken with zero permissions + """ + super(ClientCapabilityToken, self).__init__( + algorithm=self.ALGORITHM, + secret_key=auth_token, + issuer=account_sid, + nbf=nbf, + ttl=ttl, + valid_until=None, + ) + + self.account_sid = account_sid + self.auth_token = auth_token + self.client_name = None + self.capabilities = {} + + if "allow_client_outgoing" in kwargs: + self.allow_client_outgoing(**kwargs["allow_client_outgoing"]) + if "allow_client_incoming" in kwargs: + self.allow_client_incoming(**kwargs["allow_client_incoming"]) + if "allow_event_stream" in kwargs: + self.allow_event_stream(**kwargs["allow_event_stream"]) + + def allow_client_outgoing(self, application_sid, **kwargs): + """ + Allow the user of this token to make outgoing connections. Keyword arguments are passed + to the application. + + :param str application_sid: Application to contact + """ + scope = ScopeURI("client", "outgoing", {"appSid": application_sid}) + if kwargs: + scope.add_param("appParams", urlencode(kwargs, doseq=True)) + + self.capabilities["outgoing"] = scope + + def allow_client_incoming(self, client_name): + """ + Allow the user of this token to accept incoming connections. + + :param str client_name: Client name to accept calls from + """ + self.client_name = client_name + self.capabilities["incoming"] = ScopeURI( + "client", "incoming", {"clientName": client_name} + ) + + def allow_event_stream(self, **kwargs): + """ + Allow the user of this token to access their event stream. + """ + scope = ScopeURI("stream", "subscribe", {"path": "/2010-04-01/Events"}) + if kwargs: + scope.add_param("params", urlencode(kwargs, doseq=True)) + + self.capabilities["events"] = scope + + def _generate_payload(self): + if "outgoing" in self.capabilities and self.client_name is not None: + self.capabilities["outgoing"].add_param("clientName", self.client_name) + + scope_uris = [ + scope_uri.to_payload() for scope_uri in self.capabilities.values() + ] + return {"scope": " ".join(scope_uris)} + + +class ScopeURI(object): + """A single capability granted to Twilio Client and scoped to a service""" + + def __init__(self, service, privilege, params=None): + self.service = service + self.privilege = privilege + self.params = params or {} + + def add_param(self, key, value): + self.params[key] = value + + def to_payload(self): + if self.params: + sorted_params = sorted([(k, v) for k, v in self.params.items()]) + encoded_params = urlencode(sorted_params) + param_string = "?{}".format(encoded_params) + else: + param_string = "" + return "scope:{}:{}{}".format(self.service, self.privilege, param_string) + + def __str__(self): + return "<ScopeURI {}>".format(self.to_payload()) diff --git a/twilio/jwt/taskrouter/__init__.py b/twilio/jwt/taskrouter/__init__.py new file mode 100644 index 0000000000..5a01560dfa --- /dev/null +++ b/twilio/jwt/taskrouter/__init__.py @@ -0,0 +1,142 @@ +from twilio.jwt import Jwt + + +class TaskRouterCapabilityToken(Jwt): + VERSION = "v1" + DOMAIN = "https://taskrouter.twilio.com" + EVENTS_BASE_URL = "https://event-bridge.twilio.com/v1/wschannels" + ALGORITHM = "HS256" + + def __init__(self, account_sid, auth_token, workspace_sid, channel_id, **kwargs): + """ + :param str account_sid: Twilio account sid + :param str auth_token: Twilio auth token used to sign the JWT + :param str workspace_sid: TaskRouter workspace sid + :param str channel_id: TaskRouter channel sid + :param kwargs: + :param bool allow_web_sockets: shortcut to calling allow_web_sockets, defaults to True + :param bool allow_fetch_self: shortcut to calling allow_fetch_self, defaults to True + :param bool allow_update_self: shortcut to calling allow_update_self, defaults to False + :param bool allow_delete_self: shortcut to calling allow_delete_self, defaults to False + :param bool allow_fetch_subresources: shortcut to calling allow_fetch_subresources, + defaults to False + :param bool allow_update_subresources: shortcut to calling allow_update_subresources, + defaults to False + :param bool allow_delete_subresources: shortcut to calling allow_delete_subresources, + defaults to False + :returns a new TaskRouterCapabilityToken with capabilities set depending on kwargs. + """ + super(TaskRouterCapabilityToken, self).__init__( + secret_key=auth_token, + issuer=account_sid, + algorithm=self.ALGORITHM, + nbf=kwargs.get("nbf", Jwt.GENERATE), + ttl=kwargs.get("ttl", 3600), + valid_until=kwargs.get("valid_until", None), + ) + + self._validate_inputs(account_sid, workspace_sid, channel_id) + + self.account_sid = account_sid + self.auth_token = auth_token + self.workspace_sid = workspace_sid + self.channel_id = channel_id + self.policies = [] + + if kwargs.get("allow_web_sockets", True): + self.allow_web_sockets() + if kwargs.get("allow_fetch_self", True): + self.allow_fetch_self() + if kwargs.get("allow_update_self", False): + self.allow_update_self() + if kwargs.get("allow_delete_self", False): + self.allow_delete_self() + if kwargs.get("allow_fetch_subresources", False): + self.allow_fetch_subresources() + if kwargs.get("allow_delete_subresources", False): + self.allow_delete_subresources() + if kwargs.get("allow_update_subresources", False): + self.allow_update_subresources() + + @property + def workspace_url(self): + return "{}/{}/Workspaces/{}".format( + self.DOMAIN, self.VERSION, self.workspace_sid + ) + + @property + def resource_url(self): + raise NotImplementedError("Subclass must set its specific resource_url.") + + @property + def channel_prefix(self): + raise NotImplementedError( + "Subclass must set its specific channel_id sid prefix." + ) + + def allow_fetch_self(self): + self._make_policy(self.resource_url, "GET", True) + + def allow_update_self(self): + self._make_policy(self.resource_url, "POST", True) + + def allow_delete_self(self): + self._make_policy(self.resource_url, "DELETE", True) + + def allow_fetch_subresources(self): + self._make_policy(self.resource_url + "/**", "GET", True) + + def allow_update_subresources(self): + self._make_policy(self.resource_url + "/**", "POST", True) + + def allow_delete_subresources(self): + self._make_policy(self.resource_url + "/**", "DELETE", True) + + def allow_web_sockets(self, channel_id=None): + channel_id = channel_id or self.channel_id + web_socket_url = "{}/{}/{}".format( + self.EVENTS_BASE_URL, self.account_sid, channel_id + ) + self._make_policy(web_socket_url, "GET", True) + self._make_policy(web_socket_url, "POST", True) + + def _generate_payload(self): + payload = { + "account_sid": self.account_sid, + "workspace_sid": self.workspace_sid, + "channel": self.channel_id, + "version": self.VERSION, + "friendly_name": self.channel_id, + "policies": self.policies, + } + + if self.channel_id.startswith("WK"): + payload["worker_sid"] = self.channel_id + elif self.channel_id.startswith("WQ"): + payload["taskqueue_sid"] = self.channel_id + + return payload + + def _make_policy(self, url, method, allowed, query_filter=None, post_filter=None): + self.policies.append( + { + "url": url, + "method": method.upper(), + "allow": allowed, + "query_filter": query_filter or {}, + "post_filter": post_filter or {}, + } + ) + + def _validate_inputs(self, account_sid, workspace_sid, channel_id): + if not account_sid or not account_sid.startswith("AC"): + raise ValueError("Invalid account sid provided {}".format(account_sid)) + + if not workspace_sid or not workspace_sid.startswith("WS"): + raise ValueError("Invalid workspace sid provided {}".format(workspace_sid)) + + if not channel_id or not channel_id.startswith(self.channel_prefix): + raise ValueError("Invalid channel id provided {}".format(channel_id)) + + def __str__(self): + return "<TaskRouterCapabilityToken {}>".format(self.to_jwt()) diff --git a/twilio/jwt/taskrouter/capabilities.py b/twilio/jwt/taskrouter/capabilities.py new file mode 100644 index 0000000000..468a027016 --- /dev/null +++ b/twilio/jwt/taskrouter/capabilities.py @@ -0,0 +1,116 @@ +from twilio.jwt.taskrouter import TaskRouterCapabilityToken + + +class WorkerCapabilityToken(TaskRouterCapabilityToken): + def __init__( + self, account_sid, auth_token, workspace_sid, worker_sid, ttl=3600, **kwargs + ): + """ + :param kwargs: + All kwarg parameters supported by TaskRouterCapabilityToken + :param bool allow_fetch_activities: shortcut to calling allow_fetch_activities, + defaults to True + :param bool allow_fetch_reservations: shortcut to calling allow_fetch_reservations, + defaults to True + :param bool allow_fetch_worker_reservations: shortcut to calling allow_fetch_worker_reservations, + defaults to True + :param bool allow_update_activities: shortcut to calling allow_update_activities, + defaults to False + :param bool allow_update_reservations: shortcut to calling allow_update_reservations, + defaults to False + """ + super(WorkerCapabilityToken, self).__init__( + account_sid=account_sid, + auth_token=auth_token, + workspace_sid=workspace_sid, + channel_id=worker_sid, + ttl=ttl, + **kwargs + ) + + if kwargs.get("allow_fetch_activities", True): + self.allow_fetch_activities() + if kwargs.get("allow_fetch_reservations", True): + self.allow_fetch_reservations() + if kwargs.get("allow_fetch_worker_reservations", True): + self.allow_fetch_worker_reservations() + if kwargs.get("allow_update_activities", False): + self.allow_update_activities() + if kwargs.get("allow_update_reservations", False): + self.allow_update_reservations() + + @property + def resource_url(self): + return "{}/Workers/{}".format(self.workspace_url, self.channel_id) + + @property + def channel_prefix(self): + return "WK" + + def allow_fetch_activities(self): + self._make_policy(self.workspace_url + "/Activities", "GET", True) + + def allow_fetch_reservations(self): + self._make_policy(self.workspace_url + "/Tasks/**", "GET", True) + + def allow_fetch_worker_reservations(self): + self._make_policy(self.resource_url + "/Reservations/**", "GET", True) + + def allow_update_activities(self): + post_filter = {"ActivitySid": {"required": True}} + self._make_policy(self.resource_url, "POST", True, post_filter=post_filter) + + def allow_update_reservations(self): + self._make_policy(self.workspace_url + "/Tasks/**", "POST", True) + self._make_policy(self.resource_url + "/Reservations/**", "POST", True) + + def __str__(self): + return "<WorkerCapabilityToken {}>".format(self.to_jwt()) + + +class TaskQueueCapabilityToken(TaskRouterCapabilityToken): + def __init__( + self, account_sid, auth_token, workspace_sid, task_queue_sid, ttl=3600, **kwargs + ): + super(TaskQueueCapabilityToken, self).__init__( + account_sid=account_sid, + auth_token=auth_token, + workspace_sid=workspace_sid, + channel_id=task_queue_sid, + ttl=ttl, + **kwargs + ) + + @property + def resource_url(self): + return "{}/TaskQueues/{}".format(self.workspace_url, self.channel_id) + + @property + def channel_prefix(self): + return "WQ" + + def __str__(self): + return "<TaskQueueCapabilityToken {}>".format(self.to_jwt()) + + +class WorkspaceCapabilityToken(TaskRouterCapabilityToken): + def __init__(self, account_sid, auth_token, workspace_sid, ttl=3600, **kwargs): + super(WorkspaceCapabilityToken, self).__init__( + account_sid=account_sid, + auth_token=auth_token, + workspace_sid=workspace_sid, + channel_id=workspace_sid, + ttl=ttl, + **kwargs + ) + + @property + def resource_url(self): + return self.workspace_url + + @property + def channel_prefix(self): + return "WS" + + def __str__(self): + return "<WorkspaceCapabilityToken {}>".format(self.to_jwt()) diff --git a/twilio/jwt/validation/__init__.py b/twilio/jwt/validation/__init__.py new file mode 100644 index 0000000000..837d6196e0 --- /dev/null +++ b/twilio/jwt/validation/__init__.py @@ -0,0 +1,92 @@ +from hashlib import sha256 + +from twilio.jwt import Jwt + + +class ClientValidationJwt(Jwt): + """A JWT included on requests so that Twilio can verify request authenticity""" + + __CTY = "twilio-pkrv;v=1" + ALGORITHM = "RS256" + + def __init__( + self, account_sid, api_key_sid, credential_sid, private_key, validation_payload + ): + """ + Create a new ClientValidationJwt + :param str account_sid: A Twilio Account Sid starting with 'AC' + :param str api_key_sid: A Twilio API Key Sid starting with 'SK' + :param str credential_sid: A Credential Sid starting with 'CR', + public key Twilio will use to verify the JWT. + :param str private_key: The private key used to sign the JWT. + :param ValidationPayload validation_payload: information from the request to sign + """ + super(ClientValidationJwt, self).__init__( + secret_key=private_key, + issuer=api_key_sid, + subject=account_sid, + algorithm=self.ALGORITHM, + ttl=300, # 5 minute ttl + ) + self.credential_sid = credential_sid + self.validation_payload = validation_payload + + def _generate_headers(self): + return {"cty": ClientValidationJwt.__CTY, "kid": self.credential_sid} + + def _generate_payload(self): + # Lowercase header keys, combine and sort headers with list values + all_headers = { + k.lower(): self._sort_and_join(v, ",") + for k, v in self.validation_payload.all_headers.items() + } + # Names of headers we are signing in the jwt + signed_headers = sorted(self.validation_payload.signed_headers) + + # Stringify headers, only include headers in signed_headers + headers_str = [ + "{}:{}".format(h, all_headers[h]) + for h in signed_headers + if h in all_headers + ] + headers_str = "\n".join(headers_str) + + # Sort query string parameters + query_string = self.validation_payload.query_string.split("&") + query_string = self._sort_and_join(query_string, "&") + + req_body_hash = self._hash(self.validation_payload.body) or "" + + signed_headers_str = ";".join(signed_headers) + + signed_payload = [ + self.validation_payload.method, + self.validation_payload.path, + query_string, + ] + + if headers_str: + signed_payload.append(headers_str) + signed_payload.append("") + signed_payload.append(signed_headers_str) + signed_payload.append(req_body_hash) + + signed_payload = "\n".join(signed_payload) + + return {"hrh": signed_headers_str, "rqh": self._hash(signed_payload)} + + @classmethod + def _sort_and_join(cls, values, joiner): + if isinstance(values, str): + return values + return joiner.join(sorted(values)) + + @classmethod + def _hash(cls, input_str): + if not input_str: + return input_str + + if not isinstance(input_str, bytes): + input_str = input_str.encode("utf-8") + + return sha256(input_str).hexdigest() diff --git a/twilio/request_validator.py b/twilio/request_validator.py new file mode 100644 index 0000000000..f7a0db361c --- /dev/null +++ b/twilio/request_validator.py @@ -0,0 +1,137 @@ +import base64 +import hmac +from hashlib import sha1, sha256 + +from urllib.parse import urlparse, parse_qs + + +def compare(string1, string2): + """Compare two strings while protecting against timing attacks + + :param str string1: the first string + :param str string2: the second string + + :returns: True if the strings are equal, False if not + :rtype: :obj:`bool` + """ + if len(string1) != len(string2): + return False + result = True + for c1, c2 in zip(string1, string2): + result &= c1 == c2 + + return result + + +def remove_port(uri): + """Remove the port number from a URI + + :param uri: parsed URI that Twilio requested on your server + + :returns: full URI without a port number + :rtype: str + """ + if not uri.port: + return uri.geturl() + + new_netloc = uri.netloc.split(":")[0] + new_uri = uri._replace(netloc=new_netloc) + + return new_uri.geturl() + + +def add_port(uri): + """Add the port number to a URI + + :param uri: parsed URI that Twilio requested on your server + + :returns: full URI with a port number + :rtype: str + """ + if uri.port: + return uri.geturl() + + port = 443 if uri.scheme == "https" else 80 + new_netloc = uri.netloc + ":" + str(port) + new_uri = uri._replace(netloc=new_netloc) + + return new_uri.geturl() + + +class RequestValidator(object): + def __init__(self, token): + self.token = token.encode("utf-8") + + def compute_signature(self, uri, params): + """Compute the signature for a given request + + :param uri: full URI that Twilio requested on your server + :param params: post vars that Twilio sent with the request + + :returns: The computed signature + """ + s = uri + if params: + for param_name in sorted(set(params)): + values = self.get_values(params, param_name) + + for value in sorted(set(values)): + s += param_name + value + + # compute signature and compare signatures + mac = hmac.new(self.token, s.encode("utf-8"), sha1) + computed = base64.b64encode(mac.digest()) + computed = computed.decode("utf-8") + + return computed.strip() + + def get_values(self, param_dict, param_name): + try: + # Support MultiDict used by Flask. + return param_dict.getall(param_name) + except AttributeError: + try: + # Support QueryDict used by Django. + return param_dict.getlist(param_name) + except AttributeError: + # Fallback to a standard dict. + return [param_dict[param_name]] + + def compute_hash(self, body): + computed = sha256(body.encode("utf-8")).hexdigest() + + return computed.strip() + + def validate(self, uri, params, signature): + """Validate a request from Twilio + + :param uri: full URI that Twilio requested on your server + :param params: dictionary of POST variables or string of POST body for JSON requests + :param signature: expected signature in HTTP X-Twilio-Signature header + + :returns: True if the request passes validation, False if not + """ + if params is None: + params = {} + + parsed_uri = urlparse(uri) + uri_with_port = add_port(parsed_uri) + uri_without_port = remove_port(parsed_uri) + + valid_body_hash = True # May not receive body hash, so default succeed + + query = parse_qs(parsed_uri.query) + if "bodySHA256" in query and isinstance(params, str): + valid_body_hash = compare(self.compute_hash(params), query["bodySHA256"][0]) + params = {} + + # check signature of uri with and without port, + # since sig generation on back end is inconsistent + valid_signature = compare( + self.compute_signature(uri_without_port, params), signature + ) + valid_signature_with_port = compare( + self.compute_signature(uri_with_port, params), signature + ) + + return valid_body_hash and (valid_signature or valid_signature_with_port) diff --git a/twilio/rest/__init__.py b/twilio/rest/__init__.py index f8e0cf0747..823cbbfaa0 100644 --- a/twilio/rest/__init__.py +++ b/twilio/rest/__init__.py @@ -1,151 +1,742 @@ -import logging -import os -from twilio import TwilioException -from twilio.rest.resources import make_request -from twilio.rest.resources import Accounts -from twilio.rest.resources import Applications -from twilio.rest.resources import AuthorizedConnectApps -from twilio.rest.resources import Calls -from twilio.rest.resources import CallerIds -from twilio.rest.resources import Queues -from twilio.rest.resources import Members -from twilio.rest.resources import ConnectApps -from twilio.rest.resources import Notifications -from twilio.rest.resources import Recordings -from twilio.rest.resources import Transcriptions -from twilio.rest.resources import Sms -from twilio.rest.resources import Participants -from twilio.rest.resources import PhoneNumbers -from twilio.rest.resources import Conferences -from twilio.rest.resources import Sandboxes -from twilio.rest.resources import Usage - - -def find_credentials(): - """ - Look in the current environment for Twilio credentails - """ - try: - account = os.environ["TWILIO_ACCOUNT_SID"] - token = os.environ["TWILIO_AUTH_TOKEN"] - return account, token - except KeyError: - return None, None - - -class TwilioRestClient(object): - """ - A client for accessing the Twilio REST API - """ - - def request(self, path, method=None, vars=None): - """sends a request and gets a response from the Twilio REST API - - .. deprecated:: 3.0 - - :param path: the URL (relative to the endpoint URL, after the /v1 - :param url: the HTTP method to use, defaults to POST - :param vars: for POST or PUT, a dict of data to send - - :returns: Twilio response in XML or raises an exception on error - - This method is only included for backwards compatability reasons. - It will be removed in a future version - """ - logging.warning(":meth:`TwilioRestClient.request` is deprecated and " - "will be removed in a future version") - - vars = vars or {} - params = None - data = None - - if not path or len(path) < 1: - raise ValueError('Invalid path parameter') - if method and method not in ['GET', 'POST', 'DELETE', 'PUT']: - raise NotImplementedError( - 'HTTP %s method not implemented' % method) - - if path[0] == '/': - uri = self.base + path - else: - uri = self.base + '/' + path - - if method == "GET": - params = vars - elif method == "POST" or method == "PUT": - data = vars - - headers = { - "User-Agent": "twilio-python", - } - - resp = make_request(method, uri, auth=self.auth, data=data, - params=params, headers=headers) - - return resp.content - - def __init__(self, account=None, token=None, base="https://api.twilio.com", - version="2010-04-01", client=None): - """ - Create a Twilio REST 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 - auth = (account, token) - version_uri = "%s/%s" % (base, version) - account_uri = "%s/%s/Accounts/%s" % (base, version, account) +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - self.accounts = Accounts(version_uri, auth) - self.applications = Applications(account_uri, auth) - self.authorized_connect_apps = AuthorizedConnectApps(account_uri, auth) - self.calls = Calls(account_uri, auth) - self.caller_ids = CallerIds(account_uri, auth) - self.connect_apps = ConnectApps(account_uri, auth) - self.notifications = Notifications(account_uri, auth) - self.recordings = Recordings(account_uri, auth) - self.transcriptions = Transcriptions(account_uri, auth) - self.sms = Sms(account_uri, auth) - self.phone_numbers = PhoneNumbers(account_uri, auth) - self.conferences = Conferences(account_uri, auth) - self.queues = Queues(account_uri, auth) - self.sandboxes = Sandboxes(account_uri, auth) - self.usage = Usage(account_uri, auth) + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" - self.auth = auth - self.account_uri = account_uri +from typing import TYPE_CHECKING, Optional - def participants(self, conference_sid): +from twilio.base.client_base import ClientBase + +if TYPE_CHECKING: + from twilio.rest.accounts import Accounts + from twilio.rest.api import Api + from twilio.rest.assistants import Assistants + from twilio.rest.bulkexports import Bulkexports + from twilio.rest.chat import Chat + from twilio.rest.content import Content + from twilio.rest.conversations import Conversations + from twilio.rest.events import Events + from twilio.rest.flex_api import FlexApi + from twilio.rest.frontline_api import FrontlineApi + from twilio.rest.preview_iam import PreviewIam + from twilio.rest.iam import Iam + from twilio.rest.insights import Insights + from twilio.rest.intelligence import Intelligence + from twilio.rest.ip_messaging import IpMessaging + from twilio.rest.lookups import Lookups + from twilio.rest.marketplace import Marketplace + from twilio.rest.messaging import Messaging + from twilio.rest.monitor import Monitor + from twilio.rest.notify import Notify + from twilio.rest.numbers import Numbers + from twilio.rest.oauth import Oauth + from twilio.rest.preview import Preview + from twilio.rest.pricing import Pricing + from twilio.rest.proxy import Proxy + from twilio.rest.routes import Routes + from twilio.rest.serverless import Serverless + from twilio.rest.studio import Studio + from twilio.rest.supersim import Supersim + from twilio.rest.sync import Sync + from twilio.rest.taskrouter import Taskrouter + from twilio.rest.trunking import Trunking + from twilio.rest.trusthub import Trusthub + from twilio.rest.verify import Verify + from twilio.rest.video import Video + from twilio.rest.voice import Voice + from twilio.rest.wireless import Wireless + from twilio.rest.api.v2010.account.address import AddressList + from twilio.rest.api.v2010.account.application import ApplicationList + from twilio.rest.api.v2010.account.authorized_connect_app import ( + AuthorizedConnectAppList, + ) + from twilio.rest.api.v2010.account.available_phone_number_country import ( + AvailablePhoneNumberCountryList, + ) + from twilio.rest.api.v2010.account.balance import BalanceList + from twilio.rest.api.v2010.account.call import CallList + from twilio.rest.api.v2010.account.conference import ConferenceList + from twilio.rest.api.v2010.account.connect_app import ConnectAppList + from twilio.rest.api.v2010.account.incoming_phone_number import ( + IncomingPhoneNumberList, + ) + from twilio.rest.api.v2010.account.key import KeyList + from twilio.rest.api.v2010.account.new_key import NewKeyList + from twilio.rest.api.v2010.account.message import MessageList + from twilio.rest.api.v2010.account.signing_key import SigningKeyList + from twilio.rest.api.v2010.account.new_signing_key import NewSigningKeyList + from twilio.rest.api.v2010.account.notification import NotificationList + from twilio.rest.api.v2010.account.outgoing_caller_id import OutgoingCallerIdList + from twilio.rest.api.v2010.account.validation_request import ValidationRequestList + from twilio.rest.api.v2010.account.queue import QueueList + from twilio.rest.api.v2010.account.recording import RecordingList + from twilio.rest.api.v2010.account.short_code import ShortCodeList + from twilio.rest.api.v2010.account.sip import SipList + from twilio.rest.api.v2010.account.token import TokenList + from twilio.rest.api.v2010.account.transcription import TranscriptionList + from twilio.rest.api.v2010.account.usage import UsageList + + +class Client(ClientBase): + """A client for accessing the Twilio API.""" + + def __init__( + self, + username=None, + password=None, + account_sid=None, + region=None, + http_client=None, + environment=None, + edge=None, + user_agent_extensions=None, + credential_provider=None, + ): + """ + Initializes the Twilio Client + + :param str username: Username to authenticate with, either account_sid or api_key + :param str password: Password to authenticate with, auth_token (if using account_sid) or api_secret (if using api_key) + :param str account_sid: Account SID, required if using api_key to authenticate. + :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 + :param list[str] user_agent_extensions: Additions to the user agent string + + :returns: Twilio Client + :rtype: twilio.rest.Client + """ + super().__init__( + username, + password, + account_sid, + region, + http_client, + environment, + edge, + user_agent_extensions, + credential_provider, + ) + + # Domains + self._accounts: Optional["Accounts"] = None + self._api: Optional["Api"] = None + self._assistants: Optional["Assistants"] = None + self._bulkexports: Optional["Bulkexports"] = None + self._chat: Optional["Chat"] = None + self._content: Optional["Content"] = None + self._conversations: Optional["Conversations"] = None + self._events: Optional["Events"] = None + self._flex_api: Optional["FlexApi"] = None + self._frontline_api: Optional["FrontlineApi"] = None + self._preview_iam: Optional["PreviewIam"] = None + self._iam: Optional["Iam"] = None + self._insights: Optional["Insights"] = None + self._intelligence: Optional["Intelligence"] = None + self._ip_messaging: Optional["IpMessaging"] = None + self._lookups: Optional["Lookups"] = None + self._marketplace: Optional["Marketplace"] = None + self._messaging: Optional["Messaging"] = None + self._monitor: Optional["Monitor"] = None + self._notify: Optional["Notify"] = None + self._numbers: Optional["Numbers"] = None + self._oauth: Optional["Oauth"] = None + self._preview: Optional["Preview"] = None + self._pricing: Optional["Pricing"] = None + self._proxy: Optional["Proxy"] = None + self._routes: Optional["Routes"] = None + self._serverless: Optional["Serverless"] = None + self._studio: Optional["Studio"] = None + self._supersim: Optional["Supersim"] = None + self._sync: Optional["Sync"] = None + self._taskrouter: Optional["Taskrouter"] = None + self._trunking: Optional["Trunking"] = None + self._trusthub: Optional["Trusthub"] = None + self._verify: Optional["Verify"] = None + self._video: Optional["Video"] = None + self._voice: Optional["Voice"] = None + self._wireless: Optional["Wireless"] = None + + @property + def accounts(self) -> "Accounts": + """ + Access the Accounts Twilio Domain + + :returns: Accounts Twilio Domain + """ + if self._accounts is None: + from twilio.rest.accounts import Accounts + + self._accounts = Accounts(self) + return self._accounts + + @property + def api(self) -> "Api": + """ + Access the Api Twilio Domain + + :returns: Api Twilio Domain + """ + if self._api is None: + from twilio.rest.api import Api + + self._api = Api(self) + return self._api + + @property + def assistants(self) -> "Assistants": + """ + Access the Assistants Twilio Domain + + :returns: Assistants Twilio Domain + """ + if self._assistants is None: + from twilio.rest.assistants import Assistants + + self._assistants = Assistants(self) + return self._assistants + + @property + def bulkexports(self) -> "Bulkexports": + """ + Access the Bulkexports Twilio Domain + + :returns: Bulkexports Twilio Domain """ - Return a :class:`Participants` instance for the :class:`Conference` - with the given conference_sid + if self._bulkexports is None: + from twilio.rest.bulkexports import Bulkexports + + self._bulkexports = Bulkexports(self) + return self._bulkexports + + @property + def chat(self) -> "Chat": + """ + Access the Chat Twilio Domain + + :returns: Chat Twilio Domain + """ + if self._chat is None: + from twilio.rest.chat import Chat + + self._chat = Chat(self) + return self._chat + + @property + def content(self) -> "Content": """ - base_uri = "%s/Conferences/%s" % (self.account_uri, conference_sid) - return Participants(base_uri, self.auth) + Access the Content Twilio Domain - def members(self, queue_sid): + :returns: Content Twilio Domain """ - Return a :class:`Members` instance for the :class:`Queue` - with the given queue_sid + if self._content is None: + from twilio.rest.content import Content + + self._content = Content(self) + return self._content + + @property + def conversations(self) -> "Conversations": + """ + Access the Conversations Twilio Domain + + :returns: Conversations Twilio Domain + """ + if self._conversations is None: + from twilio.rest.conversations import Conversations + + self._conversations = Conversations(self) + return self._conversations + + @property + def events(self) -> "Events": """ - base_uri = "%s/Queues/%s" % (self.account_uri, queue_sid) - return Members(base_uri, self.auth) + Access the Events Twilio Domain + + :returns: Events Twilio Domain + """ + if self._events is None: + from twilio.rest.events import Events + + self._events = Events(self) + return self._events + + @property + def flex_api(self) -> "FlexApi": + """ + Access the FlexApi Twilio Domain + + :returns: FlexApi Twilio Domain + """ + if self._flex_api is None: + from twilio.rest.flex_api import FlexApi + + self._flex_api = FlexApi(self) + return self._flex_api + + @property + def frontline_api(self) -> "FrontlineApi": + """ + Access the FrontlineApi Twilio Domain + + :returns: FrontlineApi Twilio Domain + """ + if self._frontline_api is None: + from twilio.rest.frontline_api import FrontlineApi + + self._frontline_api = FrontlineApi(self) + return self._frontline_api + + @property + def preview_iam(self) -> "PreviewIam": + """ + Access the PreviewIam Twilio Domain + + :returns: PreviewIam Twilio Domain + """ + if self._preview_iam is None: + from twilio.rest.preview_iam import PreviewIam + + self._preview_iam = PreviewIam(self) + return self._preview_iam + + @property + def iam(self) -> "Iam": + """ + Access the Iam Twilio Domain + + :returns: Iam Twilio Domain + """ + if self._iam is None: + from twilio.rest.iam import Iam + + self._iam = Iam(self) + return self._iam + + @property + def insights(self) -> "Insights": + """ + Access the Insights Twilio Domain + + :returns: Insights Twilio Domain + """ + if self._insights is None: + from twilio.rest.insights import Insights + + self._insights = Insights(self) + return self._insights + + @property + def intelligence(self) -> "Intelligence": + """ + Access the Intelligence Twilio Domain + + :returns: Intelligence Twilio Domain + """ + if self._intelligence is None: + from twilio.rest.intelligence import Intelligence + + self._intelligence = Intelligence(self) + return self._intelligence + + @property + def ip_messaging(self) -> "IpMessaging": + """ + Access the IpMessaging Twilio Domain + + :returns: IpMessaging Twilio Domain + """ + if self._ip_messaging is None: + from twilio.rest.ip_messaging import IpMessaging + + self._ip_messaging = IpMessaging(self) + return self._ip_messaging + + @property + def lookups(self) -> "Lookups": + """ + Access the Lookups Twilio Domain + + :returns: Lookups Twilio Domain + """ + if self._lookups is None: + from twilio.rest.lookups import Lookups + + self._lookups = Lookups(self) + return self._lookups + + @property + def marketplace(self) -> "Marketplace": + """ + Access the Marketplace Twilio Domain + + :returns: Marketplace Twilio Domain + """ + if self._marketplace is None: + from twilio.rest.marketplace import Marketplace + + self._marketplace = Marketplace(self) + return self._marketplace + + @property + def messaging(self) -> "Messaging": + """ + Access the Messaging Twilio Domain + + :returns: Messaging Twilio Domain + """ + if self._messaging is None: + from twilio.rest.messaging import Messaging + + self._messaging = Messaging(self) + return self._messaging + + @property + def monitor(self) -> "Monitor": + """ + Access the Monitor Twilio Domain + + :returns: Monitor Twilio Domain + """ + if self._monitor is None: + from twilio.rest.monitor import Monitor + + self._monitor = Monitor(self) + return self._monitor + + @property + def notify(self) -> "Notify": + """ + Access the Notify Twilio Domain + + :returns: Notify Twilio Domain + """ + if self._notify is None: + from twilio.rest.notify import Notify + + self._notify = Notify(self) + return self._notify + + @property + def numbers(self) -> "Numbers": + """ + Access the Numbers Twilio Domain + + :returns: Numbers Twilio Domain + """ + if self._numbers is None: + from twilio.rest.numbers import Numbers + + self._numbers = Numbers(self) + return self._numbers + + @property + def oauth(self) -> "Oauth": + """ + Access the Oauth Twilio Domain + + :returns: Oauth Twilio Domain + """ + if self._oauth is None: + from twilio.rest.oauth import Oauth + + self._oauth = Oauth(self) + return self._oauth + + @property + def preview(self) -> "Preview": + """ + Access the Preview Twilio Domain + + :returns: Preview Twilio Domain + """ + if self._preview is None: + from twilio.rest.preview import Preview + + self._preview = Preview(self) + return self._preview + + @property + def pricing(self) -> "Pricing": + """ + Access the Pricing Twilio Domain + + :returns: Pricing Twilio Domain + """ + if self._pricing is None: + from twilio.rest.pricing import Pricing + + self._pricing = Pricing(self) + return self._pricing + + @property + def proxy(self) -> "Proxy": + """ + Access the Proxy Twilio Domain + + :returns: Proxy Twilio Domain + """ + if self._proxy is None: + from twilio.rest.proxy import Proxy + + self._proxy = Proxy(self) + return self._proxy + + @property + def routes(self) -> "Routes": + """ + Access the Routes Twilio Domain + + :returns: Routes Twilio Domain + """ + if self._routes is None: + from twilio.rest.routes import Routes + + self._routes = Routes(self) + return self._routes + + @property + def serverless(self) -> "Serverless": + """ + Access the Serverless Twilio Domain + + :returns: Serverless Twilio Domain + """ + if self._serverless is None: + from twilio.rest.serverless import Serverless + + self._serverless = Serverless(self) + return self._serverless + + @property + def studio(self) -> "Studio": + """ + Access the Studio Twilio Domain + + :returns: Studio Twilio Domain + """ + if self._studio is None: + from twilio.rest.studio import Studio + + self._studio = Studio(self) + return self._studio + + @property + def supersim(self) -> "Supersim": + """ + Access the Supersim Twilio Domain + + :returns: Supersim Twilio Domain + """ + if self._supersim is None: + from twilio.rest.supersim import Supersim + + self._supersim = Supersim(self) + return self._supersim + + @property + def sync(self) -> "Sync": + """ + Access the Sync Twilio Domain + + :returns: Sync Twilio Domain + """ + if self._sync is None: + from twilio.rest.sync import Sync + + self._sync = Sync(self) + return self._sync + + @property + def taskrouter(self) -> "Taskrouter": + """ + Access the Taskrouter Twilio Domain + + :returns: Taskrouter Twilio Domain + """ + if self._taskrouter is None: + from twilio.rest.taskrouter import Taskrouter + + self._taskrouter = Taskrouter(self) + return self._taskrouter + + @property + def trunking(self) -> "Trunking": + """ + Access the Trunking Twilio Domain + + :returns: Trunking Twilio Domain + """ + if self._trunking is None: + from twilio.rest.trunking import Trunking + + self._trunking = Trunking(self) + return self._trunking + + @property + def trusthub(self) -> "Trusthub": + """ + Access the Trusthub Twilio Domain + + :returns: Trusthub Twilio Domain + """ + if self._trusthub is None: + from twilio.rest.trusthub import Trusthub + + self._trusthub = Trusthub(self) + return self._trusthub + + @property + def verify(self) -> "Verify": + """ + Access the Verify Twilio Domain + + :returns: Verify Twilio Domain + """ + if self._verify is None: + from twilio.rest.verify import Verify + + self._verify = Verify(self) + return self._verify + + @property + def video(self) -> "Video": + """ + Access the Video Twilio Domain + + :returns: Video Twilio Domain + """ + if self._video is None: + from twilio.rest.video import Video + + self._video = Video(self) + return self._video + + @property + def voice(self) -> "Voice": + """ + Access the Voice Twilio Domain + + :returns: Voice Twilio Domain + """ + if self._voice is None: + from twilio.rest.voice import Voice + + self._voice = Voice(self) + return self._voice + + @property + def wireless(self) -> "Wireless": + """ + Access the Wireless Twilio Domain + + :returns: Wireless Twilio Domain + """ + if self._wireless is None: + from twilio.rest.wireless import Wireless + + self._wireless = Wireless(self) + return self._wireless + + @property + def addresses(self) -> "AddressList": + return self.api.account.addresses + + @property + def applications(self) -> "ApplicationList": + return self.api.account.applications + + @property + def authorized_connect_apps(self) -> "AuthorizedConnectAppList": + return self.api.account.authorized_connect_apps + + @property + def available_phone_numbers(self) -> "AvailablePhoneNumberCountryList": + return self.api.account.available_phone_numbers + + @property + def balance(self) -> "BalanceList": + return self.api.account.balance + + @property + def calls(self) -> "CallList": + return self.api.account.calls + + @property + def conferences(self) -> "ConferenceList": + return self.api.account.conferences + + @property + def connect_apps(self) -> "ConnectAppList": + return self.api.account.connect_apps + + @property + def incoming_phone_numbers(self) -> "IncomingPhoneNumberList": + return self.api.account.incoming_phone_numbers + + @property + def keys(self) -> "KeyList": + return self.api.account.keys + + @property + def new_keys(self) -> "NewKeyList": + return self.api.account.new_keys + + @property + def messages(self) -> "MessageList": + return self.api.account.messages + + @property + def signing_keys(self) -> "SigningKeyList": + return self.api.account.signing_keys + + @property + def new_signing_keys(self) -> "NewSigningKeyList": + return self.api.account.new_signing_keys + + @property + def notifications(self) -> "NotificationList": + return self.api.account.notifications + + @property + def outgoing_caller_ids(self) -> "OutgoingCallerIdList": + return self.api.account.outgoing_caller_ids + + @property + def validation_requests(self) -> "ValidationRequestList": + return self.api.account.validation_requests + + @property + def queues(self) -> "QueueList": + return self.api.account.queues + + @property + def recordings(self) -> "RecordingList": + return self.api.account.recordings + + @property + def short_codes(self) -> "ShortCodeList": + return self.api.account.short_codes + + @property + def sip(self) -> "SipList": + return self.api.account.sip + + @property + def tokens(self) -> "TokenList": + return self.api.account.tokens + + @property + def transcriptions(self) -> "TranscriptionList": + return self.api.account.transcriptions + + @property + def usage(self) -> "UsageList": + return self.api.account.usage diff --git a/twilio/rest/accounts/AccountsBase.py b/twilio/rest/accounts/AccountsBase.py new file mode 100644 index 0000000000..e9ac0d589d --- /dev/null +++ b/twilio/rest/accounts/AccountsBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.accounts.v1 import V1 + + +class AccountsBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Accounts Domain + + :returns: Domain for Accounts + """ + super().__init__(twilio, "https://accounts.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Accounts + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Accounts>" diff --git a/twilio/rest/accounts/__init__.py b/twilio/rest/accounts/__init__.py new file mode 100644 index 0000000000..e2275aea44 --- /dev/null +++ b/twilio/rest/accounts/__init__.py @@ -0,0 +1,35 @@ +from warnings import warn + +from twilio.rest.accounts.AccountsBase import AccountsBase +from twilio.rest.accounts.v1.auth_token_promotion import AuthTokenPromotionList +from twilio.rest.accounts.v1.credential import CredentialList +from twilio.rest.accounts.v1.secondary_auth_token import SecondaryAuthTokenList + + +class Accounts(AccountsBase): + @property + def auth_token_promotion(self) -> AuthTokenPromotionList: + warn( + "auth_token_promotion is deprecated. Use v1.auth_token_promotion instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.auth_token_promotion + + @property + def credentials(self) -> CredentialList: + warn( + "credentials is deprecated. Use v1.credentials instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.credentials + + @property + def secondary_auth_token(self) -> SecondaryAuthTokenList: + warn( + "secondary_auth_token is deprecated. Use v1.secondary_auth_token instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.secondary_auth_token diff --git a/twilio/rest/accounts/v1/__init__.py b/twilio/rest/accounts/v1/__init__.py new file mode 100644 index 0000000000..6f5012d0fa --- /dev/null +++ b/twilio/rest/accounts/v1/__init__.py @@ -0,0 +1,83 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Accounts + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.accounts.v1.auth_token_promotion import AuthTokenPromotionList +from twilio.rest.accounts.v1.bulk_consents import BulkConsentsList +from twilio.rest.accounts.v1.bulk_contacts import BulkContactsList +from twilio.rest.accounts.v1.credential import CredentialList +from twilio.rest.accounts.v1.safelist import SafelistList +from twilio.rest.accounts.v1.secondary_auth_token import SecondaryAuthTokenList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Accounts + + :param domain: The Twilio.accounts domain + """ + super().__init__(domain, "v1") + self._auth_token_promotion: Optional[AuthTokenPromotionList] = None + self._bulk_consents: Optional[BulkConsentsList] = None + self._bulk_contacts: Optional[BulkContactsList] = None + self._credentials: Optional[CredentialList] = None + self._safelist: Optional[SafelistList] = None + self._secondary_auth_token: Optional[SecondaryAuthTokenList] = None + + @property + def auth_token_promotion(self) -> AuthTokenPromotionList: + if self._auth_token_promotion is None: + self._auth_token_promotion = AuthTokenPromotionList(self) + return self._auth_token_promotion + + @property + def bulk_consents(self) -> BulkConsentsList: + if self._bulk_consents is None: + self._bulk_consents = BulkConsentsList(self) + return self._bulk_consents + + @property + def bulk_contacts(self) -> BulkContactsList: + if self._bulk_contacts is None: + self._bulk_contacts = BulkContactsList(self) + return self._bulk_contacts + + @property + def credentials(self) -> CredentialList: + if self._credentials is None: + self._credentials = CredentialList(self) + return self._credentials + + @property + def safelist(self) -> SafelistList: + if self._safelist is None: + self._safelist = SafelistList(self) + return self._safelist + + @property + def secondary_auth_token(self) -> SecondaryAuthTokenList: + if self._secondary_auth_token is None: + self._secondary_auth_token = SecondaryAuthTokenList(self) + return self._secondary_auth_token + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Accounts.V1>" diff --git a/twilio/rest/accounts/v1/auth_token_promotion.py b/twilio/rest/accounts/v1/auth_token_promotion.py new file mode 100644 index 0000000000..8580538a9b --- /dev/null +++ b/twilio/rest/accounts/v1/auth_token_promotion.py @@ -0,0 +1,181 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Accounts + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class AuthTokenPromotionInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the secondary Auth Token was created for. + :ivar auth_token: The promoted Auth Token that must be used to authenticate future API requests. + :ivar date_created: The date and time in UTC when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The URI for this resource, relative to `https://accounts.twilio.com` + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.auth_token: Optional[str] = payload.get("auth_token") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._context: Optional[AuthTokenPromotionContext] = None + + @property + def _proxy(self) -> "AuthTokenPromotionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AuthTokenPromotionContext for this AuthTokenPromotionInstance + """ + if self._context is None: + self._context = AuthTokenPromotionContext( + self._version, + ) + return self._context + + def update(self) -> "AuthTokenPromotionInstance": + """ + Update the AuthTokenPromotionInstance + + + :returns: The updated AuthTokenPromotionInstance + """ + return self._proxy.update() + + async def update_async(self) -> "AuthTokenPromotionInstance": + """ + Asynchronous coroutine to update the AuthTokenPromotionInstance + + + :returns: The updated AuthTokenPromotionInstance + """ + return await self._proxy.update_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Accounts.V1.AuthTokenPromotionInstance>" + + +class AuthTokenPromotionContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the AuthTokenPromotionContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/AuthTokens/Promote" + + def update(self) -> AuthTokenPromotionInstance: + """ + Update the AuthTokenPromotionInstance + + + :returns: The updated AuthTokenPromotionInstance + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthTokenPromotionInstance(self._version, payload) + + async def update_async(self) -> AuthTokenPromotionInstance: + """ + Asynchronous coroutine to update the AuthTokenPromotionInstance + + + :returns: The updated AuthTokenPromotionInstance + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthTokenPromotionInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Accounts.V1.AuthTokenPromotionContext>" + + +class AuthTokenPromotionList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AuthTokenPromotionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> AuthTokenPromotionContext: + """ + Constructs a AuthTokenPromotionContext + + """ + return AuthTokenPromotionContext(self._version) + + def __call__(self) -> AuthTokenPromotionContext: + """ + Constructs a AuthTokenPromotionContext + + """ + return AuthTokenPromotionContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Accounts.V1.AuthTokenPromotionList>" diff --git a/twilio/rest/accounts/v1/bulk_consents.py b/twilio/rest/accounts/v1/bulk_consents.py new file mode 100644 index 0000000000..9e242552ee --- /dev/null +++ b/twilio/rest/accounts/v1/bulk_consents.py @@ -0,0 +1,114 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Accounts + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional +from twilio.base import serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class BulkConsentsInstance(InstanceResource): + """ + :ivar items: A list of objects where each object represents the result of processing a `correlation_id`. Each object contains the following fields: `correlation_id`, a unique 32-character UUID that maps the response to the original request; `error_code`, an integer where 0 indicates success and any non-zero value represents an error; and `error_messages`, an array of strings describing specific validation errors encountered. If the request is successful, the error_messages array will be empty. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.items: Optional[Dict[str, object]] = payload.get("items") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Accounts.V1.BulkConsentsInstance>" + + +class BulkConsentsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BulkConsentsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Consents/Bulk" + + def create(self, items: List[object]) -> BulkConsentsInstance: + """ + Create the BulkConsentsInstance + + :param items: This is a list of objects that describes a contact's opt-in status. Each object contains the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID used to uniquely map the request item with the response item; `sender_id`, which can be either a valid messaging service SID or a from phone number; `status`, a string representing the consent status. Can be one of [`opt-in`, `opt-out`]; `source`, a string indicating the medium through which the consent was collected. Can be one of [`website`, `offline`, `opt-in-message`, `opt-out-message`, `others`]; `date_of_consent`, an optional datetime string field in ISO-8601 format that captures the exact date and time when the user gave or revoked consent. If not provided, it will be empty. + + :returns: The created BulkConsentsInstance + """ + + data = values.of( + { + "Items": serialize.map(items, lambda e: serialize.object(e)), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BulkConsentsInstance(self._version, payload) + + async def create_async(self, items: List[object]) -> BulkConsentsInstance: + """ + Asynchronously create the BulkConsentsInstance + + :param items: This is a list of objects that describes a contact's opt-in status. Each object contains the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID used to uniquely map the request item with the response item; `sender_id`, which can be either a valid messaging service SID or a from phone number; `status`, a string representing the consent status. Can be one of [`opt-in`, `opt-out`]; `source`, a string indicating the medium through which the consent was collected. Can be one of [`website`, `offline`, `opt-in-message`, `opt-out-message`, `others`]; `date_of_consent`, an optional datetime string field in ISO-8601 format that captures the exact date and time when the user gave or revoked consent. If not provided, it will be empty. + + :returns: The created BulkConsentsInstance + """ + + data = values.of( + { + "Items": serialize.map(items, lambda e: serialize.object(e)), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BulkConsentsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Accounts.V1.BulkConsentsList>" diff --git a/twilio/rest/accounts/v1/bulk_contacts.py b/twilio/rest/accounts/v1/bulk_contacts.py new file mode 100644 index 0000000000..17b6da33f3 --- /dev/null +++ b/twilio/rest/accounts/v1/bulk_contacts.py @@ -0,0 +1,114 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Accounts + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional +from twilio.base import serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class BulkContactsInstance(InstanceResource): + """ + :ivar items: A list of objects where each object represents the result of processing a `correlation_id`. Each object contains the following fields: `correlation_id`, a unique 32-character UUID that maps the response to the original request; `error_code`, an integer where 0 indicates success and any non-zero value represents an error; and `error_messages`, an array of strings describing specific validation errors encountered. If the request is successful, the error_messages array will be empty. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.items: Optional[Dict[str, object]] = payload.get("items") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Accounts.V1.BulkContactsInstance>" + + +class BulkContactsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BulkContactsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Contacts/Bulk" + + def create(self, items: List[object]) -> BulkContactsInstance: + """ + Create the BulkContactsInstance + + :param items: A list of objects where each object represents a contact's details. Each object includes the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID that maps the response to the original request; `country_iso_code`, a string representing the country using the ISO format (e.g., US for the United States); and `zip_code`, a string representing the postal code. + + :returns: The created BulkContactsInstance + """ + + data = values.of( + { + "Items": serialize.map(items, lambda e: serialize.object(e)), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BulkContactsInstance(self._version, payload) + + async def create_async(self, items: List[object]) -> BulkContactsInstance: + """ + Asynchronously create the BulkContactsInstance + + :param items: A list of objects where each object represents a contact's details. Each object includes the following fields: `contact_id`, which must be a string representing phone number in [E.164 format](https://www.twilio.com/docs/glossary/what-e164); `correlation_id`, a unique 32-character UUID that maps the response to the original request; `country_iso_code`, a string representing the country using the ISO format (e.g., US for the United States); and `zip_code`, a string representing the postal code. + + :returns: The created BulkContactsInstance + """ + + data = values.of( + { + "Items": serialize.map(items, lambda e: serialize.object(e)), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BulkContactsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Accounts.V1.BulkContactsList>" diff --git a/twilio/rest/accounts/v1/credential/__init__.py b/twilio/rest/accounts/v1/credential/__init__.py new file mode 100644 index 0000000000..e9c4653f0c --- /dev/null +++ b/twilio/rest/accounts/v1/credential/__init__.py @@ -0,0 +1,65 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Accounts + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.accounts.v1.credential.aws import AwsList +from twilio.rest.accounts.v1.credential.public_key import PublicKeyList + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Credentials" + + self._aws: Optional[AwsList] = None + self._public_key: Optional[PublicKeyList] = None + + @property + def aws(self) -> AwsList: + """ + Access the aws + """ + if self._aws is None: + self._aws = AwsList(self._version) + return self._aws + + @property + def public_key(self) -> PublicKeyList: + """ + Access the public_key + """ + if self._public_key is None: + self._public_key = PublicKeyList(self._version) + return self._public_key + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Accounts.V1.CredentialList>" diff --git a/twilio/rest/accounts/v1/credential/aws.py b/twilio/rest/accounts/v1/credential/aws.py new file mode 100644 index 0000000000..ba5335accd --- /dev/null +++ b/twilio/rest/accounts/v1/credential/aws.py @@ -0,0 +1,609 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Accounts + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AwsInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the AWS resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AWS resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The URI for this resource, relative to `https://accounts.twilio.com` + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AwsContext] = None + + @property + def _proxy(self) -> "AwsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AwsContext for this AwsInstance + """ + if self._context is None: + self._context = AwsContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AwsInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AwsInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AwsInstance": + """ + Fetch the AwsInstance + + + :returns: The fetched AwsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AwsInstance": + """ + Asynchronous coroutine to fetch the AwsInstance + + + :returns: The fetched AwsInstance + """ + return await self._proxy.fetch_async() + + def update(self, friendly_name: Union[str, object] = values.unset) -> "AwsInstance": + """ + Update the AwsInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated AwsInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "AwsInstance": + """ + Asynchronous coroutine to update the AwsInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated AwsInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Accounts.V1.AwsInstance {}>".format(context) + + +class AwsContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the AwsContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the AWS resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/AWS/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the AwsInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AwsInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AwsInstance: + """ + Fetch the AwsInstance + + + :returns: The fetched AwsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AwsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AwsInstance: + """ + Asynchronous coroutine to fetch the AwsInstance + + + :returns: The fetched AwsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AwsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update(self, friendly_name: Union[str, object] = values.unset) -> AwsInstance: + """ + Update the AwsInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated AwsInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AwsInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> AwsInstance: + """ + Asynchronous coroutine to update the AwsInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated AwsInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AwsInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Accounts.V1.AwsContext {}>".format(context) + + +class AwsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AwsInstance: + """ + Build an instance of AwsInstance + + :param payload: Payload response from the API + """ + return AwsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Accounts.V1.AwsPage>" + + +class AwsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AwsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Credentials/AWS" + + def create( + self, + credentials: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> AwsInstance: + """ + Create the AwsInstance + + :param credentials: A string that contains the AWS access credentials in the format `<AWS_ACCESS_KEY_ID>:<AWS_SECRET_ACCESS_KEY>`. For example, `AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY` + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request. + + :returns: The created AwsInstance + """ + + data = values.of( + { + "Credentials": credentials, + "FriendlyName": friendly_name, + "AccountSid": account_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AwsInstance(self._version, payload) + + async def create_async( + self, + credentials: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> AwsInstance: + """ + Asynchronously create the AwsInstance + + :param credentials: A string that contains the AWS access credentials in the format `<AWS_ACCESS_KEY_ID>:<AWS_SECRET_ACCESS_KEY>`. For example, `AKIAIOSFODNN7EXAMPLE:wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY` + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request. + + :returns: The created AwsInstance + """ + + data = values.of( + { + "Credentials": credentials, + "FriendlyName": friendly_name, + "AccountSid": account_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AwsInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AwsInstance]: + """ + Streams AwsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AwsInstance]: + """ + Asynchronously streams AwsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AwsInstance]: + """ + Lists AwsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AwsInstance]: + """ + Asynchronously lists AwsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AwsPage: + """ + Retrieve a single page of AwsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AwsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AwsPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AwsPage: + """ + Asynchronously retrieve a single page of AwsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AwsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AwsPage(self._version, response) + + def get_page(self, target_url: str) -> AwsPage: + """ + Retrieve a specific page of AwsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AwsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AwsPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AwsPage: + """ + Asynchronously retrieve a specific page of AwsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AwsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AwsPage(self._version, response) + + def get(self, sid: str) -> AwsContext: + """ + Constructs a AwsContext + + :param sid: The Twilio-provided string that uniquely identifies the AWS resource to update. + """ + return AwsContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AwsContext: + """ + Constructs a AwsContext + + :param sid: The Twilio-provided string that uniquely identifies the AWS resource to update. + """ + return AwsContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Accounts.V1.AwsList>" diff --git a/twilio/rest/accounts/v1/credential/public_key.py b/twilio/rest/accounts/v1/credential/public_key.py new file mode 100644 index 0000000000..c2b4f9bbee --- /dev/null +++ b/twilio/rest/accounts/v1/credential/public_key.py @@ -0,0 +1,613 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Accounts + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PublicKeyInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the PublicKey resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Credential that the PublicKey resource belongs to. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The URI for this resource, relative to `https://accounts.twilio.com` + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[PublicKeyContext] = None + + @property + def _proxy(self) -> "PublicKeyContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PublicKeyContext for this PublicKeyInstance + """ + if self._context is None: + self._context = PublicKeyContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the PublicKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PublicKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "PublicKeyInstance": + """ + Fetch the PublicKeyInstance + + + :returns: The fetched PublicKeyInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PublicKeyInstance": + """ + Asynchronous coroutine to fetch the PublicKeyInstance + + + :returns: The fetched PublicKeyInstance + """ + return await self._proxy.fetch_async() + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "PublicKeyInstance": + """ + Update the PublicKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated PublicKeyInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "PublicKeyInstance": + """ + Asynchronous coroutine to update the PublicKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated PublicKeyInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Accounts.V1.PublicKeyInstance {}>".format(context) + + +class PublicKeyContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PublicKeyContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the PublicKey resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/PublicKeys/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the PublicKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PublicKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> PublicKeyInstance: + """ + Fetch the PublicKeyInstance + + + :returns: The fetched PublicKeyInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PublicKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> PublicKeyInstance: + """ + Asynchronous coroutine to fetch the PublicKeyInstance + + + :returns: The fetched PublicKeyInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PublicKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> PublicKeyInstance: + """ + Update the PublicKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated PublicKeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PublicKeyInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> PublicKeyInstance: + """ + Asynchronous coroutine to update the PublicKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated PublicKeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PublicKeyInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Accounts.V1.PublicKeyContext {}>".format(context) + + +class PublicKeyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PublicKeyInstance: + """ + Build an instance of PublicKeyInstance + + :param payload: Payload response from the API + """ + return PublicKeyInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Accounts.V1.PublicKeyPage>" + + +class PublicKeyList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PublicKeyList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Credentials/PublicKeys" + + def create( + self, + public_key: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> PublicKeyInstance: + """ + Create the PublicKeyInstance + + :param public_key: A URL encoded representation of the public key. For example, `-----BEGIN PUBLIC KEY-----MIIBIjANB.pa9xQIDAQAB-----END PUBLIC KEY-----` + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request + + :returns: The created PublicKeyInstance + """ + + data = values.of( + { + "PublicKey": public_key, + "FriendlyName": friendly_name, + "AccountSid": account_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PublicKeyInstance(self._version, payload) + + async def create_async( + self, + public_key: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> PublicKeyInstance: + """ + Asynchronously create the PublicKeyInstance + + :param public_key: A URL encoded representation of the public key. For example, `-----BEGIN PUBLIC KEY-----MIIBIjANB.pa9xQIDAQAB-----END PUBLIC KEY-----` + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param account_sid: The SID of the Subaccount that this Credential should be associated with. Must be a valid Subaccount of the account issuing the request + + :returns: The created PublicKeyInstance + """ + + data = values.of( + { + "PublicKey": public_key, + "FriendlyName": friendly_name, + "AccountSid": account_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PublicKeyInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PublicKeyInstance]: + """ + Streams PublicKeyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PublicKeyInstance]: + """ + Asynchronously streams PublicKeyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PublicKeyInstance]: + """ + Lists PublicKeyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PublicKeyInstance]: + """ + Asynchronously lists PublicKeyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PublicKeyPage: + """ + Retrieve a single page of PublicKeyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PublicKeyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PublicKeyPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PublicKeyPage: + """ + Asynchronously retrieve a single page of PublicKeyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PublicKeyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PublicKeyPage(self._version, response) + + def get_page(self, target_url: str) -> PublicKeyPage: + """ + Retrieve a specific page of PublicKeyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PublicKeyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PublicKeyPage(self._version, response) + + async def get_page_async(self, target_url: str) -> PublicKeyPage: + """ + Asynchronously retrieve a specific page of PublicKeyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PublicKeyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PublicKeyPage(self._version, response) + + def get(self, sid: str) -> PublicKeyContext: + """ + Constructs a PublicKeyContext + + :param sid: The Twilio-provided string that uniquely identifies the PublicKey resource to update. + """ + return PublicKeyContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PublicKeyContext: + """ + Constructs a PublicKeyContext + + :param sid: The Twilio-provided string that uniquely identifies the PublicKey resource to update. + """ + return PublicKeyContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Accounts.V1.PublicKeyList>" diff --git a/twilio/rest/accounts/v1/safelist.py b/twilio/rest/accounts/v1/safelist.py new file mode 100644 index 0000000000..be8fe416af --- /dev/null +++ b/twilio/rest/accounts/v1/safelist.py @@ -0,0 +1,204 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Accounts + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SafelistInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the SafeList resource. + :ivar phone_number: The phone number or phone number 1k prefix in SafeList. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.phone_number: Optional[str] = payload.get("phone_number") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Accounts.V1.SafelistInstance>" + + +class SafelistList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SafelistList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SafeList/Numbers" + + def create(self, phone_number: str) -> SafelistInstance: + """ + Create the SafelistInstance + + :param phone_number: The phone number or phone number 1k prefix to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + + :returns: The created SafelistInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SafelistInstance(self._version, payload) + + async def create_async(self, phone_number: str) -> SafelistInstance: + """ + Asynchronously create the SafelistInstance + + :param phone_number: The phone number or phone number 1k prefix to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + + :returns: The created SafelistInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SafelistInstance(self._version, payload) + + def delete(self, phone_number: Union[str, object] = values.unset) -> bool: + """ + Asynchronously delete the SafelistInstance + + :param phone_number: The phone number or phone number 1k prefix to be removed from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :returns: True if delete succeeds, False otherwise + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + params = values.of( + { + "PhoneNumber": phone_number, + } + ) + return self._version.delete( + method="DELETE", uri=self._uri, headers=headers, params=params + ) + + async def delete_async( + self, phone_number: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronously delete the SafelistInstance + + :param phone_number: The phone number or phone number 1k prefix to be removed from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :returns: True if delete succeeds, False otherwise + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + params = values.of( + { + "PhoneNumber": phone_number, + } + ) + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers, params=params + ) + + def fetch( + self, phone_number: Union[str, object] = values.unset + ) -> SafelistInstance: + """ + Asynchronously fetch the SafelistInstance + + :param phone_number: The phone number or phone number 1k prefix to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :returns: The fetched SafelistInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "PhoneNumber": phone_number, + } + ) + + payload = self._version.fetch( + method="GET", uri=self._uri, headers=headers, params=params + ) + + return SafelistInstance(self._version, payload) + + async def fetch_async( + self, phone_number: Union[str, object] = values.unset + ) -> SafelistInstance: + """ + Asynchronously fetch the SafelistInstance + + :param phone_number: The phone number or phone number 1k prefix to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :returns: The fetched SafelistInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "PhoneNumber": phone_number, + } + ) + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + return SafelistInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Accounts.V1.SafelistList>" diff --git a/twilio/rest/accounts/v1/secondary_auth_token.py b/twilio/rest/accounts/v1/secondary_auth_token.py new file mode 100644 index 0000000000..f5e2b5c1a3 --- /dev/null +++ b/twilio/rest/accounts/v1/secondary_auth_token.py @@ -0,0 +1,215 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Accounts + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SecondaryAuthTokenInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the secondary Auth Token was created for. + :ivar date_created: The date and time in UTC when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in UTC when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar secondary_auth_token: The generated secondary Auth Token that can be used to authenticate future API requests. + :ivar url: The URI for this resource, relative to `https://accounts.twilio.com` + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.secondary_auth_token: Optional[str] = payload.get("secondary_auth_token") + self.url: Optional[str] = payload.get("url") + + self._context: Optional[SecondaryAuthTokenContext] = None + + @property + def _proxy(self) -> "SecondaryAuthTokenContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SecondaryAuthTokenContext for this SecondaryAuthTokenInstance + """ + if self._context is None: + self._context = SecondaryAuthTokenContext( + self._version, + ) + return self._context + + def create(self) -> "SecondaryAuthTokenInstance": + """ + Create the SecondaryAuthTokenInstance + + + :returns: The created SecondaryAuthTokenInstance + """ + return self._proxy.create() + + async def create_async(self) -> "SecondaryAuthTokenInstance": + """ + Asynchronous coroutine to create the SecondaryAuthTokenInstance + + + :returns: The created SecondaryAuthTokenInstance + """ + return await self._proxy.create_async() + + def delete(self) -> bool: + """ + Deletes the SecondaryAuthTokenInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SecondaryAuthTokenInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Accounts.V1.SecondaryAuthTokenInstance>" + + +class SecondaryAuthTokenContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the SecondaryAuthTokenContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/AuthTokens/Secondary" + + def create(self) -> SecondaryAuthTokenInstance: + """ + Create the SecondaryAuthTokenInstance + + + :returns: The created SecondaryAuthTokenInstance + """ + data = values.of({}) + + payload = self._version.create(method="POST", uri=self._uri, data=data) + + return SecondaryAuthTokenInstance(self._version, payload) + + async def create_async(self) -> SecondaryAuthTokenInstance: + """ + Asynchronous coroutine to create the SecondaryAuthTokenInstance + + + :returns: The created SecondaryAuthTokenInstance + """ + data = values.of({}) + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data + ) + + return SecondaryAuthTokenInstance(self._version, payload) + + def delete(self) -> bool: + """ + Deletes the SecondaryAuthTokenInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SecondaryAuthTokenInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Accounts.V1.SecondaryAuthTokenContext>" + + +class SecondaryAuthTokenList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SecondaryAuthTokenList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> SecondaryAuthTokenContext: + """ + Constructs a SecondaryAuthTokenContext + + """ + return SecondaryAuthTokenContext(self._version) + + def __call__(self) -> SecondaryAuthTokenContext: + """ + Constructs a SecondaryAuthTokenContext + + """ + return SecondaryAuthTokenContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Accounts.V1.SecondaryAuthTokenList>" diff --git a/twilio/rest/api/ApiBase.py b/twilio/rest/api/ApiBase.py new file mode 100644 index 0000000000..e53535ab3f --- /dev/null +++ b/twilio/rest/api/ApiBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.api.v2010 import V2010 + + +class ApiBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Api Domain + + :returns: Domain for Api + """ + super().__init__(twilio, "https://api.twilio.com") + self._v2010: Optional[V2010] = None + + @property + def v2010(self) -> V2010: + """ + :returns: Versions v2010 of Api + """ + if self._v2010 is None: + self._v2010 = V2010(self) + return self._v2010 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Api>" diff --git a/twilio/rest/api/__init__.py b/twilio/rest/api/__init__.py new file mode 100644 index 0000000000..08d5885cbd --- /dev/null +++ b/twilio/rest/api/__init__.py @@ -0,0 +1,258 @@ +from warnings import warn + +from twilio.rest.api.ApiBase import ApiBase +from twilio.rest.api.v2010.account import AccountContext, AccountList +from twilio.rest.api.v2010.account.address import AddressList +from twilio.rest.api.v2010.account.application import ApplicationList +from twilio.rest.api.v2010.account.authorized_connect_app import ( + AuthorizedConnectAppList, +) +from twilio.rest.api.v2010.account.available_phone_number_country import ( + AvailablePhoneNumberCountryList, +) +from twilio.rest.api.v2010.account.balance import BalanceList +from twilio.rest.api.v2010.account.call import CallList +from twilio.rest.api.v2010.account.conference import ConferenceList +from twilio.rest.api.v2010.account.connect_app import ConnectAppList +from twilio.rest.api.v2010.account.incoming_phone_number import IncomingPhoneNumberList +from twilio.rest.api.v2010.account.key import KeyList +from twilio.rest.api.v2010.account.message import MessageList +from twilio.rest.api.v2010.account.new_key import NewKeyList +from twilio.rest.api.v2010.account.new_signing_key import NewSigningKeyList +from twilio.rest.api.v2010.account.notification import NotificationList +from twilio.rest.api.v2010.account.outgoing_caller_id import OutgoingCallerIdList +from twilio.rest.api.v2010.account.queue import QueueList +from twilio.rest.api.v2010.account.recording import RecordingList +from twilio.rest.api.v2010.account.short_code import ShortCodeList +from twilio.rest.api.v2010.account.signing_key import SigningKeyList +from twilio.rest.api.v2010.account.sip import SipList +from twilio.rest.api.v2010.account.token import TokenList +from twilio.rest.api.v2010.account.transcription import TranscriptionList +from twilio.rest.api.v2010.account.usage import UsageList +from twilio.rest.api.v2010.account.validation_request import ValidationRequestList + + +class Api(ApiBase): + @property + def account(self) -> AccountContext: + return self.v2010.account + + @property + def accounts(self) -> AccountList: + return self.v2010.accounts + + @property + def addresses(self) -> AddressList: + warn( + "addresses is deprecated. Use account.addresses instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.addresses + + @property + def applications(self) -> ApplicationList: + warn( + "applications is deprecated. Use account.applications instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.applications + + @property + def authorized_connect_apps(self) -> AuthorizedConnectAppList: + warn( + "authorized_connect_apps is deprecated. Use account.authorized_connect_apps instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.authorized_connect_apps + + @property + def available_phone_numbers(self) -> AvailablePhoneNumberCountryList: + warn( + "available_phone_numbers is deprecated. Use account.available_phone_numbers instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.available_phone_numbers + + @property + def balance(self) -> BalanceList: + warn( + "balance is deprecated. Use account.balance instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.balance + + @property + def calls(self) -> CallList: + warn( + "calls is deprecated. Use account.calls instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.calls + + @property + def conferences(self) -> ConferenceList: + warn( + "conferences is deprecated. Use account.conferences instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.conferences + + @property + def connect_apps(self) -> ConnectAppList: + warn( + "connect_apps is deprecated. Use account.connect_apps instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.connect_apps + + @property + def incoming_phone_numbers(self) -> IncomingPhoneNumberList: + warn( + "incoming_phone_numbers is deprecated. Use account.incoming_phone_numbers instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.incoming_phone_numbers + + @property + def keys(self) -> KeyList: + warn( + "keys is deprecated. Use account.keys instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.keys + + @property + def messages(self) -> MessageList: + warn( + "messages is deprecated. Use account.messages instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.messages + + @property + def new_keys(self) -> NewKeyList: + warn( + "new_keys is deprecated. Use account.new_keys instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.new_keys + + @property + def new_signing_keys(self) -> NewSigningKeyList: + warn( + "new_signing_keys is deprecated. Use account.new_signing_keys instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.new_signing_keys + + @property + def notifications(self) -> NotificationList: + warn( + "notifications is deprecated. Use account.notifications instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.notifications + + @property + def outgoing_caller_ids(self) -> OutgoingCallerIdList: + warn( + "outgoing_caller_ids is deprecated. Use account.outgoing_caller_ids instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.outgoing_caller_ids + + @property + def queues(self) -> QueueList: + warn( + "queues is deprecated. Use account.queues instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.queues + + @property + def recordings(self) -> RecordingList: + warn( + "recordings is deprecated. Use account.recordings instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.recordings + + @property + def signing_keys(self) -> SigningKeyList: + warn( + "signing_keys is deprecated. Use account.signing_keys instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.signing_keys + + @property + def sip(self) -> SipList: + warn( + "sip is deprecated. Use account.sip instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.sip + + @property + def short_codes(self) -> ShortCodeList: + warn( + "short_codes is deprecated. Use account.short_codes instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.short_codes + + @property + def tokens(self) -> TokenList: + warn( + "tokens is deprecated. Use account.tokens instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.tokens + + @property + def transcriptions(self) -> TranscriptionList: + warn( + "transcriptions is deprecated. Use account.transcriptions instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.transcriptions + + @property + def usage(self) -> UsageList: + warn( + "usage is deprecated. Use account.usage instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.usage + + @property + def validation_requests(self) -> ValidationRequestList: + warn( + "validation_requests is deprecated. Use account.validation_requests instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.account.validation_requests diff --git a/twilio/rest/api/v2010/__init__.py b/twilio/rest/api/v2010/__init__.py new file mode 100644 index 0000000000..2efb4ff3d0 --- /dev/null +++ b/twilio/rest/api/v2010/__init__.py @@ -0,0 +1,59 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.api.v2010.account import AccountList +from twilio.rest.api.v2010.account import AccountContext + + +class V2010(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2010 version of Api + + :param domain: The Twilio.api domain + """ + super().__init__(domain, "2010-04-01") + self._accounts: Optional[AccountList] = None + self._account: Optional[AccountContext] = None + + @property + def accounts(self) -> AccountList: + if self._accounts is None: + self._accounts = AccountList(self) + return self._accounts + + @property + def account(self) -> AccountContext: + if self._account is None: + self._account = AccountContext(self, self.domain.twilio.account_sid) + return self._account + + @account.setter + def account(self, value: AccountContext) -> None: + """ + Setter to override account + :param value: value to use as account + """ + self._account = value + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010>" diff --git a/twilio/rest/api/v2010/account/__init__.py b/twilio/rest/api/v2010/account/__init__.py new file mode 100644 index 0000000000..7c7e2c1069 --- /dev/null +++ b/twilio/rest/api/v2010/account/__init__.py @@ -0,0 +1,1136 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.address import AddressList +from twilio.rest.api.v2010.account.application import ApplicationList +from twilio.rest.api.v2010.account.authorized_connect_app import ( + AuthorizedConnectAppList, +) +from twilio.rest.api.v2010.account.available_phone_number_country import ( + AvailablePhoneNumberCountryList, +) +from twilio.rest.api.v2010.account.balance import BalanceList +from twilio.rest.api.v2010.account.call import CallList +from twilio.rest.api.v2010.account.conference import ConferenceList +from twilio.rest.api.v2010.account.connect_app import ConnectAppList +from twilio.rest.api.v2010.account.incoming_phone_number import IncomingPhoneNumberList +from twilio.rest.api.v2010.account.key import KeyList +from twilio.rest.api.v2010.account.message import MessageList +from twilio.rest.api.v2010.account.new_key import NewKeyList +from twilio.rest.api.v2010.account.new_signing_key import NewSigningKeyList +from twilio.rest.api.v2010.account.notification import NotificationList +from twilio.rest.api.v2010.account.outgoing_caller_id import OutgoingCallerIdList +from twilio.rest.api.v2010.account.queue import QueueList +from twilio.rest.api.v2010.account.recording import RecordingList +from twilio.rest.api.v2010.account.short_code import ShortCodeList +from twilio.rest.api.v2010.account.signing_key import SigningKeyList +from twilio.rest.api.v2010.account.sip import SipList +from twilio.rest.api.v2010.account.token import TokenList +from twilio.rest.api.v2010.account.transcription import TranscriptionList +from twilio.rest.api.v2010.account.usage import UsageList +from twilio.rest.api.v2010.account.validation_request import ValidationRequestList + + +class AccountInstance(InstanceResource): + + class Status(object): + ACTIVE = "active" + SUSPENDED = "suspended" + CLOSED = "closed" + + class Type(object): + TRIAL = "Trial" + FULL = "Full" + + """ + :ivar auth_token: The authorization token for this account. This token should be kept a secret, so no sharing. + :ivar date_created: The date that this account was created, in GMT in RFC 2822 format + :ivar date_updated: The date that this account was last updated, in GMT in RFC 2822 format. + :ivar friendly_name: A human readable description of this account, up to 64 characters long. By default the FriendlyName is your email address. + :ivar owner_account_sid: The unique 34 character id that represents the parent of this account. The OwnerAccountSid of a parent account is it's own sid. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar status: + :ivar subresource_uris: A Map of various subresources available for the given Account Instance + :ivar type: + :ivar uri: The URI for this resource, relative to `https://api.twilio.com` + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.auth_token: Optional[str] = payload.get("auth_token") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.owner_account_sid: Optional[str] = payload.get("owner_account_sid") + self.sid: Optional[str] = payload.get("sid") + self.status: Optional["AccountInstance.Status"] = payload.get("status") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.type: Optional["AccountInstance.Type"] = payload.get("type") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AccountContext] = None + + @property + def _proxy(self) -> "AccountContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AccountContext for this AccountInstance + """ + if self._context is None: + self._context = AccountContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AccountInstance": + """ + Fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AccountInstance": + """ + Asynchronous coroutine to fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> "AccountInstance": + """ + Update the AccountInstance + + :param friendly_name: Update the human-readable description of this Account + :param status: + + :returns: The updated AccountInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + status=status, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> "AccountInstance": + """ + Asynchronous coroutine to update the AccountInstance + + :param friendly_name: Update the human-readable description of this Account + :param status: + + :returns: The updated AccountInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + status=status, + ) + + @property + def addresses(self) -> AddressList: + """ + Access the addresses + """ + return self._proxy.addresses + + @property + def applications(self) -> ApplicationList: + """ + Access the applications + """ + return self._proxy.applications + + @property + def authorized_connect_apps(self) -> AuthorizedConnectAppList: + """ + Access the authorized_connect_apps + """ + return self._proxy.authorized_connect_apps + + @property + def available_phone_numbers(self) -> AvailablePhoneNumberCountryList: + """ + Access the available_phone_numbers + """ + return self._proxy.available_phone_numbers + + @property + def balance(self) -> BalanceList: + """ + Access the balance + """ + return self._proxy.balance + + @property + def calls(self) -> CallList: + """ + Access the calls + """ + return self._proxy.calls + + @property + def conferences(self) -> ConferenceList: + """ + Access the conferences + """ + return self._proxy.conferences + + @property + def connect_apps(self) -> ConnectAppList: + """ + Access the connect_apps + """ + return self._proxy.connect_apps + + @property + def incoming_phone_numbers(self) -> IncomingPhoneNumberList: + """ + Access the incoming_phone_numbers + """ + return self._proxy.incoming_phone_numbers + + @property + def keys(self) -> KeyList: + """ + Access the keys + """ + return self._proxy.keys + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages + + @property + def new_keys(self) -> NewKeyList: + """ + Access the new_keys + """ + return self._proxy.new_keys + + @property + def new_signing_keys(self) -> NewSigningKeyList: + """ + Access the new_signing_keys + """ + return self._proxy.new_signing_keys + + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + return self._proxy.notifications + + @property + def outgoing_caller_ids(self) -> OutgoingCallerIdList: + """ + Access the outgoing_caller_ids + """ + return self._proxy.outgoing_caller_ids + + @property + def queues(self) -> QueueList: + """ + Access the queues + """ + return self._proxy.queues + + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + return self._proxy.recordings + + @property + def short_codes(self) -> ShortCodeList: + """ + Access the short_codes + """ + return self._proxy.short_codes + + @property + def signing_keys(self) -> SigningKeyList: + """ + Access the signing_keys + """ + return self._proxy.signing_keys + + @property + def sip(self) -> SipList: + """ + Access the sip + """ + return self._proxy.sip + + @property + def tokens(self) -> TokenList: + """ + Access the tokens + """ + return self._proxy.tokens + + @property + def transcriptions(self) -> TranscriptionList: + """ + Access the transcriptions + """ + return self._proxy.transcriptions + + @property + def usage(self) -> UsageList: + """ + Access the usage + """ + return self._proxy.usage + + @property + def validation_requests(self) -> ValidationRequestList: + """ + Access the validation_requests + """ + return self._proxy.validation_requests + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.AccountInstance {}>".format(context) + + +class AccountContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the AccountContext + + :param version: Version that contains the resource + :param sid: The Account Sid that uniquely identifies the account to update + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Accounts/{sid}.json".format(**self._solution) + + self._addresses: Optional[AddressList] = None + self._applications: Optional[ApplicationList] = None + self._authorized_connect_apps: Optional[AuthorizedConnectAppList] = None + self._available_phone_numbers: Optional[AvailablePhoneNumberCountryList] = None + self._balance: Optional[BalanceList] = None + self._calls: Optional[CallList] = None + self._conferences: Optional[ConferenceList] = None + self._connect_apps: Optional[ConnectAppList] = None + self._incoming_phone_numbers: Optional[IncomingPhoneNumberList] = None + self._keys: Optional[KeyList] = None + self._messages: Optional[MessageList] = None + self._new_keys: Optional[NewKeyList] = None + self._new_signing_keys: Optional[NewSigningKeyList] = None + self._notifications: Optional[NotificationList] = None + self._outgoing_caller_ids: Optional[OutgoingCallerIdList] = None + self._queues: Optional[QueueList] = None + self._recordings: Optional[RecordingList] = None + self._short_codes: Optional[ShortCodeList] = None + self._signing_keys: Optional[SigningKeyList] = None + self._sip: Optional[SipList] = None + self._tokens: Optional[TokenList] = None + self._transcriptions: Optional[TranscriptionList] = None + self._usage: Optional[UsageList] = None + self._validation_requests: Optional[ValidationRequestList] = None + + def fetch(self) -> AccountInstance: + """ + Fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AccountInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AccountInstance: + """ + Asynchronous coroutine to fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AccountInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> AccountInstance: + """ + Update the AccountInstance + + :param friendly_name: Update the human-readable description of this Account + :param status: + + :returns: The updated AccountInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccountInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + ) -> AccountInstance: + """ + Asynchronous coroutine to update the AccountInstance + + :param friendly_name: Update the human-readable description of this Account + :param status: + + :returns: The updated AccountInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccountInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def addresses(self) -> AddressList: + """ + Access the addresses + """ + if self._addresses is None: + self._addresses = AddressList( + self._version, + self._solution["sid"], + ) + return self._addresses + + @property + def applications(self) -> ApplicationList: + """ + Access the applications + """ + if self._applications is None: + self._applications = ApplicationList( + self._version, + self._solution["sid"], + ) + return self._applications + + @property + def authorized_connect_apps(self) -> AuthorizedConnectAppList: + """ + Access the authorized_connect_apps + """ + if self._authorized_connect_apps is None: + self._authorized_connect_apps = AuthorizedConnectAppList( + self._version, + self._solution["sid"], + ) + return self._authorized_connect_apps + + @property + def available_phone_numbers(self) -> AvailablePhoneNumberCountryList: + """ + Access the available_phone_numbers + """ + if self._available_phone_numbers is None: + self._available_phone_numbers = AvailablePhoneNumberCountryList( + self._version, + self._solution["sid"], + ) + return self._available_phone_numbers + + @property + def balance(self) -> BalanceList: + """ + Access the balance + """ + if self._balance is None: + self._balance = BalanceList( + self._version, + self._solution["sid"], + ) + return self._balance + + @property + def calls(self) -> CallList: + """ + Access the calls + """ + if self._calls is None: + self._calls = CallList( + self._version, + self._solution["sid"], + ) + return self._calls + + @property + def conferences(self) -> ConferenceList: + """ + Access the conferences + """ + if self._conferences is None: + self._conferences = ConferenceList( + self._version, + self._solution["sid"], + ) + return self._conferences + + @property + def connect_apps(self) -> ConnectAppList: + """ + Access the connect_apps + """ + if self._connect_apps is None: + self._connect_apps = ConnectAppList( + self._version, + self._solution["sid"], + ) + return self._connect_apps + + @property + def incoming_phone_numbers(self) -> IncomingPhoneNumberList: + """ + Access the incoming_phone_numbers + """ + if self._incoming_phone_numbers is None: + self._incoming_phone_numbers = IncomingPhoneNumberList( + self._version, + self._solution["sid"], + ) + return self._incoming_phone_numbers + + @property + def keys(self) -> KeyList: + """ + Access the keys + """ + if self._keys is None: + self._keys = KeyList( + self._version, + self._solution["sid"], + ) + return self._keys + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["sid"], + ) + return self._messages + + @property + def new_keys(self) -> NewKeyList: + """ + Access the new_keys + """ + if self._new_keys is None: + self._new_keys = NewKeyList( + self._version, + self._solution["sid"], + ) + return self._new_keys + + @property + def new_signing_keys(self) -> NewSigningKeyList: + """ + Access the new_signing_keys + """ + if self._new_signing_keys is None: + self._new_signing_keys = NewSigningKeyList( + self._version, + self._solution["sid"], + ) + return self._new_signing_keys + + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + if self._notifications is None: + self._notifications = NotificationList( + self._version, + self._solution["sid"], + ) + return self._notifications + + @property + def outgoing_caller_ids(self) -> OutgoingCallerIdList: + """ + Access the outgoing_caller_ids + """ + if self._outgoing_caller_ids is None: + self._outgoing_caller_ids = OutgoingCallerIdList( + self._version, + self._solution["sid"], + ) + return self._outgoing_caller_ids + + @property + def queues(self) -> QueueList: + """ + Access the queues + """ + if self._queues is None: + self._queues = QueueList( + self._version, + self._solution["sid"], + ) + return self._queues + + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + if self._recordings is None: + self._recordings = RecordingList( + self._version, + self._solution["sid"], + ) + return self._recordings + + @property + def short_codes(self) -> ShortCodeList: + """ + Access the short_codes + """ + if self._short_codes is None: + self._short_codes = ShortCodeList( + self._version, + self._solution["sid"], + ) + return self._short_codes + + @property + def signing_keys(self) -> SigningKeyList: + """ + Access the signing_keys + """ + if self._signing_keys is None: + self._signing_keys = SigningKeyList( + self._version, + self._solution["sid"], + ) + return self._signing_keys + + @property + def sip(self) -> SipList: + """ + Access the sip + """ + if self._sip is None: + self._sip = SipList( + self._version, + self._solution["sid"], + ) + return self._sip + + @property + def tokens(self) -> TokenList: + """ + Access the tokens + """ + if self._tokens is None: + self._tokens = TokenList( + self._version, + self._solution["sid"], + ) + return self._tokens + + @property + def transcriptions(self) -> TranscriptionList: + """ + Access the transcriptions + """ + if self._transcriptions is None: + self._transcriptions = TranscriptionList( + self._version, + self._solution["sid"], + ) + return self._transcriptions + + @property + def usage(self) -> UsageList: + """ + Access the usage + """ + if self._usage is None: + self._usage = UsageList( + self._version, + self._solution["sid"], + ) + return self._usage + + @property + def validation_requests(self) -> ValidationRequestList: + """ + Access the validation_requests + """ + if self._validation_requests is None: + self._validation_requests = ValidationRequestList( + self._version, + self._solution["sid"], + ) + return self._validation_requests + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.AccountContext {}>".format(context) + + +class AccountPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AccountInstance: + """ + Build an instance of AccountInstance + + :param payload: Payload response from the API + """ + return AccountInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AccountPage>" + + +class AccountList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AccountList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Accounts.json" + + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> AccountInstance: + """ + Create the AccountInstance + + :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` + + :returns: The created AccountInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccountInstance(self._version, payload) + + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> AccountInstance: + """ + Asynchronously create the AccountInstance + + :param friendly_name: A human readable description of the account to create, defaults to `SubAccount Created at {YYYY-MM-DD HH:MM meridian}` + + :returns: The created AccountInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccountInstance(self._version, payload) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AccountInstance]: + """ + Streams AccountInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param "AccountInstance.Status" status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + friendly_name=friendly_name, status=status, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AccountInstance]: + """ + Asynchronously streams AccountInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param "AccountInstance.Status" status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, status=status, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AccountInstance]: + """ + Lists AccountInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param "AccountInstance.Status" status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + status=status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AccountInstance]: + """ + Asynchronously lists AccountInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param "AccountInstance.Status" status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + status=status, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AccountPage: + """ + Retrieve a single page of AccountInstance records from the API. + Request is executed immediately + + :param friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AccountInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AccountPage(self._version, response) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + status: Union["AccountInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AccountPage: + """ + Asynchronously retrieve a single page of AccountInstance records from the API. + Request is executed immediately + + :param friendly_name: Only return the Account resources with friendly names that exactly match this name. + :param status: Only return Account resources with the given status. Can be `closed`, `suspended` or `active`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AccountInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AccountPage(self._version, response) + + def get_page(self, target_url: str) -> AccountPage: + """ + Retrieve a specific page of AccountInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AccountInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AccountPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AccountPage: + """ + Asynchronously retrieve a specific page of AccountInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AccountInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AccountPage(self._version, response) + + def get(self, sid: str) -> AccountContext: + """ + Constructs a AccountContext + + :param sid: The Account Sid that uniquely identifies the account to update + """ + return AccountContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AccountContext: + """ + Constructs a AccountContext + + :param sid: The Account Sid that uniquely identifies the account to update + """ + return AccountContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AccountList>" diff --git a/twilio/rest/api/v2010/account/address/__init__.py b/twilio/rest/api/v2010/account/address/__init__.py new file mode 100644 index 0000000000..77fc702ccc --- /dev/null +++ b/twilio/rest/api/v2010/account/address/__init__.py @@ -0,0 +1,913 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.address.dependent_phone_number import ( + DependentPhoneNumberList, +) + + +class AddressInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that is responsible for the Address resource. + :ivar city: The city in which the address is located. + :ivar customer_name: The name associated with the address.This property has a maximum length of 16 4-byte characters, or 21 3-byte characters. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar iso_country: The ISO country code of the address. + :ivar postal_code: The postal code of the address. + :ivar region: The state or region of the address. + :ivar sid: The unique string that that we created to identify the Address resource. + :ivar street: The number and street address of the address. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar emergency_enabled: Whether emergency calling has been enabled on this number. + :ivar validated: Whether the address has been validated to comply with local regulation. In countries that require valid addresses, an invalid address will not be accepted. `true` indicates the Address has been validated. `false` indicate the country doesn't require validation or the Address is not valid. + :ivar verified: Whether the address has been verified to comply with regulation. In countries that require valid addresses, an invalid address will not be accepted. `true` indicates the Address has been verified. `false` indicate the country doesn't require verified or the Address is not valid. + :ivar street_secondary: The additional number and street address of the address. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.city: Optional[str] = payload.get("city") + self.customer_name: Optional[str] = payload.get("customer_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.iso_country: Optional[str] = payload.get("iso_country") + self.postal_code: Optional[str] = payload.get("postal_code") + self.region: Optional[str] = payload.get("region") + self.sid: Optional[str] = payload.get("sid") + self.street: Optional[str] = payload.get("street") + self.uri: Optional[str] = payload.get("uri") + self.emergency_enabled: Optional[bool] = payload.get("emergency_enabled") + self.validated: Optional[bool] = payload.get("validated") + self.verified: Optional[bool] = payload.get("verified") + self.street_secondary: Optional[str] = payload.get("street_secondary") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[AddressContext] = None + + @property + def _proxy(self) -> "AddressContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AddressContext for this AddressInstance + """ + if self._context is None: + self._context = AddressContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AddressInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AddressInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AddressInstance": + """ + Fetch the AddressInstance + + + :returns: The fetched AddressInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AddressInstance": + """ + Asynchronous coroutine to fetch the AddressInstance + + + :returns: The fetched AddressInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> "AddressInstance": + """ + Update the AddressInstance + + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param customer_name: The name to associate with the address. + :param street: The number and street address of the address. + :param city: The city of the address. + :param region: The state or region of the address. + :param postal_code: The postal code of the address. + :param emergency_enabled: Whether to enable emergency calling on the address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The updated AddressInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> "AddressInstance": + """ + Asynchronous coroutine to update the AddressInstance + + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param customer_name: The name to associate with the address. + :param street: The number and street address of the address. + :param city: The city of the address. + :param region: The state or region of the address. + :param postal_code: The postal code of the address. + :param emergency_enabled: Whether to enable emergency calling on the address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The updated AddressInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + customer_name=customer_name, + street=street, + city=city, + region=region, + postal_code=postal_code, + emergency_enabled=emergency_enabled, + auto_correct_address=auto_correct_address, + street_secondary=street_secondary, + ) + + @property + def dependent_phone_numbers(self) -> DependentPhoneNumberList: + """ + Access the dependent_phone_numbers + """ + return self._proxy.dependent_phone_numbers + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.AddressInstance {}>".format(context) + + +class AddressContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the AddressContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that is responsible for the Address resource to update. + :param sid: The Twilio-provided string that uniquely identifies the Address resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Addresses/{sid}.json".format( + **self._solution + ) + + self._dependent_phone_numbers: Optional[DependentPhoneNumberList] = None + + def delete(self) -> bool: + """ + Deletes the AddressInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AddressInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AddressInstance: + """ + Fetch the AddressInstance + + + :returns: The fetched AddressInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AddressInstance: + """ + Asynchronous coroutine to fetch the AddressInstance + + + :returns: The fetched AddressInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> AddressInstance: + """ + Update the AddressInstance + + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param customer_name: The name to associate with the address. + :param street: The number and street address of the address. + :param city: The city of the address. + :param region: The state or region of the address. + :param postal_code: The postal code of the address. + :param emergency_enabled: Whether to enable emergency calling on the address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The updated AddressInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "CustomerName": customer_name, + "Street": street, + "City": city, + "Region": region, + "PostalCode": postal_code, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), + "AutoCorrectAddress": serialize.boolean_to_string(auto_correct_address), + "StreetSecondary": street_secondary, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + customer_name: Union[str, object] = values.unset, + street: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> AddressInstance: + """ + Asynchronous coroutine to update the AddressInstance + + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long for Regulatory Compliance addresses and 32 characters long for Emergency addresses. + :param customer_name: The name to associate with the address. + :param street: The number and street address of the address. + :param city: The city of the address. + :param region: The state or region of the address. + :param postal_code: The postal code of the address. + :param emergency_enabled: Whether to enable emergency calling on the address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The updated AddressInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "CustomerName": customer_name, + "Street": street, + "City": city, + "Region": region, + "PostalCode": postal_code, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), + "AutoCorrectAddress": serialize.boolean_to_string(auto_correct_address), + "StreetSecondary": street_secondary, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def dependent_phone_numbers(self) -> DependentPhoneNumberList: + """ + Access the dependent_phone_numbers + """ + if self._dependent_phone_numbers is None: + self._dependent_phone_numbers = DependentPhoneNumberList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._dependent_phone_numbers + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.AddressContext {}>".format(context) + + +class AddressPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AddressInstance: + """ + Build an instance of AddressInstance + + :param payload: Payload response from the API + """ + return AddressInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AddressPage>" + + +class AddressList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the AddressList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that is responsible for the Address resource to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Addresses.json".format(**self._solution) + + def create( + self, + customer_name: str, + street: str, + city: str, + region: str, + postal_code: str, + iso_country: str, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> AddressInstance: + """ + Create the AddressInstance + + :param customer_name: The name to associate with the new address. + :param street: The number and street address of the new address. + :param city: The city of the new address. + :param region: The state or region of the new address. + :param postal_code: The postal code of the new address. + :param iso_country: The ISO country code of the new address. + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long. + :param emergency_enabled: Whether to enable emergency calling on the new address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The created AddressInstance + """ + + data = values.of( + { + "CustomerName": customer_name, + "Street": street, + "City": city, + "Region": region, + "PostalCode": postal_code, + "IsoCountry": iso_country, + "FriendlyName": friendly_name, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), + "AutoCorrectAddress": serialize.boolean_to_string(auto_correct_address), + "StreetSecondary": street_secondary, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AddressInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + customer_name: str, + street: str, + city: str, + region: str, + postal_code: str, + iso_country: str, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + auto_correct_address: Union[bool, object] = values.unset, + street_secondary: Union[str, object] = values.unset, + ) -> AddressInstance: + """ + Asynchronously create the AddressInstance + + :param customer_name: The name to associate with the new address. + :param street: The number and street address of the new address. + :param city: The city of the new address. + :param region: The state or region of the new address. + :param postal_code: The postal code of the new address. + :param iso_country: The ISO country code of the new address. + :param friendly_name: A descriptive string that you create to describe the new address. It can be up to 64 characters long. + :param emergency_enabled: Whether to enable emergency calling on the new address. Can be: `true` or `false`. + :param auto_correct_address: Whether we should automatically correct the address. Can be: `true` or `false` and the default is `true`. If empty or `true`, we will correct the address you provide if necessary. If `false`, we won't alter the address you provide. + :param street_secondary: The additional number and street address of the address. + + :returns: The created AddressInstance + """ + + data = values.of( + { + "CustomerName": customer_name, + "Street": street, + "City": city, + "Region": region, + "PostalCode": postal_code, + "IsoCountry": iso_country, + "FriendlyName": friendly_name, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), + "AutoCorrectAddress": serialize.boolean_to_string(auto_correct_address), + "StreetSecondary": street_secondary, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AddressInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + customer_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + iso_country: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AddressInstance]: + """ + Streams AddressInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str customer_name: The `customer_name` of the Address resources to read. + :param str friendly_name: The string that identifies the Address resources to read. + :param bool emergency_enabled: Whether the address can be associated to a number for emergency calling. + :param str iso_country: The ISO country code of the Address resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + customer_name=customer_name, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + iso_country=iso_country, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + customer_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + iso_country: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AddressInstance]: + """ + Asynchronously streams AddressInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str customer_name: The `customer_name` of the Address resources to read. + :param str friendly_name: The string that identifies the Address resources to read. + :param bool emergency_enabled: Whether the address can be associated to a number for emergency calling. + :param str iso_country: The ISO country code of the Address resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + customer_name=customer_name, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + iso_country=iso_country, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + customer_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + iso_country: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AddressInstance]: + """ + Lists AddressInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str customer_name: The `customer_name` of the Address resources to read. + :param str friendly_name: The string that identifies the Address resources to read. + :param bool emergency_enabled: Whether the address can be associated to a number for emergency calling. + :param str iso_country: The ISO country code of the Address resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + customer_name=customer_name, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + iso_country=iso_country, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + customer_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + iso_country: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AddressInstance]: + """ + Asynchronously lists AddressInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str customer_name: The `customer_name` of the Address resources to read. + :param str friendly_name: The string that identifies the Address resources to read. + :param bool emergency_enabled: Whether the address can be associated to a number for emergency calling. + :param str iso_country: The ISO country code of the Address resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + customer_name=customer_name, + friendly_name=friendly_name, + emergency_enabled=emergency_enabled, + iso_country=iso_country, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + customer_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + iso_country: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AddressPage: + """ + Retrieve a single page of AddressInstance records from the API. + Request is executed immediately + + :param customer_name: The `customer_name` of the Address resources to read. + :param friendly_name: The string that identifies the Address resources to read. + :param emergency_enabled: Whether the address can be associated to a number for emergency calling. + :param iso_country: The ISO country code of the Address resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AddressInstance + """ + data = values.of( + { + "CustomerName": customer_name, + "FriendlyName": friendly_name, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), + "IsoCountry": iso_country, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AddressPage(self._version, response, self._solution) + + async def page_async( + self, + customer_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + emergency_enabled: Union[bool, object] = values.unset, + iso_country: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AddressPage: + """ + Asynchronously retrieve a single page of AddressInstance records from the API. + Request is executed immediately + + :param customer_name: The `customer_name` of the Address resources to read. + :param friendly_name: The string that identifies the Address resources to read. + :param emergency_enabled: Whether the address can be associated to a number for emergency calling. + :param iso_country: The ISO country code of the Address resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AddressInstance + """ + data = values.of( + { + "CustomerName": customer_name, + "FriendlyName": friendly_name, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), + "IsoCountry": iso_country, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AddressPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AddressPage: + """ + Retrieve a specific page of AddressInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AddressInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AddressPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AddressPage: + """ + Asynchronously retrieve a specific page of AddressInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AddressInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AddressPage(self._version, response, self._solution) + + def get(self, sid: str) -> AddressContext: + """ + Constructs a AddressContext + + :param sid: The Twilio-provided string that uniquely identifies the Address resource to update. + """ + return AddressContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> AddressContext: + """ + Constructs a AddressContext + + :param sid: The Twilio-provided string that uniquely identifies the Address resource to update. + """ + return AddressContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AddressList>" diff --git a/twilio/rest/api/v2010/account/address/dependent_phone_number.py b/twilio/rest/api/v2010/account/address/dependent_phone_number.py new file mode 100644 index 0000000000..504e69bc92 --- /dev/null +++ b/twilio/rest/api/v2010/account/address/dependent_phone_number.py @@ -0,0 +1,374 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DependentPhoneNumberInstance(InstanceResource): + + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" + + class EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" + + """ + :ivar sid: The unique string that that we created to identify the DependentPhoneNumber resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the DependentPhoneNumber resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar voice_url: The URL we call when the phone number receives a call. The `voice_url` will not be used if a `voice_application_sid` or a `trunk_sid` is set. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_method: The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + :ivar voice_caller_id_lookup: Whether we look up the caller's caller-ID name from the CNAM database. Can be: `true` or `false`. Caller ID lookups can cost $0.01 each. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar sms_fallback_method: The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :ivar sms_fallback_url: The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :ivar sms_method: The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + :ivar sms_url: The URL we call when the phone number receives an incoming SMS message. + :ivar address_requirements: + :ivar capabilities: The set of Boolean properties that indicates whether a phone number can receive calls or messages. Capabilities are `Voice`, `SMS`, and `MMS` and each capability can be: `true` or `false`. + :ivar status_callback: The URL we call using the `status_callback_method` to send status information to your application. + :ivar status_callback_method: The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + :ivar api_version: The API version used to start a new TwiML session. + :ivar sms_application_sid: The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :ivar voice_application_sid: The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :ivar trunk_sid: The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :ivar emergency_status: + :ivar emergency_address_sid: The SID of the emergency address configuration that we use for emergency calling from the phone number. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + address_sid: str, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.phone_number: Optional[str] = payload.get("phone_number") + self.voice_url: Optional[str] = payload.get("voice_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_caller_id_lookup: Optional[bool] = payload.get( + "voice_caller_id_lookup" + ) + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_url: Optional[str] = payload.get("sms_url") + self.address_requirements: Optional[ + "DependentPhoneNumberInstance.AddressRequirement" + ] = payload.get("address_requirements") + self.capabilities: Optional[Dict[str, object]] = payload.get("capabilities") + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.api_version: Optional[str] = payload.get("api_version") + self.sms_application_sid: Optional[str] = payload.get("sms_application_sid") + self.voice_application_sid: Optional[str] = payload.get("voice_application_sid") + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.emergency_status: Optional[ + "DependentPhoneNumberInstance.EmergencyStatus" + ] = payload.get("emergency_status") + self.emergency_address_sid: Optional[str] = payload.get("emergency_address_sid") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "address_sid": address_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.DependentPhoneNumberInstance {}>".format(context) + + +class DependentPhoneNumberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DependentPhoneNumberInstance: + """ + Build an instance of DependentPhoneNumberInstance + + :param payload: Payload response from the API + """ + return DependentPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + address_sid=self._solution["address_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.DependentPhoneNumberPage>" + + +class DependentPhoneNumberList(ListResource): + + def __init__(self, version: Version, account_sid: str, address_sid: str): + """ + Initialize the DependentPhoneNumberList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the DependentPhoneNumber resources to read. + :param address_sid: The SID of the Address resource associated with the phone number. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "address_sid": address_sid, + } + self._uri = "/Accounts/{account_sid}/Addresses/{address_sid}/DependentPhoneNumbers.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DependentPhoneNumberInstance]: + """ + Streams DependentPhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DependentPhoneNumberInstance]: + """ + Asynchronously streams DependentPhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DependentPhoneNumberInstance]: + """ + Lists DependentPhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DependentPhoneNumberInstance]: + """ + Asynchronously lists DependentPhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DependentPhoneNumberPage: + """ + Retrieve a single page of DependentPhoneNumberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DependentPhoneNumberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentPhoneNumberPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DependentPhoneNumberPage: + """ + Asynchronously retrieve a single page of DependentPhoneNumberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DependentPhoneNumberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentPhoneNumberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DependentPhoneNumberPage: + """ + Retrieve a specific page of DependentPhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DependentPhoneNumberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DependentPhoneNumberPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DependentPhoneNumberPage: + """ + Asynchronously retrieve a specific page of DependentPhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DependentPhoneNumberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DependentPhoneNumberPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.DependentPhoneNumberList>" diff --git a/twilio/rest/api/v2010/account/application.py b/twilio/rest/api/v2010/account/application.py new file mode 100644 index 0000000000..555ab72b4a --- /dev/null +++ b/twilio/rest/api/v2010/account/application.py @@ -0,0 +1,984 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ApplicationInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Application resource. + :ivar api_version: The API version used to start a new TwiML session. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar message_status_callback: The URL we call using a POST method to send message status information to your application. + :ivar sid: The unique string that that we created to identify the Application resource. + :ivar sms_fallback_method: The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :ivar sms_fallback_url: The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :ivar sms_method: The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + :ivar sms_status_callback: The URL we call using a POST method to send status information to your application about SMS messages that refer to the application. + :ivar sms_url: The URL we call when the phone number receives an incoming SMS message. + :ivar status_callback: The URL we call using the `status_callback_method` to send status information to your application. + :ivar status_callback_method: The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar voice_caller_id_lookup: Whether we look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :ivar voice_fallback_method: The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_url: The URL we call when the phone number assigned to this application receives a call. + :ivar public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.message_status_callback: Optional[str] = payload.get( + "message_status_callback" + ) + self.sid: Optional[str] = payload.get("sid") + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_status_callback: Optional[str] = payload.get("sms_status_callback") + self.sms_url: Optional[str] = payload.get("sms_url") + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.uri: Optional[str] = payload.get("uri") + self.voice_caller_id_lookup: Optional[bool] = payload.get( + "voice_caller_id_lookup" + ) + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_url: Optional[str] = payload.get("voice_url") + self.public_application_connect_enabled: Optional[bool] = payload.get( + "public_application_connect_enabled" + ) + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[ApplicationContext] = None + + @property + def _proxy(self) -> "ApplicationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ApplicationContext for this ApplicationInstance + """ + if self._context is None: + self._context = ApplicationContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ApplicationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ApplicationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ApplicationInstance": + """ + Fetch the ApplicationInstance + + + :returns: The fetched ApplicationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ApplicationInstance": + """ + Asynchronous coroutine to fetch the ApplicationInstance + + + :returns: The fetched ApplicationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> "ApplicationInstance": + """ + Update the ApplicationInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is your account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: Same as message_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. Deprecated, included for backwards compatibility. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: The updated ApplicationInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + public_application_connect_enabled=public_application_connect_enabled, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> "ApplicationInstance": + """ + Asynchronous coroutine to update the ApplicationInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is your account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: Same as message_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. Deprecated, included for backwards compatibility. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: The updated ApplicationInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + api_version=api_version, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_caller_id_lookup=voice_caller_id_lookup, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + sms_status_callback=sms_status_callback, + message_status_callback=message_status_callback, + public_application_connect_enabled=public_application_connect_enabled, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.ApplicationInstance {}>".format(context) + + +class ApplicationContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the ApplicationContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Application resources to update. + :param sid: The Twilio-provided string that uniquely identifies the Application resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Applications/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the ApplicationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ApplicationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ApplicationInstance: + """ + Fetch the ApplicationInstance + + + :returns: The fetched ApplicationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ApplicationInstance: + """ + Asynchronous coroutine to fetch the ApplicationInstance + + + :returns: The fetched ApplicationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> ApplicationInstance: + """ + Update the ApplicationInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is your account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: Same as message_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. Deprecated, included for backwards compatibility. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: The updated ApplicationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApiVersion": api_version, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsStatusCallback": sms_status_callback, + "MessageStatusCallback": message_status_callback, + "PublicApplicationConnectEnabled": serialize.boolean_to_string( + public_application_connect_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> ApplicationInstance: + """ + Asynchronous coroutine to update the ApplicationInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is your account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: Same as message_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. Deprecated, included for backwards compatibility. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: The updated ApplicationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApiVersion": api_version, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsStatusCallback": sms_status_callback, + "MessageStatusCallback": message_status_callback, + "PublicApplicationConnectEnabled": serialize.boolean_to_string( + public_application_connect_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.ApplicationContext {}>".format(context) + + +class ApplicationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ApplicationInstance: + """ + Build an instance of ApplicationInstance + + :param payload: Payload response from the API + """ + return ApplicationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.ApplicationPage>" + + +class ApplicationList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the ApplicationList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Application resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Applications.json".format(**self._solution) + + def create( + self, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> ApplicationInstance: + """ + Create the ApplicationInstance + + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is the account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param friendly_name: A descriptive string that you create to describe the new application. It can be up to 64 characters long. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: The created ApplicationInstance + """ + + data = values.of( + { + "ApiVersion": api_version, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsStatusCallback": sms_status_callback, + "MessageStatusCallback": message_status_callback, + "FriendlyName": friendly_name, + "PublicApplicationConnectEnabled": serialize.boolean_to_string( + public_application_connect_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ApplicationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + api_version: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_status_callback: Union[str, object] = values.unset, + message_status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + public_application_connect_enabled: Union[bool, object] = values.unset, + ) -> ApplicationInstance: + """ + Asynchronously create the ApplicationInstance + + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. The default value is the account's default API version. + :param voice_url: The URL we should call when the phone number assigned to this application receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`. + :param voice_caller_id_lookup: Whether we should look up the caller's caller-ID name from the CNAM database (additional charges apply). Can be: `true` or `false`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :param sms_status_callback: The URL we should call using a POST method to send status information about SMS messages sent by the application. + :param message_status_callback: The URL we should call using a POST method to send message status information to your application. + :param friendly_name: A descriptive string that you create to describe the new application. It can be up to 64 characters long. + :param public_application_connect_enabled: Whether to allow other Twilio accounts to dial this applicaton using Dial verb. Can be: `true` or `false`. + + :returns: The created ApplicationInstance + """ + + data = values.of( + { + "ApiVersion": api_version, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsStatusCallback": sms_status_callback, + "MessageStatusCallback": message_status_callback, + "FriendlyName": friendly_name, + "PublicApplicationConnectEnabled": serialize.boolean_to_string( + public_application_connect_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ApplicationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ApplicationInstance]: + """ + Streams ApplicationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The string that identifies the Application resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ApplicationInstance]: + """ + Asynchronously streams ApplicationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The string that identifies the Application resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ApplicationInstance]: + """ + Lists ApplicationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The string that identifies the Application resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ApplicationInstance]: + """ + Asynchronously lists ApplicationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The string that identifies the Application resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApplicationPage: + """ + Retrieve a single page of ApplicationInstance records from the API. + Request is executed immediately + + :param friendly_name: The string that identifies the Application resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ApplicationInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ApplicationPage(self._version, response, self._solution) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ApplicationPage: + """ + Asynchronously retrieve a single page of ApplicationInstance records from the API. + Request is executed immediately + + :param friendly_name: The string that identifies the Application resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ApplicationInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ApplicationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ApplicationPage: + """ + Retrieve a specific page of ApplicationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ApplicationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ApplicationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ApplicationPage: + """ + Asynchronously retrieve a specific page of ApplicationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ApplicationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ApplicationPage(self._version, response, self._solution) + + def get(self, sid: str) -> ApplicationContext: + """ + Constructs a ApplicationContext + + :param sid: The Twilio-provided string that uniquely identifies the Application resource to update. + """ + return ApplicationContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ApplicationContext: + """ + Constructs a ApplicationContext + + :param sid: The Twilio-provided string that uniquely identifies the Application resource to update. + """ + return ApplicationContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.ApplicationList>" diff --git a/twilio/rest/api/v2010/account/authorized_connect_app.py b/twilio/rest/api/v2010/account/authorized_connect_app.py new file mode 100644 index 0000000000..cceb694c10 --- /dev/null +++ b/twilio/rest/api/v2010/account/authorized_connect_app.py @@ -0,0 +1,458 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AuthorizedConnectAppInstance(InstanceResource): + + class Permission(object): + GET_ALL = "get-all" + POST_ALL = "post-all" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AuthorizedConnectApp resource. + :ivar connect_app_company_name: The company name set for the Connect App. + :ivar connect_app_description: A detailed description of the Connect App. + :ivar connect_app_friendly_name: The name of the Connect App. + :ivar connect_app_homepage_url: The public URL for the Connect App. + :ivar connect_app_sid: The SID that we assigned to the Connect App. + :ivar permissions: The set of permissions that you authorized for the Connect App. Can be: `get-all` or `post-all`. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + connect_app_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.connect_app_company_name: Optional[str] = payload.get( + "connect_app_company_name" + ) + self.connect_app_description: Optional[str] = payload.get( + "connect_app_description" + ) + self.connect_app_friendly_name: Optional[str] = payload.get( + "connect_app_friendly_name" + ) + self.connect_app_homepage_url: Optional[str] = payload.get( + "connect_app_homepage_url" + ) + self.connect_app_sid: Optional[str] = payload.get("connect_app_sid") + self.permissions: Optional[List["AuthorizedConnectAppInstance.Permission"]] = ( + payload.get("permissions") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "connect_app_sid": connect_app_sid or self.connect_app_sid, + } + self._context: Optional[AuthorizedConnectAppContext] = None + + @property + def _proxy(self) -> "AuthorizedConnectAppContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AuthorizedConnectAppContext for this AuthorizedConnectAppInstance + """ + if self._context is None: + self._context = AuthorizedConnectAppContext( + self._version, + account_sid=self._solution["account_sid"], + connect_app_sid=self._solution["connect_app_sid"], + ) + return self._context + + def fetch(self) -> "AuthorizedConnectAppInstance": + """ + Fetch the AuthorizedConnectAppInstance + + + :returns: The fetched AuthorizedConnectAppInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AuthorizedConnectAppInstance": + """ + Asynchronous coroutine to fetch the AuthorizedConnectAppInstance + + + :returns: The fetched AuthorizedConnectAppInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.AuthorizedConnectAppInstance {}>".format(context) + + +class AuthorizedConnectAppContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, connect_app_sid: str): + """ + Initialize the AuthorizedConnectAppContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AuthorizedConnectApp resource to fetch. + :param connect_app_sid: The SID of the Connect App to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "connect_app_sid": connect_app_sid, + } + self._uri = "/Accounts/{account_sid}/AuthorizedConnectApps/{connect_app_sid}.json".format( + **self._solution + ) + + def fetch(self) -> AuthorizedConnectAppInstance: + """ + Fetch the AuthorizedConnectAppInstance + + + :returns: The fetched AuthorizedConnectAppInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AuthorizedConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + connect_app_sid=self._solution["connect_app_sid"], + ) + + async def fetch_async(self) -> AuthorizedConnectAppInstance: + """ + Asynchronous coroutine to fetch the AuthorizedConnectAppInstance + + + :returns: The fetched AuthorizedConnectAppInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AuthorizedConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + connect_app_sid=self._solution["connect_app_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.AuthorizedConnectAppContext {}>".format(context) + + +class AuthorizedConnectAppPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AuthorizedConnectAppInstance: + """ + Build an instance of AuthorizedConnectAppInstance + + :param payload: Payload response from the API + """ + return AuthorizedConnectAppInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AuthorizedConnectAppPage>" + + +class AuthorizedConnectAppList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the AuthorizedConnectAppList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AuthorizedConnectApp resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/AuthorizedConnectApps.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AuthorizedConnectAppInstance]: + """ + Streams AuthorizedConnectAppInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AuthorizedConnectAppInstance]: + """ + Asynchronously streams AuthorizedConnectAppInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthorizedConnectAppInstance]: + """ + Lists AuthorizedConnectAppInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthorizedConnectAppInstance]: + """ + Asynchronously lists AuthorizedConnectAppInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthorizedConnectAppPage: + """ + Retrieve a single page of AuthorizedConnectAppInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthorizedConnectAppInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthorizedConnectAppPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthorizedConnectAppPage: + """ + Asynchronously retrieve a single page of AuthorizedConnectAppInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthorizedConnectAppInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthorizedConnectAppPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AuthorizedConnectAppPage: + """ + Retrieve a specific page of AuthorizedConnectAppInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthorizedConnectAppInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AuthorizedConnectAppPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AuthorizedConnectAppPage: + """ + Asynchronously retrieve a specific page of AuthorizedConnectAppInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthorizedConnectAppInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AuthorizedConnectAppPage(self._version, response, self._solution) + + def get(self, connect_app_sid: str) -> AuthorizedConnectAppContext: + """ + Constructs a AuthorizedConnectAppContext + + :param connect_app_sid: The SID of the Connect App to fetch. + """ + return AuthorizedConnectAppContext( + self._version, + account_sid=self._solution["account_sid"], + connect_app_sid=connect_app_sid, + ) + + def __call__(self, connect_app_sid: str) -> AuthorizedConnectAppContext: + """ + Constructs a AuthorizedConnectAppContext + + :param connect_app_sid: The SID of the Connect App to fetch. + """ + return AuthorizedConnectAppContext( + self._version, + account_sid=self._solution["account_sid"], + connect_app_sid=connect_app_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AuthorizedConnectAppList>" diff --git a/twilio/rest/api/v2010/account/available_phone_number_country/__init__.py b/twilio/rest/api/v2010/account/available_phone_number_country/__init__.py new file mode 100644 index 0000000000..fc2a6f0600 --- /dev/null +++ b/twilio/rest/api/v2010/account/available_phone_number_country/__init__.py @@ -0,0 +1,612 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.available_phone_number_country.local import LocalList +from twilio.rest.api.v2010.account.available_phone_number_country.machine_to_machine import ( + MachineToMachineList, +) +from twilio.rest.api.v2010.account.available_phone_number_country.mobile import ( + MobileList, +) +from twilio.rest.api.v2010.account.available_phone_number_country.national import ( + NationalList, +) +from twilio.rest.api.v2010.account.available_phone_number_country.shared_cost import ( + SharedCostList, +) +from twilio.rest.api.v2010.account.available_phone_number_country.toll_free import ( + TollFreeList, +) +from twilio.rest.api.v2010.account.available_phone_number_country.voip import VoipList + + +class AvailablePhoneNumberCountryInstance(InstanceResource): + """ + :ivar country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country. + :ivar country: The name of the country. + :ivar uri: The URI of the Country resource, relative to `https://api.twilio.com`. + :ivar beta: Whether all phone numbers available in the country are new to the Twilio platform. `true` if they are and `false` if all numbers are not in the Twilio Phone Number Beta program. + :ivar subresource_uris: A list of related AvailablePhoneNumber resources identified by their URIs relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + country_code: Optional[str] = None, + ): + super().__init__(version) + + self.country_code: Optional[str] = payload.get("country_code") + self.country: Optional[str] = payload.get("country") + self.uri: Optional[str] = payload.get("uri") + self.beta: Optional[bool] = payload.get("beta") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + + self._solution = { + "account_sid": account_sid, + "country_code": country_code or self.country_code, + } + self._context: Optional[AvailablePhoneNumberCountryContext] = None + + @property + def _proxy(self) -> "AvailablePhoneNumberCountryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AvailablePhoneNumberCountryContext for this AvailablePhoneNumberCountryInstance + """ + if self._context is None: + self._context = AvailablePhoneNumberCountryContext( + self._version, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + return self._context + + def fetch(self) -> "AvailablePhoneNumberCountryInstance": + """ + Fetch the AvailablePhoneNumberCountryInstance + + + :returns: The fetched AvailablePhoneNumberCountryInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AvailablePhoneNumberCountryInstance": + """ + Asynchronous coroutine to fetch the AvailablePhoneNumberCountryInstance + + + :returns: The fetched AvailablePhoneNumberCountryInstance + """ + return await self._proxy.fetch_async() + + @property + def local(self) -> LocalList: + """ + Access the local + """ + return self._proxy.local + + @property + def machine_to_machine(self) -> MachineToMachineList: + """ + Access the machine_to_machine + """ + return self._proxy.machine_to_machine + + @property + def mobile(self) -> MobileList: + """ + Access the mobile + """ + return self._proxy.mobile + + @property + def national(self) -> NationalList: + """ + Access the national + """ + return self._proxy.national + + @property + def shared_cost(self) -> SharedCostList: + """ + Access the shared_cost + """ + return self._proxy.shared_cost + + @property + def toll_free(self) -> TollFreeList: + """ + Access the toll_free + """ + return self._proxy.toll_free + + @property + def voip(self) -> VoipList: + """ + Access the voip + """ + return self._proxy.voip + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.AvailablePhoneNumberCountryInstance {}>".format( + context + ) + + +class AvailablePhoneNumberCountryContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, country_code: str): + """ + Initialize the AvailablePhoneNumberCountryContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) requesting the available phone number Country resource. + :param country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country to fetch available phone number information about. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + self._uri = ( + "/Accounts/{account_sid}/AvailablePhoneNumbers/{country_code}.json".format( + **self._solution + ) + ) + + self._local: Optional[LocalList] = None + self._machine_to_machine: Optional[MachineToMachineList] = None + self._mobile: Optional[MobileList] = None + self._national: Optional[NationalList] = None + self._shared_cost: Optional[SharedCostList] = None + self._toll_free: Optional[TollFreeList] = None + self._voip: Optional[VoipList] = None + + def fetch(self) -> AvailablePhoneNumberCountryInstance: + """ + Fetch the AvailablePhoneNumberCountryInstance + + + :returns: The fetched AvailablePhoneNumberCountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AvailablePhoneNumberCountryInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + + async def fetch_async(self) -> AvailablePhoneNumberCountryInstance: + """ + Asynchronous coroutine to fetch the AvailablePhoneNumberCountryInstance + + + :returns: The fetched AvailablePhoneNumberCountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AvailablePhoneNumberCountryInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + + @property + def local(self) -> LocalList: + """ + Access the local + """ + if self._local is None: + self._local = LocalList( + self._version, + self._solution["account_sid"], + self._solution["country_code"], + ) + return self._local + + @property + def machine_to_machine(self) -> MachineToMachineList: + """ + Access the machine_to_machine + """ + if self._machine_to_machine is None: + self._machine_to_machine = MachineToMachineList( + self._version, + self._solution["account_sid"], + self._solution["country_code"], + ) + return self._machine_to_machine + + @property + def mobile(self) -> MobileList: + """ + Access the mobile + """ + if self._mobile is None: + self._mobile = MobileList( + self._version, + self._solution["account_sid"], + self._solution["country_code"], + ) + return self._mobile + + @property + def national(self) -> NationalList: + """ + Access the national + """ + if self._national is None: + self._national = NationalList( + self._version, + self._solution["account_sid"], + self._solution["country_code"], + ) + return self._national + + @property + def shared_cost(self) -> SharedCostList: + """ + Access the shared_cost + """ + if self._shared_cost is None: + self._shared_cost = SharedCostList( + self._version, + self._solution["account_sid"], + self._solution["country_code"], + ) + return self._shared_cost + + @property + def toll_free(self) -> TollFreeList: + """ + Access the toll_free + """ + if self._toll_free is None: + self._toll_free = TollFreeList( + self._version, + self._solution["account_sid"], + self._solution["country_code"], + ) + return self._toll_free + + @property + def voip(self) -> VoipList: + """ + Access the voip + """ + if self._voip is None: + self._voip = VoipList( + self._version, + self._solution["account_sid"], + self._solution["country_code"], + ) + return self._voip + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.AvailablePhoneNumberCountryContext {}>".format( + context + ) + + +class AvailablePhoneNumberCountryPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> AvailablePhoneNumberCountryInstance: + """ + Build an instance of AvailablePhoneNumberCountryInstance + + :param payload: Payload response from the API + """ + return AvailablePhoneNumberCountryInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AvailablePhoneNumberCountryPage>" + + +class AvailablePhoneNumberCountryList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the AvailablePhoneNumberCountryList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) requesting the available phone number Country resources. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/AvailablePhoneNumbers.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AvailablePhoneNumberCountryInstance]: + """ + Streams AvailablePhoneNumberCountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AvailablePhoneNumberCountryInstance]: + """ + Asynchronously streams AvailablePhoneNumberCountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailablePhoneNumberCountryInstance]: + """ + Lists AvailablePhoneNumberCountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailablePhoneNumberCountryInstance]: + """ + Asynchronously lists AvailablePhoneNumberCountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailablePhoneNumberCountryPage: + """ + Retrieve a single page of AvailablePhoneNumberCountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AvailablePhoneNumberCountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailablePhoneNumberCountryPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailablePhoneNumberCountryPage: + """ + Asynchronously retrieve a single page of AvailablePhoneNumberCountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AvailablePhoneNumberCountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailablePhoneNumberCountryPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AvailablePhoneNumberCountryPage: + """ + Retrieve a specific page of AvailablePhoneNumberCountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailablePhoneNumberCountryInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AvailablePhoneNumberCountryPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AvailablePhoneNumberCountryPage: + """ + Asynchronously retrieve a specific page of AvailablePhoneNumberCountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailablePhoneNumberCountryInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AvailablePhoneNumberCountryPage(self._version, response, self._solution) + + def get(self, country_code: str) -> AvailablePhoneNumberCountryContext: + """ + Constructs a AvailablePhoneNumberCountryContext + + :param country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country to fetch available phone number information about. + """ + return AvailablePhoneNumberCountryContext( + self._version, + account_sid=self._solution["account_sid"], + country_code=country_code, + ) + + def __call__(self, country_code: str) -> AvailablePhoneNumberCountryContext: + """ + Constructs a AvailablePhoneNumberCountryContext + + :param country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country to fetch available phone number information about. + """ + return AvailablePhoneNumberCountryContext( + self._version, + account_sid=self._solution["account_sid"], + country_code=country_code, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AvailablePhoneNumberCountryList>" diff --git a/twilio/rest/api/v2010/account/available_phone_number_country/local.py b/twilio/rest/api/v2010/account/available_phone_number_country/local.py new file mode 100644 index 0000000000..4f0b2e7991 --- /dev/null +++ b/twilio/rest/api/v2010/account/available_phone_number_country/local.py @@ -0,0 +1,664 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class LocalInstance(InstanceResource): + """ + :ivar friendly_name: A formatted version of the phone number. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar lata: The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + :ivar locality: The locality or city of this phone number's location. + :ivar rate_center: The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + :ivar latitude: The latitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar longitude: The longitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar region: The two-letter state or province abbreviation of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar postal_code: The postal or ZIP code of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + :ivar address_requirements: The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number's country is required. `foreign` means an address outside of the phone number's country is required. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + country_code: str, + ): + super().__init__(version) + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.phone_number: Optional[str] = payload.get("phone_number") + self.lata: Optional[str] = payload.get("lata") + self.locality: Optional[str] = payload.get("locality") + self.rate_center: Optional[str] = payload.get("rate_center") + self.latitude: Optional[float] = deserialize.decimal(payload.get("latitude")) + self.longitude: Optional[float] = deserialize.decimal(payload.get("longitude")) + self.region: Optional[str] = payload.get("region") + self.postal_code: Optional[str] = payload.get("postal_code") + self.iso_country: Optional[str] = payload.get("iso_country") + self.address_requirements: Optional[str] = payload.get("address_requirements") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.LocalInstance {}>".format(context) + + +class LocalPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> LocalInstance: + """ + Build an instance of LocalInstance + + :param payload: Payload response from the API + """ + return LocalInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.LocalPage>" + + +class LocalList(ListResource): + + def __init__(self, version: Version, account_sid: str, country_code: str): + """ + Initialize the LocalList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) requesting the AvailablePhoneNumber resources. + :param country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country from which to read phone numbers. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + self._uri = "/Accounts/{account_sid}/AvailablePhoneNumbers/{country_code}/Local.json".format( + **self._solution + ) + + def stream( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[LocalInstance]: + """ + Streams LocalInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[LocalInstance]: + """ + Asynchronously streams LocalInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LocalInstance]: + """ + Lists LocalInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LocalInstance]: + """ + Asynchronously lists LocalInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LocalPage: + """ + Retrieve a single page of LocalInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LocalInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LocalPage(self._version, response, self._solution) + + async def page_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LocalPage: + """ + Asynchronously retrieve a single page of LocalInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-number-pattern) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumberlocal-resource?code-sample=code-find-phone-numbers-by-character-pattern). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LocalInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LocalPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> LocalPage: + """ + Retrieve a specific page of LocalInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of LocalInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return LocalPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> LocalPage: + """ + Asynchronously retrieve a specific page of LocalInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of LocalInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return LocalPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.LocalList>" diff --git a/twilio/rest/api/v2010/account/available_phone_number_country/machine_to_machine.py b/twilio/rest/api/v2010/account/available_phone_number_country/machine_to_machine.py new file mode 100644 index 0000000000..5695c917c3 --- /dev/null +++ b/twilio/rest/api/v2010/account/available_phone_number_country/machine_to_machine.py @@ -0,0 +1,664 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MachineToMachineInstance(InstanceResource): + """ + :ivar friendly_name: A formatted version of the phone number. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar lata: The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + :ivar locality: The locality or city of this phone number's location. + :ivar rate_center: The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + :ivar latitude: The latitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar longitude: The longitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar region: The two-letter state or province abbreviation of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar postal_code: The postal or ZIP code of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + :ivar address_requirements: The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number's country is required. `foreign` means an address outside of the phone number's country is required. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + country_code: str, + ): + super().__init__(version) + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.phone_number: Optional[str] = payload.get("phone_number") + self.lata: Optional[str] = payload.get("lata") + self.locality: Optional[str] = payload.get("locality") + self.rate_center: Optional[str] = payload.get("rate_center") + self.latitude: Optional[float] = deserialize.decimal(payload.get("latitude")) + self.longitude: Optional[float] = deserialize.decimal(payload.get("longitude")) + self.region: Optional[str] = payload.get("region") + self.postal_code: Optional[str] = payload.get("postal_code") + self.iso_country: Optional[str] = payload.get("iso_country") + self.address_requirements: Optional[str] = payload.get("address_requirements") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.MachineToMachineInstance {}>".format(context) + + +class MachineToMachinePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MachineToMachineInstance: + """ + Build an instance of MachineToMachineInstance + + :param payload: Payload response from the API + """ + return MachineToMachineInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.MachineToMachinePage>" + + +class MachineToMachineList(ListResource): + + def __init__(self, version: Version, account_sid: str, country_code: str): + """ + Initialize the MachineToMachineList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) requesting the AvailablePhoneNumber resources. + :param country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country from which to read phone numbers. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + self._uri = "/Accounts/{account_sid}/AvailablePhoneNumbers/{country_code}/MachineToMachine.json".format( + **self._solution + ) + + def stream( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MachineToMachineInstance]: + """ + Streams MachineToMachineInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MachineToMachineInstance]: + """ + Asynchronously streams MachineToMachineInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MachineToMachineInstance]: + """ + Lists MachineToMachineInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MachineToMachineInstance]: + """ + Asynchronously lists MachineToMachineInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MachineToMachinePage: + """ + Retrieve a single page of MachineToMachineInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MachineToMachineInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MachineToMachinePage(self._version, response, self._solution) + + async def page_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MachineToMachinePage: + """ + Asynchronously retrieve a single page of MachineToMachineInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MachineToMachineInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MachineToMachinePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MachineToMachinePage: + """ + Retrieve a specific page of MachineToMachineInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MachineToMachineInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MachineToMachinePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MachineToMachinePage: + """ + Asynchronously retrieve a specific page of MachineToMachineInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MachineToMachineInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MachineToMachinePage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.MachineToMachineList>" diff --git a/twilio/rest/api/v2010/account/available_phone_number_country/mobile.py b/twilio/rest/api/v2010/account/available_phone_number_country/mobile.py new file mode 100644 index 0000000000..2382155ee5 --- /dev/null +++ b/twilio/rest/api/v2010/account/available_phone_number_country/mobile.py @@ -0,0 +1,664 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MobileInstance(InstanceResource): + """ + :ivar friendly_name: A formatted version of the phone number. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar lata: The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + :ivar locality: The locality or city of this phone number's location. + :ivar rate_center: The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + :ivar latitude: The latitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar longitude: The longitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar region: The two-letter state or province abbreviation of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar postal_code: The postal or ZIP code of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + :ivar address_requirements: The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number's country is required. `foreign` means an address outside of the phone number's country is required. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + country_code: str, + ): + super().__init__(version) + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.phone_number: Optional[str] = payload.get("phone_number") + self.lata: Optional[str] = payload.get("lata") + self.locality: Optional[str] = payload.get("locality") + self.rate_center: Optional[str] = payload.get("rate_center") + self.latitude: Optional[float] = deserialize.decimal(payload.get("latitude")) + self.longitude: Optional[float] = deserialize.decimal(payload.get("longitude")) + self.region: Optional[str] = payload.get("region") + self.postal_code: Optional[str] = payload.get("postal_code") + self.iso_country: Optional[str] = payload.get("iso_country") + self.address_requirements: Optional[str] = payload.get("address_requirements") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.MobileInstance {}>".format(context) + + +class MobilePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MobileInstance: + """ + Build an instance of MobileInstance + + :param payload: Payload response from the API + """ + return MobileInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.MobilePage>" + + +class MobileList(ListResource): + + def __init__(self, version: Version, account_sid: str, country_code: str): + """ + Initialize the MobileList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) requesting the AvailablePhoneNumber resources. + :param country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country from which to read phone numbers. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + self._uri = "/Accounts/{account_sid}/AvailablePhoneNumbers/{country_code}/Mobile.json".format( + **self._solution + ) + + def stream( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MobileInstance]: + """ + Streams MobileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MobileInstance]: + """ + Asynchronously streams MobileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MobileInstance]: + """ + Lists MobileInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MobileInstance]: + """ + Asynchronously lists MobileInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MobilePage: + """ + Retrieve a single page of MobileInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MobileInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MobilePage(self._version, response, self._solution) + + async def page_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MobilePage: + """ + Asynchronously retrieve a single page of MobileInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MobileInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MobilePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MobilePage: + """ + Retrieve a specific page of MobileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MobileInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MobilePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MobilePage: + """ + Asynchronously retrieve a specific page of MobileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MobileInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MobilePage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.MobileList>" diff --git a/twilio/rest/api/v2010/account/available_phone_number_country/national.py b/twilio/rest/api/v2010/account/available_phone_number_country/national.py new file mode 100644 index 0000000000..a5e926425a --- /dev/null +++ b/twilio/rest/api/v2010/account/available_phone_number_country/national.py @@ -0,0 +1,664 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class NationalInstance(InstanceResource): + """ + :ivar friendly_name: A formatted version of the phone number. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar lata: The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + :ivar locality: The locality or city of this phone number's location. + :ivar rate_center: The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + :ivar latitude: The latitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar longitude: The longitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar region: The two-letter state or province abbreviation of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar postal_code: The postal or ZIP code of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + :ivar address_requirements: The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number's country is required. `foreign` means an address outside of the phone number's country is required. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + country_code: str, + ): + super().__init__(version) + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.phone_number: Optional[str] = payload.get("phone_number") + self.lata: Optional[str] = payload.get("lata") + self.locality: Optional[str] = payload.get("locality") + self.rate_center: Optional[str] = payload.get("rate_center") + self.latitude: Optional[float] = deserialize.decimal(payload.get("latitude")) + self.longitude: Optional[float] = deserialize.decimal(payload.get("longitude")) + self.region: Optional[str] = payload.get("region") + self.postal_code: Optional[str] = payload.get("postal_code") + self.iso_country: Optional[str] = payload.get("iso_country") + self.address_requirements: Optional[str] = payload.get("address_requirements") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.NationalInstance {}>".format(context) + + +class NationalPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> NationalInstance: + """ + Build an instance of NationalInstance + + :param payload: Payload response from the API + """ + return NationalInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.NationalPage>" + + +class NationalList(ListResource): + + def __init__(self, version: Version, account_sid: str, country_code: str): + """ + Initialize the NationalList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) requesting the AvailablePhoneNumber resources. + :param country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country from which to read phone numbers. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + self._uri = "/Accounts/{account_sid}/AvailablePhoneNumbers/{country_code}/National.json".format( + **self._solution + ) + + def stream( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[NationalInstance]: + """ + Streams NationalInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[NationalInstance]: + """ + Asynchronously streams NationalInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NationalInstance]: + """ + Lists NationalInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NationalInstance]: + """ + Asynchronously lists NationalInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NationalPage: + """ + Retrieve a single page of NationalInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NationalInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NationalPage(self._version, response, self._solution) + + async def page_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NationalPage: + """ + Asynchronously retrieve a single page of NationalInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NationalInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NationalPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> NationalPage: + """ + Retrieve a specific page of NationalInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NationalInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return NationalPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> NationalPage: + """ + Asynchronously retrieve a specific page of NationalInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NationalInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return NationalPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.NationalList>" diff --git a/twilio/rest/api/v2010/account/available_phone_number_country/shared_cost.py b/twilio/rest/api/v2010/account/available_phone_number_country/shared_cost.py new file mode 100644 index 0000000000..3a9c02bab4 --- /dev/null +++ b/twilio/rest/api/v2010/account/available_phone_number_country/shared_cost.py @@ -0,0 +1,664 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SharedCostInstance(InstanceResource): + """ + :ivar friendly_name: A formatted version of the phone number. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar lata: The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + :ivar locality: The locality or city of this phone number's location. + :ivar rate_center: The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + :ivar latitude: The latitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar longitude: The longitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar region: The two-letter state or province abbreviation of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar postal_code: The postal or ZIP code of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + :ivar address_requirements: The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number's country is required. `foreign` means an address outside of the phone number's country is required. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + country_code: str, + ): + super().__init__(version) + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.phone_number: Optional[str] = payload.get("phone_number") + self.lata: Optional[str] = payload.get("lata") + self.locality: Optional[str] = payload.get("locality") + self.rate_center: Optional[str] = payload.get("rate_center") + self.latitude: Optional[float] = deserialize.decimal(payload.get("latitude")) + self.longitude: Optional[float] = deserialize.decimal(payload.get("longitude")) + self.region: Optional[str] = payload.get("region") + self.postal_code: Optional[str] = payload.get("postal_code") + self.iso_country: Optional[str] = payload.get("iso_country") + self.address_requirements: Optional[str] = payload.get("address_requirements") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.SharedCostInstance {}>".format(context) + + +class SharedCostPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SharedCostInstance: + """ + Build an instance of SharedCostInstance + + :param payload: Payload response from the API + """ + return SharedCostInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.SharedCostPage>" + + +class SharedCostList(ListResource): + + def __init__(self, version: Version, account_sid: str, country_code: str): + """ + Initialize the SharedCostList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) requesting the AvailablePhoneNumber resources. + :param country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country from which to read phone numbers. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + self._uri = "/Accounts/{account_sid}/AvailablePhoneNumbers/{country_code}/SharedCost.json".format( + **self._solution + ) + + def stream( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SharedCostInstance]: + """ + Streams SharedCostInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SharedCostInstance]: + """ + Asynchronously streams SharedCostInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SharedCostInstance]: + """ + Lists SharedCostInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SharedCostInstance]: + """ + Asynchronously lists SharedCostInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SharedCostPage: + """ + Retrieve a single page of SharedCostInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SharedCostInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SharedCostPage(self._version, response, self._solution) + + async def page_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SharedCostPage: + """ + Asynchronously retrieve a single page of SharedCostInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SharedCostInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SharedCostPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SharedCostPage: + """ + Retrieve a specific page of SharedCostInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SharedCostInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SharedCostPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SharedCostPage: + """ + Asynchronously retrieve a specific page of SharedCostInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SharedCostInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SharedCostPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.SharedCostList>" diff --git a/twilio/rest/api/v2010/account/available_phone_number_country/toll_free.py b/twilio/rest/api/v2010/account/available_phone_number_country/toll_free.py new file mode 100644 index 0000000000..de4a2d9885 --- /dev/null +++ b/twilio/rest/api/v2010/account/available_phone_number_country/toll_free.py @@ -0,0 +1,664 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TollFreeInstance(InstanceResource): + """ + :ivar friendly_name: A formatted version of the phone number. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar lata: The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + :ivar locality: The locality or city of this phone number's location. + :ivar rate_center: The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + :ivar latitude: The latitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar longitude: The longitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar region: The two-letter state or province abbreviation of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar postal_code: The postal or ZIP code of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + :ivar address_requirements: The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number's country is required. `foreign` means an address outside of the phone number's country is required. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + country_code: str, + ): + super().__init__(version) + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.phone_number: Optional[str] = payload.get("phone_number") + self.lata: Optional[str] = payload.get("lata") + self.locality: Optional[str] = payload.get("locality") + self.rate_center: Optional[str] = payload.get("rate_center") + self.latitude: Optional[float] = deserialize.decimal(payload.get("latitude")) + self.longitude: Optional[float] = deserialize.decimal(payload.get("longitude")) + self.region: Optional[str] = payload.get("region") + self.postal_code: Optional[str] = payload.get("postal_code") + self.iso_country: Optional[str] = payload.get("iso_country") + self.address_requirements: Optional[str] = payload.get("address_requirements") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.TollFreeInstance {}>".format(context) + + +class TollFreePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TollFreeInstance: + """ + Build an instance of TollFreeInstance + + :param payload: Payload response from the API + """ + return TollFreeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.TollFreePage>" + + +class TollFreeList(ListResource): + + def __init__(self, version: Version, account_sid: str, country_code: str): + """ + Initialize the TollFreeList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) requesting the AvailablePhoneNumber resources. + :param country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country from which to read phone numbers. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + self._uri = "/Accounts/{account_sid}/AvailablePhoneNumbers/{country_code}/TollFree.json".format( + **self._solution + ) + + def stream( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TollFreeInstance]: + """ + Streams TollFreeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TollFreeInstance]: + """ + Asynchronously streams TollFreeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TollFreeInstance]: + """ + Lists TollFreeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TollFreeInstance]: + """ + Asynchronously lists TollFreeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TollFreePage: + """ + Retrieve a single page of TollFreeInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TollFreeInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TollFreePage(self._version, response, self._solution) + + async def page_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TollFreePage: + """ + Asynchronously retrieve a single page of TollFreeInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TollFreeInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TollFreePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TollFreePage: + """ + Retrieve a specific page of TollFreeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TollFreeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TollFreePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TollFreePage: + """ + Asynchronously retrieve a specific page of TollFreeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TollFreeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TollFreePage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.TollFreeList>" diff --git a/twilio/rest/api/v2010/account/available_phone_number_country/voip.py b/twilio/rest/api/v2010/account/available_phone_number_country/voip.py new file mode 100644 index 0000000000..9ebfae5396 --- /dev/null +++ b/twilio/rest/api/v2010/account/available_phone_number_country/voip.py @@ -0,0 +1,664 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class VoipInstance(InstanceResource): + """ + :ivar friendly_name: A formatted version of the phone number. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar lata: The [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) of this phone number. Available for only phone numbers from the US and Canada. + :ivar locality: The locality or city of this phone number's location. + :ivar rate_center: The [rate center](https://en.wikipedia.org/wiki/Telephone_exchange) of this phone number. Available for only phone numbers from the US and Canada. + :ivar latitude: The latitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar longitude: The longitude of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar region: The two-letter state or province abbreviation of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar postal_code: The postal or ZIP code of this phone number's location. Available for only phone numbers from the US and Canada. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of this phone number. + :ivar address_requirements: The type of [Address](https://www.twilio.com/docs/usage/api/address) resource the phone number requires. Can be: `none`, `any`, `local`, or `foreign`. `none` means no address is required. `any` means an address is required, but it can be anywhere in the world. `local` means an address in the phone number's country is required. `foreign` means an address outside of the phone number's country is required. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + country_code: str, + ): + super().__init__(version) + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.phone_number: Optional[str] = payload.get("phone_number") + self.lata: Optional[str] = payload.get("lata") + self.locality: Optional[str] = payload.get("locality") + self.rate_center: Optional[str] = payload.get("rate_center") + self.latitude: Optional[float] = deserialize.decimal(payload.get("latitude")) + self.longitude: Optional[float] = deserialize.decimal(payload.get("longitude")) + self.region: Optional[str] = payload.get("region") + self.postal_code: Optional[str] = payload.get("postal_code") + self.iso_country: Optional[str] = payload.get("iso_country") + self.address_requirements: Optional[str] = payload.get("address_requirements") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.VoipInstance {}>".format(context) + + +class VoipPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> VoipInstance: + """ + Build an instance of VoipInstance + + :param payload: Payload response from the API + """ + return VoipInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.VoipPage>" + + +class VoipList(ListResource): + + def __init__(self, version: Version, account_sid: str, country_code: str): + """ + Initialize the VoipList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) requesting the AvailablePhoneNumber resources. + :param country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country from which to read phone numbers. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "country_code": country_code, + } + self._uri = "/Accounts/{account_sid}/AvailablePhoneNumbers/{country_code}/Voip.json".format( + **self._solution + ) + + def stream( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[VoipInstance]: + """ + Streams VoipInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[VoipInstance]: + """ + Asynchronously streams VoipInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[VoipInstance]: + """ + Lists VoipInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[VoipInstance]: + """ + Asynchronously lists VoipInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param str contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param bool sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param bool mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param bool voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param bool exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param bool beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param str near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param int distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param str in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param str in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param str in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param str in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param str in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param bool fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + area_code=area_code, + contains=contains, + sms_enabled=sms_enabled, + mms_enabled=mms_enabled, + voice_enabled=voice_enabled, + exclude_all_address_required=exclude_all_address_required, + exclude_local_address_required=exclude_local_address_required, + exclude_foreign_address_required=exclude_foreign_address_required, + beta=beta, + near_number=near_number, + near_lat_long=near_lat_long, + distance=distance, + in_postal_code=in_postal_code, + in_region=in_region, + in_rate_center=in_rate_center, + in_lata=in_lata, + in_locality=in_locality, + fax_enabled=fax_enabled, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> VoipPage: + """ + Retrieve a single page of VoipInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of VoipInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return VoipPage(self._version, response, self._solution) + + async def page_async( + self, + area_code: Union[int, object] = values.unset, + contains: Union[str, object] = values.unset, + sms_enabled: Union[bool, object] = values.unset, + mms_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + exclude_all_address_required: Union[bool, object] = values.unset, + exclude_local_address_required: Union[bool, object] = values.unset, + exclude_foreign_address_required: Union[bool, object] = values.unset, + beta: Union[bool, object] = values.unset, + near_number: Union[str, object] = values.unset, + near_lat_long: Union[str, object] = values.unset, + distance: Union[int, object] = values.unset, + in_postal_code: Union[str, object] = values.unset, + in_region: Union[str, object] = values.unset, + in_rate_center: Union[str, object] = values.unset, + in_lata: Union[str, object] = values.unset, + in_locality: Union[str, object] = values.unset, + fax_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> VoipPage: + """ + Asynchronously retrieve a single page of VoipInstance records from the API. + Request is executed immediately + + :param area_code: The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada. + :param contains: The pattern on which to match phone numbers. Valid characters are `*`, `0-9`, `a-z`, and `A-Z`. The `*` character matches any single digit. For examples, see [Example 2](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-2) and [Example 3](https://www.twilio.com/docs/phone-numbers/api/availablephonenumber-resource#local-get-basic-example-3). If specified, this value must have at least two characters. + :param sms_enabled: Whether the phone numbers can receive text messages. Can be: `true` or `false`. + :param mms_enabled: Whether the phone numbers can receive MMS messages. Can be: `true` or `false`. + :param voice_enabled: Whether the phone numbers can receive calls. Can be: `true` or `false`. + :param exclude_all_address_required: Whether to exclude phone numbers that require an [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_local_address_required: Whether to exclude phone numbers that require a local [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param exclude_foreign_address_required: Whether to exclude phone numbers that require a foreign [Address](https://www.twilio.com/docs/usage/api/address). Can be: `true` or `false` and the default is `false`. + :param beta: Whether to read phone numbers that are new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param near_number: Given a phone number, find a geographically close number within `distance` miles. Distance defaults to 25 miles. Applies to only phone numbers in the US and Canada. + :param near_lat_long: Given a latitude/longitude pair `lat,long` find geographically close numbers within `distance` miles. Applies to only phone numbers in the US and Canada. + :param distance: The search radius, in miles, for a `near_` query. Can be up to `500` and the default is `25`. Applies to only phone numbers in the US and Canada. + :param in_postal_code: Limit results to a particular postal code. Given a phone number, search within the same postal code as that number. Applies to only phone numbers in the US and Canada. + :param in_region: Limit results to a particular region, state, or province. Given a phone number, search within the same region as that number. Applies to only phone numbers in the US and Canada. + :param in_rate_center: Limit results to a specific rate center, or given a phone number search within the same rate center as that number. Requires `in_lata` to be set as well. Applies to only phone numbers in the US and Canada. + :param in_lata: Limit results to a specific local access and transport area ([LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area)). Given a phone number, search within the same [LATA](https://en.wikipedia.org/wiki/Local_access_and_transport_area) as that number. Applies to only phone numbers in the US and Canada. + :param in_locality: Limit results to a particular locality or city. Given a phone number, search within the same Locality as that number. + :param fax_enabled: Whether the phone numbers can receive faxes. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of VoipInstance + """ + data = values.of( + { + "AreaCode": area_code, + "Contains": contains, + "SmsEnabled": serialize.boolean_to_string(sms_enabled), + "MmsEnabled": serialize.boolean_to_string(mms_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "ExcludeAllAddressRequired": serialize.boolean_to_string( + exclude_all_address_required + ), + "ExcludeLocalAddressRequired": serialize.boolean_to_string( + exclude_local_address_required + ), + "ExcludeForeignAddressRequired": serialize.boolean_to_string( + exclude_foreign_address_required + ), + "Beta": serialize.boolean_to_string(beta), + "NearNumber": near_number, + "NearLatLong": near_lat_long, + "Distance": distance, + "InPostalCode": in_postal_code, + "InRegion": in_region, + "InRateCenter": in_rate_center, + "InLata": in_lata, + "InLocality": in_locality, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return VoipPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> VoipPage: + """ + Retrieve a specific page of VoipInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of VoipInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return VoipPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> VoipPage: + """ + Asynchronously retrieve a specific page of VoipInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of VoipInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return VoipPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.VoipList>" diff --git a/twilio/rest/api/v2010/account/balance.py b/twilio/rest/api/v2010/account/balance.py new file mode 100644 index 0000000000..66bb91e9f9 --- /dev/null +++ b/twilio/rest/api/v2010/account/balance.py @@ -0,0 +1,111 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class BalanceInstance(InstanceResource): + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar balance: The balance of the Account, in units specified by the unit parameter. Balance changes may not be reflected immediately. Child accounts do not contain balance information + :ivar currency: The units of currency for the account balance + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.balance: Optional[str] = payload.get("balance") + self.currency: Optional[str] = payload.get("currency") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.BalanceInstance {}>".format(context) + + +class BalanceList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the BalanceList + + :param version: Version that contains the resource + :param account_sid: The unique SID identifier of the Account. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Balance.json".format(**self._solution) + + def fetch(self) -> BalanceInstance: + """ + Asynchronously fetch the BalanceInstance + + + :returns: The fetched BalanceInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return BalanceInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def fetch_async(self) -> BalanceInstance: + """ + Asynchronously fetch the BalanceInstance + + + :returns: The fetched BalanceInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return BalanceInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.BalanceList>" diff --git a/twilio/rest/api/v2010/account/call/__init__.py b/twilio/rest/api/v2010/account/call/__init__.py new file mode 100644 index 0000000000..f7756c40ec --- /dev/null +++ b/twilio/rest/api/v2010/account/call/__init__.py @@ -0,0 +1,1400 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.call.event import EventList +from twilio.rest.api.v2010.account.call.notification import NotificationList +from twilio.rest.api.v2010.account.call.payment import PaymentList +from twilio.rest.api.v2010.account.call.recording import RecordingList +from twilio.rest.api.v2010.account.call.siprec import SiprecList +from twilio.rest.api.v2010.account.call.stream import StreamList +from twilio.rest.api.v2010.account.call.transcription import TranscriptionList +from twilio.rest.api.v2010.account.call.user_defined_message import ( + UserDefinedMessageList, +) +from twilio.rest.api.v2010.account.call.user_defined_message_subscription import ( + UserDefinedMessageSubscriptionList, +) + + +class CallInstance(InstanceResource): + + class Status(object): + QUEUED = "queued" + RINGING = "ringing" + IN_PROGRESS = "in-progress" + COMPLETED = "completed" + BUSY = "busy" + FAILED = "failed" + NO_ANSWER = "no-answer" + CANCELED = "canceled" + + class UpdateStatus(object): + CANCELED = "canceled" + COMPLETED = "completed" + + """ + :ivar sid: The unique string that we created to identify this Call resource. + :ivar date_created: The date and time in UTC that this resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in UTC that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar parent_call_sid: The SID that identifies the call that created this leg. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Call resource. + :ivar to: The phone number, SIP address, Client identifier or SIM SID that received this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `name@company.com`. Client identifiers are formatted `client:name`. SIM SIDs are formatted as `sim:sid`. + :ivar to_formatted: The phone number, SIP address or Client identifier that received this call. Formatted for display. Non-North American phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +442071838750). + :ivar _from: The phone number, SIP address, Client identifier or SIM SID that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `name@company.com`. Client identifiers are formatted `client:name`. SIM SIDs are formatted as `sim:sid`. + :ivar from_formatted: The calling phone number, SIP address, or Client identifier formatted for display. Non-North American phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +442071838750). + :ivar phone_number_sid: If the call was inbound, this is the SID of the IncomingPhoneNumber resource that received the call. If the call was outbound, it is the SID of the OutgoingCallerId resource from which the call was placed. + :ivar status: + :ivar start_time: The start time of the call, given as UTC in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. Empty if the call has not yet been dialed. + :ivar end_time: The time the call ended, given as UTC in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. Empty if the call did not complete successfully. + :ivar duration: The length of the call in seconds. This value is empty for busy, failed, unanswered, or ongoing calls. + :ivar price: The charge for this call, in the currency associated with the account. Populated after the call is completed. May not be immediately available. The price associated with a call only reflects the charge for connectivity. Charges for other call-related features such as Answering Machine Detection, Text-To-Speech, and SIP REFER are not included in this value. + :ivar price_unit: The currency in which `Price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g., `USD`, `EUR`, `JPY`). Always capitalized for calls. + :ivar direction: A string describing the direction of the call. Can be: `inbound` for inbound calls, `outbound-api` for calls initiated via the REST API or `outbound-dial` for calls initiated by a `<Dial>` verb. Using [Elastic SIP Trunking](https://www.twilio.com/docs/sip-trunking), the values can be [`trunking-terminating`](https://www.twilio.com/docs/sip-trunking#termination) for outgoing calls from your communications infrastructure to the PSTN or [`trunking-originating`](https://www.twilio.com/docs/sip-trunking#origination) for incoming calls to your communications infrastructure from the PSTN. + :ivar answered_by: Either `human` or `machine` if this call was initiated with answering machine detection. Empty otherwise. + :ivar api_version: The API version used to create the call. + :ivar forwarded_from: The forwarding phone number if this call was an incoming call forwarded from another number (depends on carrier supporting forwarding). Otherwise, empty. + :ivar group_sid: The Group SID associated with this call. If no Group is associated with the call, the field is empty. + :ivar caller_name: The caller's name if this call was an incoming call to a phone number with caller ID Lookup enabled. Otherwise, empty. + :ivar queue_time: The wait time in milliseconds before the call is placed. + :ivar trunk_sid: The unique identifier of the trunk resource that was used for this call. The field is empty if the call was not made using a SIP trunk or if the call is not terminated. + :ivar uri: The URI of this resource, relative to `https://api.twilio.com`. + :ivar subresource_uris: A list of subresources available to this call, identified by their URIs relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.parent_call_sid: Optional[str] = payload.get("parent_call_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.to: Optional[str] = payload.get("to") + self.to_formatted: Optional[str] = payload.get("to_formatted") + self._from: Optional[str] = payload.get("from") + self.from_formatted: Optional[str] = payload.get("from_formatted") + self.phone_number_sid: Optional[str] = payload.get("phone_number_sid") + self.status: Optional["CallInstance.Status"] = payload.get("status") + self.start_time: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("end_time") + ) + self.duration: Optional[str] = payload.get("duration") + self.price: Optional[str] = payload.get("price") + self.price_unit: Optional[str] = payload.get("price_unit") + self.direction: Optional[str] = payload.get("direction") + self.answered_by: Optional[str] = payload.get("answered_by") + self.api_version: Optional[str] = payload.get("api_version") + self.forwarded_from: Optional[str] = payload.get("forwarded_from") + self.group_sid: Optional[str] = payload.get("group_sid") + self.caller_name: Optional[str] = payload.get("caller_name") + self.queue_time: Optional[str] = payload.get("queue_time") + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.uri: Optional[str] = payload.get("uri") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[CallContext] = None + + @property + def _proxy(self) -> "CallContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CallContext for this CallInstance + """ + if self._context is None: + self._context = CallContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CallInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CallInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CallInstance": + """ + Fetch the CallInstance + + + :returns: The fetched CallInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CallInstance": + """ + Asynchronous coroutine to fetch the CallInstance + + + :returns: The fetched CallInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> "CallInstance": + """ + Update the CallInstance + + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status: + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + + :returns: The updated CallInstance + """ + return self._proxy.update( + url=url, + method=method, + status=status, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + twiml=twiml, + time_limit=time_limit, + ) + + async def update_async( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> "CallInstance": + """ + Asynchronous coroutine to update the CallInstance + + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status: + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + + :returns: The updated CallInstance + """ + return await self._proxy.update_async( + url=url, + method=method, + status=status, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + status_callback_method=status_callback_method, + twiml=twiml, + time_limit=time_limit, + ) + + @property + def events(self) -> EventList: + """ + Access the events + """ + return self._proxy.events + + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + return self._proxy.notifications + + @property + def payments(self) -> PaymentList: + """ + Access the payments + """ + return self._proxy.payments + + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + return self._proxy.recordings + + @property + def siprec(self) -> SiprecList: + """ + Access the siprec + """ + return self._proxy.siprec + + @property + def streams(self) -> StreamList: + """ + Access the streams + """ + return self._proxy.streams + + @property + def transcriptions(self) -> TranscriptionList: + """ + Access the transcriptions + """ + return self._proxy.transcriptions + + @property + def user_defined_messages(self) -> UserDefinedMessageList: + """ + Access the user_defined_messages + """ + return self._proxy.user_defined_messages + + @property + def user_defined_message_subscriptions(self) -> UserDefinedMessageSubscriptionList: + """ + Access the user_defined_message_subscriptions + """ + return self._proxy.user_defined_message_subscriptions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.CallInstance {}>".format(context) + + +class CallContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the CallContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Call resource(s) to update. + :param sid: The Twilio-provided string that uniquely identifies the Call resource to update + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Calls/{sid}.json".format(**self._solution) + + self._events: Optional[EventList] = None + self._notifications: Optional[NotificationList] = None + self._payments: Optional[PaymentList] = None + self._recordings: Optional[RecordingList] = None + self._siprec: Optional[SiprecList] = None + self._streams: Optional[StreamList] = None + self._transcriptions: Optional[TranscriptionList] = None + self._user_defined_messages: Optional[UserDefinedMessageList] = None + self._user_defined_message_subscriptions: Optional[ + UserDefinedMessageSubscriptionList + ] = None + + def delete(self) -> bool: + """ + Deletes the CallInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CallInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CallInstance: + """ + Fetch the CallInstance + + + :returns: The fetched CallInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CallInstance: + """ + Asynchronous coroutine to fetch the CallInstance + + + :returns: The fetched CallInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> CallInstance: + """ + Update the CallInstance + + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status: + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + + :returns: The updated CallInstance + """ + + data = values.of( + { + "Url": url, + "Method": method, + "Status": status, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Twiml": twiml, + "TimeLimit": time_limit, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + url: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + status: Union["CallInstance.UpdateStatus", object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + ) -> CallInstance: + """ + Asynchronous coroutine to update the CallInstance + + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param method: The HTTP method we should use when calling the `url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status: + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_method: The HTTP method we should use when requesting the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url. Twiml and url parameters are mutually exclusive + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + + :returns: The updated CallInstance + """ + + data = values.of( + { + "Url": url, + "Method": method, + "Status": status, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Twiml": twiml, + "TimeLimit": time_limit, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def events(self) -> EventList: + """ + Access the events + """ + if self._events is None: + self._events = EventList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._events + + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + if self._notifications is None: + self._notifications = NotificationList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._notifications + + @property + def payments(self) -> PaymentList: + """ + Access the payments + """ + if self._payments is None: + self._payments = PaymentList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._payments + + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + if self._recordings is None: + self._recordings = RecordingList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._recordings + + @property + def siprec(self) -> SiprecList: + """ + Access the siprec + """ + if self._siprec is None: + self._siprec = SiprecList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._siprec + + @property + def streams(self) -> StreamList: + """ + Access the streams + """ + if self._streams is None: + self._streams = StreamList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._streams + + @property + def transcriptions(self) -> TranscriptionList: + """ + Access the transcriptions + """ + if self._transcriptions is None: + self._transcriptions = TranscriptionList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._transcriptions + + @property + def user_defined_messages(self) -> UserDefinedMessageList: + """ + Access the user_defined_messages + """ + if self._user_defined_messages is None: + self._user_defined_messages = UserDefinedMessageList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._user_defined_messages + + @property + def user_defined_message_subscriptions(self) -> UserDefinedMessageSubscriptionList: + """ + Access the user_defined_message_subscriptions + """ + if self._user_defined_message_subscriptions is None: + self._user_defined_message_subscriptions = ( + UserDefinedMessageSubscriptionList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + ) + return self._user_defined_message_subscriptions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.CallContext {}>".format(context) + + +class CallPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CallInstance: + """ + Build an instance of CallInstance + + :param payload: Payload response from the API + """ + return CallInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.CallPage>" + + +class CallList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the CallList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Call resource(s) to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Calls.json".format(**self._solution) + + def create( + self, + to: str, + from_: str, + method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_event: Union[List[str], object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + send_digits: Union[str, object] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + machine_detection: Union[str, object] = values.unset, + machine_detection_timeout: Union[int, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + trim: Union[str, object] = values.unset, + caller_id: Union[str, object] = values.unset, + machine_detection_speech_threshold: Union[int, object] = values.unset, + machine_detection_speech_end_threshold: Union[int, object] = values.unset, + machine_detection_silence_timeout: Union[int, object] = values.unset, + async_amd: Union[str, object] = values.unset, + async_amd_status_callback: Union[str, object] = values.unset, + async_amd_status_callback_method: Union[str, object] = values.unset, + byoc: Union[str, object] = values.unset, + call_reason: Union[str, object] = values.unset, + call_token: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + url: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + ) -> CallInstance: + """ + Create the CallInstance + + :param to: The phone number, SIP address, or client identifier to call. + :param from_: The phone number or client identifier to use as the caller id. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `From` must also be a phone number. + :param method: The HTTP method we should use when calling the `url` parameter's value. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_event: The call progress events that we will send to the `status_callback` URL. Can be: `initiated`, `ringing`, `answered`, and `completed`. If no event is specified, we send the `completed` status. If you want to receive multiple events, specify each one in a separate `status_callback_event` parameter. See the code sample for [monitoring call progress](https://www.twilio.com/docs/voice/api/call-resource?code-sample=code-create-a-call-resource-and-specify-a-statuscallbackevent&code-sdk-version=json). If an `application_sid` is present, this parameter is ignored. + :param status_callback_method: The HTTP method we should use when calling the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param send_digits: The string of keys to dial after connecting to the number, with a maximum length of 32 digits. Valid digits in the string include any digit (`0`-`9`), '`A`', '`B`', '`C`', '`D`', '`#`', and '`*`'. You can also use '`w`' to insert a half-second pause and '`W`' to insert a one-second pause. For example, to pause for one second after connecting and then dial extension 1234 followed by the # key, set this parameter to `W1234#`. Be sure to URL-encode this string because the '`#`' character has special meaning in a URL. If both `SendDigits` and `MachineDetection` parameters are provided, then `MachineDetection` will be ignored. + :param timeout: The integer number of seconds that we should allow the phone to ring before assuming there is no answer. The default is `60` seconds and the maximum is `600` seconds. For some call flows, we will add a 5-second buffer to the timeout value you provide. For this reason, a timeout value of 10 seconds could result in an actual timeout closer to 15 seconds. You can set this to a short time, such as `15` seconds, to hang up before reaching an answering machine or voicemail. + :param record: Whether to record the call. Can be `true` to record the phone call, or `false` to not. The default is `false`. The `recording_url` is sent to the `status_callback` URL. + :param recording_channels: The number of channels in the final recording. Can be: `mono` or `dual`. The default is `mono`. `mono` records both legs of the call in a single channel of the recording file. `dual` records each leg to a separate channel of the recording file. The first channel of a dual-channel recording contains the parent call and the second channel contains the child call. + :param recording_status_callback: The URL that we call when the recording is available to be accessed. + :param recording_status_callback_method: The HTTP method we should use when calling the `recording_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param sip_auth_username: The username used to authenticate the caller making a SIP call. + :param sip_auth_password: The password required to authenticate the user account specified in `sip_auth_username`. + :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. If `send_digits` is provided, this parameter is ignored. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). + :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. + :param recording_status_callback_event: The recording status events that will trigger calls to the URL specified in `recording_status_callback`. Can be: `in-progress`, `completed` and `absent`. Defaults to `completed`. Separate multiple values with a space. + :param trim: Whether to trim any leading and trailing silence from the recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. + :param caller_id: The phone number, SIP address, or Client identifier that made this call. Phone numbers are in [E.164 format](https://wwnw.twilio.com/docs/glossary/what-e164) (e.g., +16175551212). SIP addresses are formatted as `name@company.com`. + :param machine_detection_speech_threshold: The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. + :param machine_detection_speech_end_threshold: The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. + :param machine_detection_silence_timeout: The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. + :param async_amd: Select whether to perform answering machine detection in the background. Default, blocks the execution of the call until Answering Machine Detection is completed. Can be: `true` or `false`. + :param async_amd_status_callback: The URL that we should call using the `async_amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. + :param async_amd_status_callback_method: The HTTP method we should use when calling the `async_amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param byoc: The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) + :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) + :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url parameter. If both `twiml` and `url` are provided then `twiml` parameter will be ignored. Max 4000 characters. + :param application_sid: The SID of the Application resource that will handle the call, if the call will be handled by an application. + + :returns: The created CallInstance + """ + + data = values.of( + { + "To": to, + "From": from_, + "Method": method, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "StatusCallbackMethod": status_callback_method, + "SendDigits": send_digits, + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "MachineDetection": machine_detection, + "MachineDetectionTimeout": machine_detection_timeout, + "RecordingStatusCallbackEvent": serialize.map( + recording_status_callback_event, lambda e: e + ), + "Trim": trim, + "CallerId": caller_id, + "MachineDetectionSpeechThreshold": machine_detection_speech_threshold, + "MachineDetectionSpeechEndThreshold": machine_detection_speech_end_threshold, + "MachineDetectionSilenceTimeout": machine_detection_silence_timeout, + "AsyncAmd": async_amd, + "AsyncAmdStatusCallback": async_amd_status_callback, + "AsyncAmdStatusCallbackMethod": async_amd_status_callback_method, + "Byoc": byoc, + "CallReason": call_reason, + "CallToken": call_token, + "RecordingTrack": recording_track, + "TimeLimit": time_limit, + "Url": url, + "Twiml": twiml, + "ApplicationSid": application_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CallInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + to: str, + from_: str, + method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_event: Union[List[str], object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + send_digits: Union[str, object] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + machine_detection: Union[str, object] = values.unset, + machine_detection_timeout: Union[int, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + trim: Union[str, object] = values.unset, + caller_id: Union[str, object] = values.unset, + machine_detection_speech_threshold: Union[int, object] = values.unset, + machine_detection_speech_end_threshold: Union[int, object] = values.unset, + machine_detection_silence_timeout: Union[int, object] = values.unset, + async_amd: Union[str, object] = values.unset, + async_amd_status_callback: Union[str, object] = values.unset, + async_amd_status_callback_method: Union[str, object] = values.unset, + byoc: Union[str, object] = values.unset, + call_reason: Union[str, object] = values.unset, + call_token: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + url: Union[str, object] = values.unset, + twiml: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + ) -> CallInstance: + """ + Asynchronously create the CallInstance + + :param to: The phone number, SIP address, or client identifier to call. + :param from_: The phone number or client identifier to use as the caller id. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `From` must also be a phone number. + :param method: The HTTP method we should use when calling the `url` parameter's value. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_url: The URL that we call using the `fallback_method` if an error occurs when requesting or executing the TwiML at `url`. If an `application_sid` parameter is present, this parameter is ignored. + :param fallback_method: The HTTP method that we should use to request the `fallback_url`. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If no `status_callback_event` is specified, we will send the `completed` status. If an `application_sid` parameter is present, this parameter is ignored. URLs must contain a valid hostname (underscores are not permitted). + :param status_callback_event: The call progress events that we will send to the `status_callback` URL. Can be: `initiated`, `ringing`, `answered`, and `completed`. If no event is specified, we send the `completed` status. If you want to receive multiple events, specify each one in a separate `status_callback_event` parameter. See the code sample for [monitoring call progress](https://www.twilio.com/docs/voice/api/call-resource?code-sample=code-create-a-call-resource-and-specify-a-statuscallbackevent&code-sdk-version=json). If an `application_sid` is present, this parameter is ignored. + :param status_callback_method: The HTTP method we should use when calling the `status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. If an `application_sid` parameter is present, this parameter is ignored. + :param send_digits: The string of keys to dial after connecting to the number, with a maximum length of 32 digits. Valid digits in the string include any digit (`0`-`9`), '`A`', '`B`', '`C`', '`D`', '`#`', and '`*`'. You can also use '`w`' to insert a half-second pause and '`W`' to insert a one-second pause. For example, to pause for one second after connecting and then dial extension 1234 followed by the # key, set this parameter to `W1234#`. Be sure to URL-encode this string because the '`#`' character has special meaning in a URL. If both `SendDigits` and `MachineDetection` parameters are provided, then `MachineDetection` will be ignored. + :param timeout: The integer number of seconds that we should allow the phone to ring before assuming there is no answer. The default is `60` seconds and the maximum is `600` seconds. For some call flows, we will add a 5-second buffer to the timeout value you provide. For this reason, a timeout value of 10 seconds could result in an actual timeout closer to 15 seconds. You can set this to a short time, such as `15` seconds, to hang up before reaching an answering machine or voicemail. + :param record: Whether to record the call. Can be `true` to record the phone call, or `false` to not. The default is `false`. The `recording_url` is sent to the `status_callback` URL. + :param recording_channels: The number of channels in the final recording. Can be: `mono` or `dual`. The default is `mono`. `mono` records both legs of the call in a single channel of the recording file. `dual` records each leg to a separate channel of the recording file. The first channel of a dual-channel recording contains the parent call and the second channel contains the child call. + :param recording_status_callback: The URL that we call when the recording is available to be accessed. + :param recording_status_callback_method: The HTTP method we should use when calling the `recording_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param sip_auth_username: The username used to authenticate the caller making a SIP call. + :param sip_auth_password: The password required to authenticate the user account specified in `sip_auth_username`. + :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. If `send_digits` is provided, this parameter is ignored. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). + :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. + :param recording_status_callback_event: The recording status events that will trigger calls to the URL specified in `recording_status_callback`. Can be: `in-progress`, `completed` and `absent`. Defaults to `completed`. Separate multiple values with a space. + :param trim: Whether to trim any leading and trailing silence from the recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. + :param caller_id: The phone number, SIP address, or Client identifier that made this call. Phone numbers are in [E.164 format](https://wwnw.twilio.com/docs/glossary/what-e164) (e.g., +16175551212). SIP addresses are formatted as `name@company.com`. + :param machine_detection_speech_threshold: The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. + :param machine_detection_speech_end_threshold: The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. + :param machine_detection_silence_timeout: The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. + :param async_amd: Select whether to perform answering machine detection in the background. Default, blocks the execution of the call until Answering Machine Detection is completed. Can be: `true` or `false`. + :param async_amd_status_callback: The URL that we should call using the `async_amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. + :param async_amd_status_callback_method: The HTTP method we should use when calling the `async_amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param byoc: The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) + :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) + :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + :param url: The absolute URL that returns the TwiML instructions for the call. We will call this URL using the `method` when the call connects. For more information, see the [Url Parameter](https://www.twilio.com/docs/voice/make-calls#specify-a-url-parameter) section in [Making Calls](https://www.twilio.com/docs/voice/make-calls). + :param twiml: TwiML instructions for the call Twilio will use without fetching Twiml from url parameter. If both `twiml` and `url` are provided then `twiml` parameter will be ignored. Max 4000 characters. + :param application_sid: The SID of the Application resource that will handle the call, if the call will be handled by an application. + + :returns: The created CallInstance + """ + + data = values.of( + { + "To": to, + "From": from_, + "Method": method, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "StatusCallbackMethod": status_callback_method, + "SendDigits": send_digits, + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "MachineDetection": machine_detection, + "MachineDetectionTimeout": machine_detection_timeout, + "RecordingStatusCallbackEvent": serialize.map( + recording_status_callback_event, lambda e: e + ), + "Trim": trim, + "CallerId": caller_id, + "MachineDetectionSpeechThreshold": machine_detection_speech_threshold, + "MachineDetectionSpeechEndThreshold": machine_detection_speech_end_threshold, + "MachineDetectionSilenceTimeout": machine_detection_silence_timeout, + "AsyncAmd": async_amd, + "AsyncAmdStatusCallback": async_amd_status_callback, + "AsyncAmdStatusCallbackMethod": async_amd_status_callback_method, + "Byoc": byoc, + "CallReason": call_reason, + "CallToken": call_token, + "RecordingTrack": recording_track, + "TimeLimit": time_limit, + "Url": url, + "Twiml": twiml, + "ApplicationSid": application_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CallInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CallInstance]: + """ + Streams CallInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param str from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param str parent_call_sid: Only include calls spawned by calls with this SID. + :param "CallInstance.Status" status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + to=to, + from_=from_, + parent_call_sid=parent_call_sid, + status=status, + start_time=start_time, + start_time_before=start_time_before, + start_time_after=start_time_after, + end_time=end_time, + end_time_before=end_time_before, + end_time_after=end_time_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CallInstance]: + """ + Asynchronously streams CallInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param str from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param str parent_call_sid: Only include calls spawned by calls with this SID. + :param "CallInstance.Status" status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + to=to, + from_=from_, + parent_call_sid=parent_call_sid, + status=status, + start_time=start_time, + start_time_before=start_time_before, + start_time_after=start_time_after, + end_time=end_time, + end_time_before=end_time_before, + end_time_after=end_time_after, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CallInstance]: + """ + Lists CallInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param str from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param str parent_call_sid: Only include calls spawned by calls with this SID. + :param "CallInstance.Status" status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + to=to, + from_=from_, + parent_call_sid=parent_call_sid, + status=status, + start_time=start_time, + start_time_before=start_time_before, + start_time_after=start_time_after, + end_time=end_time, + end_time_before=end_time_before, + end_time_after=end_time_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CallInstance]: + """ + Asynchronously lists CallInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param str from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param str parent_call_sid: Only include calls spawned by calls with this SID. + :param "CallInstance.Status" status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param datetime start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param datetime end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param datetime end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + to=to, + from_=from_, + parent_call_sid=parent_call_sid, + status=status, + start_time=start_time, + start_time_before=start_time_before, + start_time_after=start_time_after, + end_time=end_time, + end_time_before=end_time_before, + end_time_after=end_time_after, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CallPage: + """ + Retrieve a single page of CallInstance records from the API. + Request is executed immediately + + :param to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param parent_call_sid: Only include calls spawned by calls with this SID. + :param status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CallInstance + """ + data = values.of( + { + "To": to, + "From": from_, + "ParentCallSid": parent_call_sid, + "Status": status, + "StartTime": serialize.iso8601_datetime(start_time), + "StartTime<": serialize.iso8601_datetime(start_time_before), + "StartTime>": serialize.iso8601_datetime(start_time_after), + "EndTime": serialize.iso8601_datetime(end_time), + "EndTime<": serialize.iso8601_datetime(end_time_before), + "EndTime>": serialize.iso8601_datetime(end_time_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CallPage(self._version, response, self._solution) + + async def page_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + parent_call_sid: Union[str, object] = values.unset, + status: Union["CallInstance.Status", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + start_time_before: Union[datetime, object] = values.unset, + start_time_after: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + end_time_before: Union[datetime, object] = values.unset, + end_time_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CallPage: + """ + Asynchronously retrieve a single page of CallInstance records from the API. + Request is executed immediately + + :param to: Only show calls made to this phone number, SIP address, Client identifier or SIM SID. + :param from_: Only include calls from this phone number, SIP address, Client identifier or SIM SID. + :param parent_call_sid: Only include calls spawned by calls with this SID. + :param status: The status of the calls to include. Can be: `queued`, `ringing`, `in-progress`, `canceled`, `completed`, `failed`, `busy`, or `no-answer`. + :param start_time: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param start_time_before: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param start_time_after: Only include calls that started on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that started on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read calls that started on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read calls that started on or after midnight of this date. + :param end_time: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param end_time_before: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param end_time_after: Only include calls that ended on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only calls that ended on this date. You can also specify an inequality, such as `EndTime<=YYYY-MM-DD`, to read calls that ended on or before midnight of this date, and `EndTime>=YYYY-MM-DD` to read calls that ended on or after midnight of this date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CallInstance + """ + data = values.of( + { + "To": to, + "From": from_, + "ParentCallSid": parent_call_sid, + "Status": status, + "StartTime": serialize.iso8601_datetime(start_time), + "StartTime<": serialize.iso8601_datetime(start_time_before), + "StartTime>": serialize.iso8601_datetime(start_time_after), + "EndTime": serialize.iso8601_datetime(end_time), + "EndTime<": serialize.iso8601_datetime(end_time_before), + "EndTime>": serialize.iso8601_datetime(end_time_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CallPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> CallPage: + """ + Retrieve a specific page of CallInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CallInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CallPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> CallPage: + """ + Asynchronously retrieve a specific page of CallInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CallInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CallPage(self._version, response, self._solution) + + def get(self, sid: str) -> CallContext: + """ + Constructs a CallContext + + :param sid: The Twilio-provided string that uniquely identifies the Call resource to update + """ + return CallContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> CallContext: + """ + Constructs a CallContext + + :param sid: The Twilio-provided string that uniquely identifies the Call resource to update + """ + return CallContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.CallList>" diff --git a/twilio/rest/api/v2010/account/call/event.py b/twilio/rest/api/v2010/account/call/event.py new file mode 100644 index 0000000000..80eb8aa8ba --- /dev/null +++ b/twilio/rest/api/v2010/account/call/event.py @@ -0,0 +1,298 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EventInstance(InstanceResource): + """ + :ivar request: Contains a dictionary representing the request of the call. + :ivar response: Contains a dictionary representing the call response, including a list of the call events. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], account_sid: str, call_sid: str + ): + super().__init__(version) + + self.request: Optional[Dict[str, object]] = payload.get("request") + self.response: Optional[Dict[str, object]] = payload.get("response") + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.EventInstance {}>".format(context) + + +class EventPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EventInstance: + """ + Build an instance of EventInstance + + :param payload: Payload response from the API + """ + return EventInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.EventPage>" + + +class EventList(ListResource): + + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the EventList + + :param version: Version that contains the resource + :param account_sid: The unique SID identifier of the Account. + :param call_sid: The unique SID identifier of the Call. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = "/Accounts/{account_sid}/Calls/{call_sid}/Events.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EventInstance]: + """ + Streams EventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EventInstance]: + """ + Asynchronously streams EventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: + """ + Lists EventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: + """ + Asynchronously lists EventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventPage: + """ + Retrieve a single page of EventInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventPage: + """ + Asynchronously retrieve a single page of EventInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> EventPage: + """ + Retrieve a specific page of EventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EventPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> EventPage: + """ + Asynchronously retrieve a specific page of EventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EventPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.EventList>" diff --git a/twilio/rest/api/v2010/account/call/notification.py b/twilio/rest/api/v2010/account/call/notification.py new file mode 100644 index 0000000000..fd9e8c0d00 --- /dev/null +++ b/twilio/rest/api/v2010/account/call/notification.py @@ -0,0 +1,562 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class NotificationInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Call Notification resource. + :ivar api_version: The API version used to create the Call Notification resource. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Call Notification resource is associated with. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar error_code: A unique error code for the error condition that is described in our [Error Dictionary](https://www.twilio.com/docs/api/errors). + :ivar log: An integer log level that corresponds to the type of notification: `0` is ERROR, `1` is WARNING. + :ivar message_date: The date the notification was actually generated in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. Message buffering can cause this value to differ from `date_created`. + :ivar message_text: The text of the notification. + :ivar more_info: The URL for more information about the error condition. This value is a page in our [Error Dictionary](https://www.twilio.com/docs/api/errors). + :ivar request_method: The HTTP method used to generate the notification. If the notification was generated during a phone call, this is the HTTP Method used to request the resource on your server. If the notification was generated by your use of our REST API, this is the HTTP method used to call the resource on our servers. + :ivar request_url: The URL of the resource that generated the notification. If the notification was generated during a phone call, this is the URL of the resource on your server that caused the notification. If the notification was generated by your use of our REST API, this is the URL of the resource you called. + :ivar request_variables: The HTTP GET or POST variables we sent to your server. However, if the notification was generated by our REST API, this contains the HTTP POST or PUT variables you sent to our API. + :ivar response_body: The HTTP body returned by your server. + :ivar response_headers: The HTTP headers returned by your server. + :ivar sid: The unique string that that we created to identify the Call Notification resource. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + call_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.call_sid: Optional[str] = payload.get("call_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.error_code: Optional[str] = payload.get("error_code") + self.log: Optional[str] = payload.get("log") + self.message_date: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("message_date") + ) + self.message_text: Optional[str] = payload.get("message_text") + self.more_info: Optional[str] = payload.get("more_info") + self.request_method: Optional[str] = payload.get("request_method") + self.request_url: Optional[str] = payload.get("request_url") + self.request_variables: Optional[str] = payload.get("request_variables") + self.response_body: Optional[str] = payload.get("response_body") + self.response_headers: Optional[str] = payload.get("response_headers") + self.sid: Optional[str] = payload.get("sid") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } + self._context: Optional[NotificationContext] = None + + @property + def _proxy(self) -> "NotificationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NotificationContext for this NotificationInstance + """ + if self._context is None: + self._context = NotificationContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "NotificationInstance": + """ + Fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "NotificationInstance": + """ + Asynchronous coroutine to fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.NotificationInstance {}>".format(context) + + +class NotificationContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): + """ + Initialize the NotificationContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Call Notification resource to fetch. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the Call Notification resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Call Notification resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/Notifications/{sid}.json".format( + **self._solution + ) + ) + + def fetch(self) -> NotificationInstance: + """ + Fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> NotificationInstance: + """ + Asynchronous coroutine to fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.NotificationContext {}>".format(context) + + +class NotificationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> NotificationInstance: + """ + Build an instance of NotificationInstance + + :param payload: Payload response from the API + """ + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.NotificationPage>" + + +class NotificationList(ListResource): + + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the NotificationList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Call Notification resources to read. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the Call Notification resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/Notifications.json".format( + **self._solution + ) + ) + + def stream( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[NotificationInstance]: + """ + Streams NotificationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[NotificationInstance]: + """ + Asynchronously streams NotificationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NotificationInstance]: + """ + Lists NotificationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NotificationInstance]: + """ + Asynchronously lists NotificationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NotificationPage: + """ + Retrieve a single page of NotificationInstance records from the API. + Request is executed immediately + + :param log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NotificationInstance + """ + data = values.of( + { + "Log": log, + "MessageDate": serialize.iso8601_date(message_date), + "MessageDate<": serialize.iso8601_date(message_date_before), + "MessageDate>": serialize.iso8601_date(message_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NotificationPage(self._version, response, self._solution) + + async def page_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NotificationPage: + """ + Asynchronously retrieve a single page of NotificationInstance records from the API. + Request is executed immediately + + :param log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NotificationInstance + """ + data = values.of( + { + "Log": log, + "MessageDate": serialize.iso8601_date(message_date), + "MessageDate<": serialize.iso8601_date(message_date_before), + "MessageDate>": serialize.iso8601_date(message_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NotificationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> NotificationPage: + """ + Retrieve a specific page of NotificationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NotificationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return NotificationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> NotificationPage: + """ + Asynchronously retrieve a specific page of NotificationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NotificationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return NotificationPage(self._version, response, self._solution) + + def get(self, sid: str) -> NotificationContext: + """ + Constructs a NotificationContext + + :param sid: The Twilio-provided string that uniquely identifies the Call Notification resource to fetch. + """ + return NotificationContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> NotificationContext: + """ + Constructs a NotificationContext + + :param sid: The Twilio-provided string that uniquely identifies the Call Notification resource to fetch. + """ + return NotificationContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.NotificationList>" diff --git a/twilio/rest/api/v2010/account/call/payment.py b/twilio/rest/api/v2010/account/call/payment.py new file mode 100644 index 0000000000..0f91860987 --- /dev/null +++ b/twilio/rest/api/v2010/account/call/payment.py @@ -0,0 +1,503 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PaymentInstance(InstanceResource): + + class BankAccountType(object): + CONSUMER_CHECKING = "consumer-checking" + CONSUMER_SAVINGS = "consumer-savings" + COMMERCIAL_CHECKING = "commercial-checking" + + class Capture(object): + PAYMENT_CARD_NUMBER = "payment-card-number" + EXPIRATION_DATE = "expiration-date" + SECURITY_CODE = "security-code" + POSTAL_CODE = "postal-code" + BANK_ROUTING_NUMBER = "bank-routing-number" + BANK_ACCOUNT_NUMBER = "bank-account-number" + + class PaymentMethod(object): + CREDIT_CARD = "credit-card" + ACH_DEBIT = "ach-debit" + + class Status(object): + COMPLETE = "complete" + CANCEL = "cancel" + + class TokenType(object): + ONE_TIME = "one-time" + REUSABLE = "reusable" + PAYMENT_METHOD = "payment-method" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Payments resource is associated with. This will refer to the call sid that is producing the payment card (credit/ACH) information thru DTMF. + :ivar sid: The SID of the Payments resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + call_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.sid: Optional[str] = payload.get("sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } + self._context: Optional[PaymentContext] = None + + @property + def _proxy(self) -> "PaymentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PaymentContext for this PaymentInstance + """ + if self._context is None: + self._context = PaymentContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return self._context + + def update( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> "PaymentInstance": + """ + Update the PaymentInstance + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. + :param capture: + :param status: + + :returns: The updated PaymentInstance + """ + return self._proxy.update( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, + ) + + async def update_async( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> "PaymentInstance": + """ + Asynchronous coroutine to update the PaymentInstance + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. + :param capture: + :param status: + + :returns: The updated PaymentInstance + """ + return await self._proxy.update_async( + idempotency_key=idempotency_key, + status_callback=status_callback, + capture=capture, + status=status, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.PaymentInstance {}>".format(context) + + +class PaymentContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): + """ + Initialize the PaymentContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that will update the resource. + :param call_sid: The SID of the call that will update the resource. This should be the same call sid that was used to create payments resource. + :param sid: The SID of Payments session that needs to be updated. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/Payments/{sid}.json".format( + **self._solution + ) + ) + + def update( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> PaymentInstance: + """ + Update the PaymentInstance + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. + :param capture: + :param status: + + :returns: The updated PaymentInstance + """ + + data = values.of( + { + "IdempotencyKey": idempotency_key, + "StatusCallback": status_callback, + "Capture": capture, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PaymentInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + idempotency_key: str, + status_callback: str, + capture: Union["PaymentInstance.Capture", object] = values.unset, + status: Union["PaymentInstance.Status", object] = values.unset, + ) -> PaymentInstance: + """ + Asynchronous coroutine to update the PaymentInstance + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [Update](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-update) and [Complete/Cancel](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback-cancelcomplete) POST requests. + :param capture: + :param status: + + :returns: The updated PaymentInstance + """ + + data = values.of( + { + "IdempotencyKey": idempotency_key, + "StatusCallback": status_callback, + "Capture": capture, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PaymentInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.PaymentContext {}>".format(context) + + +class PaymentList(ListResource): + + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the PaymentList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that will create the resource. + :param call_sid: The SID of the call that will create the resource. Call leg associated with this sid is expected to provide payment information thru DTMF. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = "/Accounts/{account_sid}/Calls/{call_sid}/Payments.json".format( + **self._solution + ) + + def create( + self, + idempotency_key: str, + status_callback: str, + bank_account_type: Union[ + "PaymentInstance.BankAccountType", object + ] = values.unset, + charge_amount: Union[float, object] = values.unset, + currency: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + input: Union[str, object] = values.unset, + min_postal_code_length: Union[int, object] = values.unset, + parameter: Union[object, object] = values.unset, + payment_connector: Union[str, object] = values.unset, + payment_method: Union["PaymentInstance.PaymentMethod", object] = values.unset, + postal_code: Union[bool, object] = values.unset, + security_code: Union[bool, object] = values.unset, + timeout: Union[int, object] = values.unset, + token_type: Union["PaymentInstance.TokenType", object] = values.unset, + valid_card_types: Union[str, object] = values.unset, + ) -> PaymentInstance: + """ + Create the PaymentInstance + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [expected StatusCallback values](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback) + :param bank_account_type: + :param charge_amount: A positive decimal value less than 1,000,000 to charge against the credit card or bank account. Default currency can be overwritten with `currency` field. Leave blank or set to 0 to tokenize. + :param currency: The currency of the `charge_amount`, formatted as [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format. The default value is `USD` and all values allowed from the Pay Connector are accepted. + :param description: The description can be used to provide more details regarding the transaction. This information is submitted along with the payment details to the Payment Connector which are then posted on the transactions. + :param input: A list of inputs that should be accepted. Currently only `dtmf` is supported. All digits captured during a pay session are redacted from the logs. + :param min_postal_code_length: A positive integer that is used to validate the length of the `PostalCode` inputted by the user. User must enter this many digits. + :param parameter: A single-level JSON object used to pass custom parameters to payment processors. (Required for ACH payments). The information that has to be included here depends on the <Pay> Connector. [Read more](https://www.twilio.com/console/voice/pay-connectors). + :param payment_connector: This is the unique name corresponding to the Pay Connector installed in the Twilio Add-ons. Learn more about [<Pay> Connectors](https://www.twilio.com/console/voice/pay-connectors). The default value is `Default`. + :param payment_method: + :param postal_code: Indicates whether the credit card postal code (zip code) is a required piece of payment information that must be provided by the caller. The default is `true`. + :param security_code: Indicates whether the credit card security code is a required piece of payment information that must be provided by the caller. The default is `true`. + :param timeout: The number of seconds that <Pay> should wait for the caller to press a digit between each subsequent digit, after the first one, before moving on to validate the digits captured. The default is `5`, maximum is `600`. + :param token_type: + :param valid_card_types: Credit card types separated by space that Pay should accept. The default value is `visa mastercard amex` + + :returns: The created PaymentInstance + """ + + data = values.of( + { + "IdempotencyKey": idempotency_key, + "StatusCallback": status_callback, + "BankAccountType": bank_account_type, + "ChargeAmount": charge_amount, + "Currency": currency, + "Description": description, + "Input": input, + "MinPostalCodeLength": min_postal_code_length, + "Parameter": serialize.object(parameter), + "PaymentConnector": payment_connector, + "PaymentMethod": payment_method, + "PostalCode": serialize.boolean_to_string(postal_code), + "SecurityCode": serialize.boolean_to_string(security_code), + "Timeout": timeout, + "TokenType": token_type, + "ValidCardTypes": valid_card_types, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PaymentInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_async( + self, + idempotency_key: str, + status_callback: str, + bank_account_type: Union[ + "PaymentInstance.BankAccountType", object + ] = values.unset, + charge_amount: Union[float, object] = values.unset, + currency: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + input: Union[str, object] = values.unset, + min_postal_code_length: Union[int, object] = values.unset, + parameter: Union[object, object] = values.unset, + payment_connector: Union[str, object] = values.unset, + payment_method: Union["PaymentInstance.PaymentMethod", object] = values.unset, + postal_code: Union[bool, object] = values.unset, + security_code: Union[bool, object] = values.unset, + timeout: Union[int, object] = values.unset, + token_type: Union["PaymentInstance.TokenType", object] = values.unset, + valid_card_types: Union[str, object] = values.unset, + ) -> PaymentInstance: + """ + Asynchronously create the PaymentInstance + + :param idempotency_key: A unique token that will be used to ensure that multiple API calls with the same information do not result in multiple transactions. This should be a unique string value per API call and can be a randomly generated. + :param status_callback: Provide an absolute or relative URL to receive status updates regarding your Pay session. Read more about the [expected StatusCallback values](https://www.twilio.com/docs/voice/api/payment-resource#statuscallback) + :param bank_account_type: + :param charge_amount: A positive decimal value less than 1,000,000 to charge against the credit card or bank account. Default currency can be overwritten with `currency` field. Leave blank or set to 0 to tokenize. + :param currency: The currency of the `charge_amount`, formatted as [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format. The default value is `USD` and all values allowed from the Pay Connector are accepted. + :param description: The description can be used to provide more details regarding the transaction. This information is submitted along with the payment details to the Payment Connector which are then posted on the transactions. + :param input: A list of inputs that should be accepted. Currently only `dtmf` is supported. All digits captured during a pay session are redacted from the logs. + :param min_postal_code_length: A positive integer that is used to validate the length of the `PostalCode` inputted by the user. User must enter this many digits. + :param parameter: A single-level JSON object used to pass custom parameters to payment processors. (Required for ACH payments). The information that has to be included here depends on the <Pay> Connector. [Read more](https://www.twilio.com/console/voice/pay-connectors). + :param payment_connector: This is the unique name corresponding to the Pay Connector installed in the Twilio Add-ons. Learn more about [<Pay> Connectors](https://www.twilio.com/console/voice/pay-connectors). The default value is `Default`. + :param payment_method: + :param postal_code: Indicates whether the credit card postal code (zip code) is a required piece of payment information that must be provided by the caller. The default is `true`. + :param security_code: Indicates whether the credit card security code is a required piece of payment information that must be provided by the caller. The default is `true`. + :param timeout: The number of seconds that <Pay> should wait for the caller to press a digit between each subsequent digit, after the first one, before moving on to validate the digits captured. The default is `5`, maximum is `600`. + :param token_type: + :param valid_card_types: Credit card types separated by space that Pay should accept. The default value is `visa mastercard amex` + + :returns: The created PaymentInstance + """ + + data = values.of( + { + "IdempotencyKey": idempotency_key, + "StatusCallback": status_callback, + "BankAccountType": bank_account_type, + "ChargeAmount": charge_amount, + "Currency": currency, + "Description": description, + "Input": input, + "MinPostalCodeLength": min_postal_code_length, + "Parameter": serialize.object(parameter), + "PaymentConnector": payment_connector, + "PaymentMethod": payment_method, + "PostalCode": serialize.boolean_to_string(postal_code), + "SecurityCode": serialize.boolean_to_string(security_code), + "Timeout": timeout, + "TokenType": token_type, + "ValidCardTypes": valid_card_types, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PaymentInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def get(self, sid: str) -> PaymentContext: + """ + Constructs a PaymentContext + + :param sid: The SID of Payments session that needs to be updated. + """ + return PaymentContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> PaymentContext: + """ + Constructs a PaymentContext + + :param sid: The SID of Payments session that needs to be updated. + """ + return PaymentContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.PaymentList>" diff --git a/twilio/rest/api/v2010/account/call/recording.py b/twilio/rest/api/v2010/account/call/recording.py new file mode 100644 index 0000000000..5b93ec6c95 --- /dev/null +++ b/twilio/rest/api/v2010/account/call/recording.py @@ -0,0 +1,822 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RecordingInstance(InstanceResource): + + class Source(object): + DIALVERB = "DialVerb" + CONFERENCE = "Conference" + OUTBOUNDAPI = "OutboundAPI" + TRUNKING = "Trunking" + RECORDVERB = "RecordVerb" + STARTCALLRECORDINGAPI = "StartCallRecordingAPI" + STARTCONFERENCERECORDINGAPI = "StartConferenceRecordingAPI" + + class Status(object): + IN_PROGRESS = "in-progress" + PAUSED = "paused" + STOPPED = "stopped" + PROCESSING = "processing" + COMPLETED = "completed" + ABSENT = "absent" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resource. + :ivar api_version: The API version used to make the recording. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Recording resource is associated with. + :ivar conference_sid: The Conference SID that identifies the conference associated with the recording, if a conference recording. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar start_time: The start time of the recording in GMT and in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar duration: The length of the recording in seconds. + :ivar sid: The unique string that that we created to identify the Recording resource. + :ivar price: The one-time cost of creating the recording in the `price_unit` currency. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar encryption_details: How to decrypt the recording if it was encrypted using [Call Recording Encryption](https://www.twilio.com/docs/voice/tutorials/voice-recording-encryption) feature. + :ivar price_unit: The currency used in the `price` property. Example: `USD`. + :ivar status: + :ivar channels: The number of channels in the final recording file. Can be: `1`, or `2`. Separating a two leg call into two separate channels of the recording file is supported in [Dial](https://www.twilio.com/docs/voice/twiml/dial#attributes-record) and [Outbound Rest API](https://www.twilio.com/docs/voice/make-calls) record options. + :ivar source: + :ivar error_code: The error code that describes why the recording is `absent`. The error code is described in our [Error Dictionary](https://www.twilio.com/docs/api/errors). This value is null if the recording `status` is not `absent`. + :ivar track: The recorded track. Can be: `inbound`, `outbound`, or `both`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + call_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.call_sid: Optional[str] = payload.get("call_sid") + self.conference_sid: Optional[str] = payload.get("conference_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.start_time: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("start_time") + ) + self.duration: Optional[str] = payload.get("duration") + self.sid: Optional[str] = payload.get("sid") + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.uri: Optional[str] = payload.get("uri") + self.encryption_details: Optional[Dict[str, object]] = payload.get( + "encryption_details" + ) + self.price_unit: Optional[str] = payload.get("price_unit") + self.status: Optional["RecordingInstance.Status"] = payload.get("status") + self.channels: Optional[int] = deserialize.integer(payload.get("channels")) + self.source: Optional["RecordingInstance.Source"] = payload.get("source") + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.track: Optional[str] = payload.get("track") + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } + self._context: Optional[RecordingContext] = None + + @property + def _proxy(self) -> "RecordingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RecordingContext for this RecordingInstance + """ + if self._context is None: + self._context = RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RecordingInstance": + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RecordingInstance": + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> "RecordingInstance": + """ + Update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance + """ + return self._proxy.update( + status=status, + pause_behavior=pause_behavior, + ) + + async def update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> "RecordingInstance": + """ + Asynchronous coroutine to update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance + """ + return await self._proxy.update_async( + status=status, + pause_behavior=pause_behavior, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.RecordingInstance {}>".format(context) + + +class RecordingContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): + """ + Initialize the RecordingContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resource to update. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resource to update. + :param sid: The Twilio-provided string that uniquely identifies the Recording resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/Recordings/{sid}.json".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RecordingInstance: + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> RecordingInstance: + """ + Update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance + """ + + data = values.of( + { + "Status": status, + "PauseBehavior": pause_behavior, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> RecordingInstance: + """ + Asynchronous coroutine to update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance + """ + + data = values.of( + { + "Status": status, + "PauseBehavior": pause_behavior, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.RecordingContext {}>".format(context) + + +class RecordingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: + """ + Build an instance of RecordingInstance + + :param payload: Payload response from the API + """ + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.RecordingPage>" + + +class RecordingList(ListResource): + + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the RecordingList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resources to read. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = "/Accounts/{account_sid}/Calls/{call_sid}/Recordings.json".format( + **self._solution + ) + + def create( + self, + recording_status_callback_event: Union[List[str], object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + ) -> RecordingInstance: + """ + Create the RecordingInstance + + :param recording_status_callback_event: The recording status events on which we should call the `recording_status_callback` URL. Can be: `in-progress`, `completed` and `absent` and the default is `completed`. Separate multiple event values with a space. + :param recording_status_callback: The URL we should call using the `recording_status_callback_method` on each recording event specified in `recording_status_callback_event`. For more information, see [RecordingStatusCallback parameters](https://www.twilio.com/docs/voice/api/recording#recordingstatuscallback). + :param recording_status_callback_method: The HTTP method we should use to call `recording_status_callback`. Can be: `GET` or `POST` and the default is `POST`. + :param trim: Whether to trim any leading and trailing silence in the recording. Can be: `trim-silence` or `do-not-trim` and the default is `do-not-trim`. `trim-silence` trims the silence from the beginning and end of the recording and `do-not-trim` does not. + :param recording_channels: The number of channels used in the recording. Can be: `mono` or `dual` and the default is `mono`. `mono` records all parties of the call into one channel. `dual` records each party of a 2-party call into separate channels. + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. + + :returns: The created RecordingInstance + """ + + data = values.of( + { + "RecordingStatusCallbackEvent": serialize.map( + recording_status_callback_event, lambda e: e + ), + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "Trim": trim, + "RecordingChannels": recording_channels, + "RecordingTrack": recording_track, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_async( + self, + recording_status_callback_event: Union[List[str], object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + ) -> RecordingInstance: + """ + Asynchronously create the RecordingInstance + + :param recording_status_callback_event: The recording status events on which we should call the `recording_status_callback` URL. Can be: `in-progress`, `completed` and `absent` and the default is `completed`. Separate multiple event values with a space. + :param recording_status_callback: The URL we should call using the `recording_status_callback_method` on each recording event specified in `recording_status_callback_event`. For more information, see [RecordingStatusCallback parameters](https://www.twilio.com/docs/voice/api/recording#recordingstatuscallback). + :param recording_status_callback_method: The HTTP method we should use to call `recording_status_callback`. Can be: `GET` or `POST` and the default is `POST`. + :param trim: Whether to trim any leading and trailing silence in the recording. Can be: `trim-silence` or `do-not-trim` and the default is `do-not-trim`. `trim-silence` trims the silence from the beginning and end of the recording and `do-not-trim` does not. + :param recording_channels: The number of channels used in the recording. Can be: `mono` or `dual` and the default is `mono`. `mono` records all parties of the call into one channel. `dual` records each party of a 2-party call into separate channels. + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is generated from Twilio. `both` records the audio that is received and generated by Twilio. + + :returns: The created RecordingInstance + """ + + data = values.of( + { + "RecordingStatusCallbackEvent": serialize.map( + recording_status_callback_event, lambda e: e + ), + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "Trim": trim, + "RecordingChannels": recording_channels, + "RecordingTrack": recording_track, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def stream( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RecordingInstance]: + """ + Streams RecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RecordingInstance]: + """ + Asynchronously streams RecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordingInstance]: + """ + Lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordingInstance]: + """ + Asynchronously lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordingPage: + """ + Retrieve a single page of RecordingInstance records from the API. + Request is executed immediately + + :param date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordingInstance + """ + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response, self._solution) + + async def page_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordingPage: + """ + Asynchronously retrieve a single page of RecordingInstance records from the API. + Request is executed immediately + + :param date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordingInstance + """ + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RecordingPage: + """ + Retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RecordingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RecordingPage: + """ + Asynchronously retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RecordingPage(self._version, response, self._solution) + + def get(self, sid: str) -> RecordingContext: + """ + Constructs a RecordingContext + + :param sid: The Twilio-provided string that uniquely identifies the Recording resource to update. + """ + return RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> RecordingContext: + """ + Constructs a RecordingContext + + :param sid: The Twilio-provided string that uniquely identifies the Recording resource to update. + """ + return RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.RecordingList>" diff --git a/twilio/rest/api/v2010/account/call/siprec.py b/twilio/rest/api/v2010/account/call/siprec.py new file mode 100644 index 0000000000..d808331c64 --- /dev/null +++ b/twilio/rest/api/v2010/account/call/siprec.py @@ -0,0 +1,1561 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SiprecInstance(InstanceResource): + + class Status(object): + IN_PROGRESS = "in-progress" + STOPPED = "stopped" + + class Track(object): + INBOUND_TRACK = "inbound_track" + OUTBOUND_TRACK = "outbound_track" + BOTH_TRACKS = "both_tracks" + + class UpdateStatus(object): + STOPPED = "stopped" + + """ + :ivar sid: The SID of the Siprec resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Siprec resource. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Siprec resource is associated with. + :ivar name: The user-specified name of this Siprec, if one was given when the Siprec was created. This may be used to stop the Siprec. + :ivar status: + :ivar date_updated: The date and time in GMT that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + call_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.name: Optional[str] = payload.get("name") + self.status: Optional["SiprecInstance.Status"] = payload.get("status") + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } + self._context: Optional[SiprecContext] = None + + @property + def _proxy(self) -> "SiprecContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SiprecContext for this SiprecInstance + """ + if self._context is None: + self._context = SiprecContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return self._context + + def update(self, status: "SiprecInstance.UpdateStatus") -> "SiprecInstance": + """ + Update the SiprecInstance + + :param status: + + :returns: The updated SiprecInstance + """ + return self._proxy.update( + status=status, + ) + + async def update_async( + self, status: "SiprecInstance.UpdateStatus" + ) -> "SiprecInstance": + """ + Asynchronous coroutine to update the SiprecInstance + + :param status: + + :returns: The updated SiprecInstance + """ + return await self._proxy.update_async( + status=status, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.SiprecInstance {}>".format(context) + + +class SiprecContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): + """ + Initialize the SiprecContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Siprec resource. + :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Siprec resource is associated with. + :param sid: The SID of the Siprec resource, or the `name` used when creating the resource + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Calls/{call_sid}/Siprec/{sid}.json".format( + **self._solution + ) + + def update(self, status: "SiprecInstance.UpdateStatus") -> SiprecInstance: + """ + Update the SiprecInstance + + :param status: + + :returns: The updated SiprecInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, status: "SiprecInstance.UpdateStatus" + ) -> SiprecInstance: + """ + Asynchronous coroutine to update the SiprecInstance + + :param status: + + :returns: The updated SiprecInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.SiprecContext {}>".format(context) + + +class SiprecList(ListResource): + + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the SiprecList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Siprec resource. + :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Siprec resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = "/Accounts/{account_sid}/Calls/{call_sid}/Siprec.json".format( + **self._solution + ) + + def create( + self, + name: Union[str, object] = values.unset, + connector_name: Union[str, object] = values.unset, + track: Union["SiprecInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> SiprecInstance: + """ + Create the SiprecInstance + + :param name: The user-specified name of this Siprec, if one was given when the Siprec was created. This may be used to stop the Siprec. + :param connector_name: Unique name used when configuring the connector via Marketplace Add-on. + :param track: + :param status_callback: Absolute URL of the status callback. + :param status_callback_method: The http method for the status_callback (one of GET, POST). + :param parameter1_name: Parameter name + :param parameter1_value: Parameter value + :param parameter2_name: Parameter name + :param parameter2_value: Parameter value + :param parameter3_name: Parameter name + :param parameter3_value: Parameter value + :param parameter4_name: Parameter name + :param parameter4_value: Parameter value + :param parameter5_name: Parameter name + :param parameter5_value: Parameter value + :param parameter6_name: Parameter name + :param parameter6_value: Parameter value + :param parameter7_name: Parameter name + :param parameter7_value: Parameter value + :param parameter8_name: Parameter name + :param parameter8_value: Parameter value + :param parameter9_name: Parameter name + :param parameter9_value: Parameter value + :param parameter10_name: Parameter name + :param parameter10_value: Parameter value + :param parameter11_name: Parameter name + :param parameter11_value: Parameter value + :param parameter12_name: Parameter name + :param parameter12_value: Parameter value + :param parameter13_name: Parameter name + :param parameter13_value: Parameter value + :param parameter14_name: Parameter name + :param parameter14_value: Parameter value + :param parameter15_name: Parameter name + :param parameter15_value: Parameter value + :param parameter16_name: Parameter name + :param parameter16_value: Parameter value + :param parameter17_name: Parameter name + :param parameter17_value: Parameter value + :param parameter18_name: Parameter name + :param parameter18_value: Parameter value + :param parameter19_name: Parameter name + :param parameter19_value: Parameter value + :param parameter20_name: Parameter name + :param parameter20_value: Parameter value + :param parameter21_name: Parameter name + :param parameter21_value: Parameter value + :param parameter22_name: Parameter name + :param parameter22_value: Parameter value + :param parameter23_name: Parameter name + :param parameter23_value: Parameter value + :param parameter24_name: Parameter name + :param parameter24_value: Parameter value + :param parameter25_name: Parameter name + :param parameter25_value: Parameter value + :param parameter26_name: Parameter name + :param parameter26_value: Parameter value + :param parameter27_name: Parameter name + :param parameter27_value: Parameter value + :param parameter28_name: Parameter name + :param parameter28_value: Parameter value + :param parameter29_name: Parameter name + :param parameter29_value: Parameter value + :param parameter30_name: Parameter name + :param parameter30_value: Parameter value + :param parameter31_name: Parameter name + :param parameter31_value: Parameter value + :param parameter32_name: Parameter name + :param parameter32_value: Parameter value + :param parameter33_name: Parameter name + :param parameter33_value: Parameter value + :param parameter34_name: Parameter name + :param parameter34_value: Parameter value + :param parameter35_name: Parameter name + :param parameter35_value: Parameter value + :param parameter36_name: Parameter name + :param parameter36_value: Parameter value + :param parameter37_name: Parameter name + :param parameter37_value: Parameter value + :param parameter38_name: Parameter name + :param parameter38_value: Parameter value + :param parameter39_name: Parameter name + :param parameter39_value: Parameter value + :param parameter40_name: Parameter name + :param parameter40_value: Parameter value + :param parameter41_name: Parameter name + :param parameter41_value: Parameter value + :param parameter42_name: Parameter name + :param parameter42_value: Parameter value + :param parameter43_name: Parameter name + :param parameter43_value: Parameter value + :param parameter44_name: Parameter name + :param parameter44_value: Parameter value + :param parameter45_name: Parameter name + :param parameter45_value: Parameter value + :param parameter46_name: Parameter name + :param parameter46_value: Parameter value + :param parameter47_name: Parameter name + :param parameter47_value: Parameter value + :param parameter48_name: Parameter name + :param parameter48_value: Parameter value + :param parameter49_name: Parameter name + :param parameter49_value: Parameter value + :param parameter50_name: Parameter name + :param parameter50_value: Parameter value + :param parameter51_name: Parameter name + :param parameter51_value: Parameter value + :param parameter52_name: Parameter name + :param parameter52_value: Parameter value + :param parameter53_name: Parameter name + :param parameter53_value: Parameter value + :param parameter54_name: Parameter name + :param parameter54_value: Parameter value + :param parameter55_name: Parameter name + :param parameter55_value: Parameter value + :param parameter56_name: Parameter name + :param parameter56_value: Parameter value + :param parameter57_name: Parameter name + :param parameter57_value: Parameter value + :param parameter58_name: Parameter name + :param parameter58_value: Parameter value + :param parameter59_name: Parameter name + :param parameter59_value: Parameter value + :param parameter60_name: Parameter name + :param parameter60_value: Parameter value + :param parameter61_name: Parameter name + :param parameter61_value: Parameter value + :param parameter62_name: Parameter name + :param parameter62_value: Parameter value + :param parameter63_name: Parameter name + :param parameter63_value: Parameter value + :param parameter64_name: Parameter name + :param parameter64_value: Parameter value + :param parameter65_name: Parameter name + :param parameter65_value: Parameter value + :param parameter66_name: Parameter name + :param parameter66_value: Parameter value + :param parameter67_name: Parameter name + :param parameter67_value: Parameter value + :param parameter68_name: Parameter name + :param parameter68_value: Parameter value + :param parameter69_name: Parameter name + :param parameter69_value: Parameter value + :param parameter70_name: Parameter name + :param parameter70_value: Parameter value + :param parameter71_name: Parameter name + :param parameter71_value: Parameter value + :param parameter72_name: Parameter name + :param parameter72_value: Parameter value + :param parameter73_name: Parameter name + :param parameter73_value: Parameter value + :param parameter74_name: Parameter name + :param parameter74_value: Parameter value + :param parameter75_name: Parameter name + :param parameter75_value: Parameter value + :param parameter76_name: Parameter name + :param parameter76_value: Parameter value + :param parameter77_name: Parameter name + :param parameter77_value: Parameter value + :param parameter78_name: Parameter name + :param parameter78_value: Parameter value + :param parameter79_name: Parameter name + :param parameter79_value: Parameter value + :param parameter80_name: Parameter name + :param parameter80_value: Parameter value + :param parameter81_name: Parameter name + :param parameter81_value: Parameter value + :param parameter82_name: Parameter name + :param parameter82_value: Parameter value + :param parameter83_name: Parameter name + :param parameter83_value: Parameter value + :param parameter84_name: Parameter name + :param parameter84_value: Parameter value + :param parameter85_name: Parameter name + :param parameter85_value: Parameter value + :param parameter86_name: Parameter name + :param parameter86_value: Parameter value + :param parameter87_name: Parameter name + :param parameter87_value: Parameter value + :param parameter88_name: Parameter name + :param parameter88_value: Parameter value + :param parameter89_name: Parameter name + :param parameter89_value: Parameter value + :param parameter90_name: Parameter name + :param parameter90_value: Parameter value + :param parameter91_name: Parameter name + :param parameter91_value: Parameter value + :param parameter92_name: Parameter name + :param parameter92_value: Parameter value + :param parameter93_name: Parameter name + :param parameter93_value: Parameter value + :param parameter94_name: Parameter name + :param parameter94_value: Parameter value + :param parameter95_name: Parameter name + :param parameter95_value: Parameter value + :param parameter96_name: Parameter name + :param parameter96_value: Parameter value + :param parameter97_name: Parameter name + :param parameter97_value: Parameter value + :param parameter98_name: Parameter name + :param parameter98_value: Parameter value + :param parameter99_name: Parameter name + :param parameter99_value: Parameter value + + :returns: The created SiprecInstance + """ + + data = values.of( + { + "Name": name, + "ConnectorName": connector_name, + "Track": track, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Parameter1.Name": parameter1_name, + "Parameter1.Value": parameter1_value, + "Parameter2.Name": parameter2_name, + "Parameter2.Value": parameter2_value, + "Parameter3.Name": parameter3_name, + "Parameter3.Value": parameter3_value, + "Parameter4.Name": parameter4_name, + "Parameter4.Value": parameter4_value, + "Parameter5.Name": parameter5_name, + "Parameter5.Value": parameter5_value, + "Parameter6.Name": parameter6_name, + "Parameter6.Value": parameter6_value, + "Parameter7.Name": parameter7_name, + "Parameter7.Value": parameter7_value, + "Parameter8.Name": parameter8_name, + "Parameter8.Value": parameter8_value, + "Parameter9.Name": parameter9_name, + "Parameter9.Value": parameter9_value, + "Parameter10.Name": parameter10_name, + "Parameter10.Value": parameter10_value, + "Parameter11.Name": parameter11_name, + "Parameter11.Value": parameter11_value, + "Parameter12.Name": parameter12_name, + "Parameter12.Value": parameter12_value, + "Parameter13.Name": parameter13_name, + "Parameter13.Value": parameter13_value, + "Parameter14.Name": parameter14_name, + "Parameter14.Value": parameter14_value, + "Parameter15.Name": parameter15_name, + "Parameter15.Value": parameter15_value, + "Parameter16.Name": parameter16_name, + "Parameter16.Value": parameter16_value, + "Parameter17.Name": parameter17_name, + "Parameter17.Value": parameter17_value, + "Parameter18.Name": parameter18_name, + "Parameter18.Value": parameter18_value, + "Parameter19.Name": parameter19_name, + "Parameter19.Value": parameter19_value, + "Parameter20.Name": parameter20_name, + "Parameter20.Value": parameter20_value, + "Parameter21.Name": parameter21_name, + "Parameter21.Value": parameter21_value, + "Parameter22.Name": parameter22_name, + "Parameter22.Value": parameter22_value, + "Parameter23.Name": parameter23_name, + "Parameter23.Value": parameter23_value, + "Parameter24.Name": parameter24_name, + "Parameter24.Value": parameter24_value, + "Parameter25.Name": parameter25_name, + "Parameter25.Value": parameter25_value, + "Parameter26.Name": parameter26_name, + "Parameter26.Value": parameter26_value, + "Parameter27.Name": parameter27_name, + "Parameter27.Value": parameter27_value, + "Parameter28.Name": parameter28_name, + "Parameter28.Value": parameter28_value, + "Parameter29.Name": parameter29_name, + "Parameter29.Value": parameter29_value, + "Parameter30.Name": parameter30_name, + "Parameter30.Value": parameter30_value, + "Parameter31.Name": parameter31_name, + "Parameter31.Value": parameter31_value, + "Parameter32.Name": parameter32_name, + "Parameter32.Value": parameter32_value, + "Parameter33.Name": parameter33_name, + "Parameter33.Value": parameter33_value, + "Parameter34.Name": parameter34_name, + "Parameter34.Value": parameter34_value, + "Parameter35.Name": parameter35_name, + "Parameter35.Value": parameter35_value, + "Parameter36.Name": parameter36_name, + "Parameter36.Value": parameter36_value, + "Parameter37.Name": parameter37_name, + "Parameter37.Value": parameter37_value, + "Parameter38.Name": parameter38_name, + "Parameter38.Value": parameter38_value, + "Parameter39.Name": parameter39_name, + "Parameter39.Value": parameter39_value, + "Parameter40.Name": parameter40_name, + "Parameter40.Value": parameter40_value, + "Parameter41.Name": parameter41_name, + "Parameter41.Value": parameter41_value, + "Parameter42.Name": parameter42_name, + "Parameter42.Value": parameter42_value, + "Parameter43.Name": parameter43_name, + "Parameter43.Value": parameter43_value, + "Parameter44.Name": parameter44_name, + "Parameter44.Value": parameter44_value, + "Parameter45.Name": parameter45_name, + "Parameter45.Value": parameter45_value, + "Parameter46.Name": parameter46_name, + "Parameter46.Value": parameter46_value, + "Parameter47.Name": parameter47_name, + "Parameter47.Value": parameter47_value, + "Parameter48.Name": parameter48_name, + "Parameter48.Value": parameter48_value, + "Parameter49.Name": parameter49_name, + "Parameter49.Value": parameter49_value, + "Parameter50.Name": parameter50_name, + "Parameter50.Value": parameter50_value, + "Parameter51.Name": parameter51_name, + "Parameter51.Value": parameter51_value, + "Parameter52.Name": parameter52_name, + "Parameter52.Value": parameter52_value, + "Parameter53.Name": parameter53_name, + "Parameter53.Value": parameter53_value, + "Parameter54.Name": parameter54_name, + "Parameter54.Value": parameter54_value, + "Parameter55.Name": parameter55_name, + "Parameter55.Value": parameter55_value, + "Parameter56.Name": parameter56_name, + "Parameter56.Value": parameter56_value, + "Parameter57.Name": parameter57_name, + "Parameter57.Value": parameter57_value, + "Parameter58.Name": parameter58_name, + "Parameter58.Value": parameter58_value, + "Parameter59.Name": parameter59_name, + "Parameter59.Value": parameter59_value, + "Parameter60.Name": parameter60_name, + "Parameter60.Value": parameter60_value, + "Parameter61.Name": parameter61_name, + "Parameter61.Value": parameter61_value, + "Parameter62.Name": parameter62_name, + "Parameter62.Value": parameter62_value, + "Parameter63.Name": parameter63_name, + "Parameter63.Value": parameter63_value, + "Parameter64.Name": parameter64_name, + "Parameter64.Value": parameter64_value, + "Parameter65.Name": parameter65_name, + "Parameter65.Value": parameter65_value, + "Parameter66.Name": parameter66_name, + "Parameter66.Value": parameter66_value, + "Parameter67.Name": parameter67_name, + "Parameter67.Value": parameter67_value, + "Parameter68.Name": parameter68_name, + "Parameter68.Value": parameter68_value, + "Parameter69.Name": parameter69_name, + "Parameter69.Value": parameter69_value, + "Parameter70.Name": parameter70_name, + "Parameter70.Value": parameter70_value, + "Parameter71.Name": parameter71_name, + "Parameter71.Value": parameter71_value, + "Parameter72.Name": parameter72_name, + "Parameter72.Value": parameter72_value, + "Parameter73.Name": parameter73_name, + "Parameter73.Value": parameter73_value, + "Parameter74.Name": parameter74_name, + "Parameter74.Value": parameter74_value, + "Parameter75.Name": parameter75_name, + "Parameter75.Value": parameter75_value, + "Parameter76.Name": parameter76_name, + "Parameter76.Value": parameter76_value, + "Parameter77.Name": parameter77_name, + "Parameter77.Value": parameter77_value, + "Parameter78.Name": parameter78_name, + "Parameter78.Value": parameter78_value, + "Parameter79.Name": parameter79_name, + "Parameter79.Value": parameter79_value, + "Parameter80.Name": parameter80_name, + "Parameter80.Value": parameter80_value, + "Parameter81.Name": parameter81_name, + "Parameter81.Value": parameter81_value, + "Parameter82.Name": parameter82_name, + "Parameter82.Value": parameter82_value, + "Parameter83.Name": parameter83_name, + "Parameter83.Value": parameter83_value, + "Parameter84.Name": parameter84_name, + "Parameter84.Value": parameter84_value, + "Parameter85.Name": parameter85_name, + "Parameter85.Value": parameter85_value, + "Parameter86.Name": parameter86_name, + "Parameter86.Value": parameter86_value, + "Parameter87.Name": parameter87_name, + "Parameter87.Value": parameter87_value, + "Parameter88.Name": parameter88_name, + "Parameter88.Value": parameter88_value, + "Parameter89.Name": parameter89_name, + "Parameter89.Value": parameter89_value, + "Parameter90.Name": parameter90_name, + "Parameter90.Value": parameter90_value, + "Parameter91.Name": parameter91_name, + "Parameter91.Value": parameter91_value, + "Parameter92.Name": parameter92_name, + "Parameter92.Value": parameter92_value, + "Parameter93.Name": parameter93_name, + "Parameter93.Value": parameter93_value, + "Parameter94.Name": parameter94_name, + "Parameter94.Value": parameter94_value, + "Parameter95.Name": parameter95_name, + "Parameter95.Value": parameter95_value, + "Parameter96.Name": parameter96_name, + "Parameter96.Value": parameter96_value, + "Parameter97.Name": parameter97_name, + "Parameter97.Value": parameter97_value, + "Parameter98.Name": parameter98_name, + "Parameter98.Value": parameter98_value, + "Parameter99.Name": parameter99_name, + "Parameter99.Value": parameter99_value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_async( + self, + name: Union[str, object] = values.unset, + connector_name: Union[str, object] = values.unset, + track: Union["SiprecInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> SiprecInstance: + """ + Asynchronously create the SiprecInstance + + :param name: The user-specified name of this Siprec, if one was given when the Siprec was created. This may be used to stop the Siprec. + :param connector_name: Unique name used when configuring the connector via Marketplace Add-on. + :param track: + :param status_callback: Absolute URL of the status callback. + :param status_callback_method: The http method for the status_callback (one of GET, POST). + :param parameter1_name: Parameter name + :param parameter1_value: Parameter value + :param parameter2_name: Parameter name + :param parameter2_value: Parameter value + :param parameter3_name: Parameter name + :param parameter3_value: Parameter value + :param parameter4_name: Parameter name + :param parameter4_value: Parameter value + :param parameter5_name: Parameter name + :param parameter5_value: Parameter value + :param parameter6_name: Parameter name + :param parameter6_value: Parameter value + :param parameter7_name: Parameter name + :param parameter7_value: Parameter value + :param parameter8_name: Parameter name + :param parameter8_value: Parameter value + :param parameter9_name: Parameter name + :param parameter9_value: Parameter value + :param parameter10_name: Parameter name + :param parameter10_value: Parameter value + :param parameter11_name: Parameter name + :param parameter11_value: Parameter value + :param parameter12_name: Parameter name + :param parameter12_value: Parameter value + :param parameter13_name: Parameter name + :param parameter13_value: Parameter value + :param parameter14_name: Parameter name + :param parameter14_value: Parameter value + :param parameter15_name: Parameter name + :param parameter15_value: Parameter value + :param parameter16_name: Parameter name + :param parameter16_value: Parameter value + :param parameter17_name: Parameter name + :param parameter17_value: Parameter value + :param parameter18_name: Parameter name + :param parameter18_value: Parameter value + :param parameter19_name: Parameter name + :param parameter19_value: Parameter value + :param parameter20_name: Parameter name + :param parameter20_value: Parameter value + :param parameter21_name: Parameter name + :param parameter21_value: Parameter value + :param parameter22_name: Parameter name + :param parameter22_value: Parameter value + :param parameter23_name: Parameter name + :param parameter23_value: Parameter value + :param parameter24_name: Parameter name + :param parameter24_value: Parameter value + :param parameter25_name: Parameter name + :param parameter25_value: Parameter value + :param parameter26_name: Parameter name + :param parameter26_value: Parameter value + :param parameter27_name: Parameter name + :param parameter27_value: Parameter value + :param parameter28_name: Parameter name + :param parameter28_value: Parameter value + :param parameter29_name: Parameter name + :param parameter29_value: Parameter value + :param parameter30_name: Parameter name + :param parameter30_value: Parameter value + :param parameter31_name: Parameter name + :param parameter31_value: Parameter value + :param parameter32_name: Parameter name + :param parameter32_value: Parameter value + :param parameter33_name: Parameter name + :param parameter33_value: Parameter value + :param parameter34_name: Parameter name + :param parameter34_value: Parameter value + :param parameter35_name: Parameter name + :param parameter35_value: Parameter value + :param parameter36_name: Parameter name + :param parameter36_value: Parameter value + :param parameter37_name: Parameter name + :param parameter37_value: Parameter value + :param parameter38_name: Parameter name + :param parameter38_value: Parameter value + :param parameter39_name: Parameter name + :param parameter39_value: Parameter value + :param parameter40_name: Parameter name + :param parameter40_value: Parameter value + :param parameter41_name: Parameter name + :param parameter41_value: Parameter value + :param parameter42_name: Parameter name + :param parameter42_value: Parameter value + :param parameter43_name: Parameter name + :param parameter43_value: Parameter value + :param parameter44_name: Parameter name + :param parameter44_value: Parameter value + :param parameter45_name: Parameter name + :param parameter45_value: Parameter value + :param parameter46_name: Parameter name + :param parameter46_value: Parameter value + :param parameter47_name: Parameter name + :param parameter47_value: Parameter value + :param parameter48_name: Parameter name + :param parameter48_value: Parameter value + :param parameter49_name: Parameter name + :param parameter49_value: Parameter value + :param parameter50_name: Parameter name + :param parameter50_value: Parameter value + :param parameter51_name: Parameter name + :param parameter51_value: Parameter value + :param parameter52_name: Parameter name + :param parameter52_value: Parameter value + :param parameter53_name: Parameter name + :param parameter53_value: Parameter value + :param parameter54_name: Parameter name + :param parameter54_value: Parameter value + :param parameter55_name: Parameter name + :param parameter55_value: Parameter value + :param parameter56_name: Parameter name + :param parameter56_value: Parameter value + :param parameter57_name: Parameter name + :param parameter57_value: Parameter value + :param parameter58_name: Parameter name + :param parameter58_value: Parameter value + :param parameter59_name: Parameter name + :param parameter59_value: Parameter value + :param parameter60_name: Parameter name + :param parameter60_value: Parameter value + :param parameter61_name: Parameter name + :param parameter61_value: Parameter value + :param parameter62_name: Parameter name + :param parameter62_value: Parameter value + :param parameter63_name: Parameter name + :param parameter63_value: Parameter value + :param parameter64_name: Parameter name + :param parameter64_value: Parameter value + :param parameter65_name: Parameter name + :param parameter65_value: Parameter value + :param parameter66_name: Parameter name + :param parameter66_value: Parameter value + :param parameter67_name: Parameter name + :param parameter67_value: Parameter value + :param parameter68_name: Parameter name + :param parameter68_value: Parameter value + :param parameter69_name: Parameter name + :param parameter69_value: Parameter value + :param parameter70_name: Parameter name + :param parameter70_value: Parameter value + :param parameter71_name: Parameter name + :param parameter71_value: Parameter value + :param parameter72_name: Parameter name + :param parameter72_value: Parameter value + :param parameter73_name: Parameter name + :param parameter73_value: Parameter value + :param parameter74_name: Parameter name + :param parameter74_value: Parameter value + :param parameter75_name: Parameter name + :param parameter75_value: Parameter value + :param parameter76_name: Parameter name + :param parameter76_value: Parameter value + :param parameter77_name: Parameter name + :param parameter77_value: Parameter value + :param parameter78_name: Parameter name + :param parameter78_value: Parameter value + :param parameter79_name: Parameter name + :param parameter79_value: Parameter value + :param parameter80_name: Parameter name + :param parameter80_value: Parameter value + :param parameter81_name: Parameter name + :param parameter81_value: Parameter value + :param parameter82_name: Parameter name + :param parameter82_value: Parameter value + :param parameter83_name: Parameter name + :param parameter83_value: Parameter value + :param parameter84_name: Parameter name + :param parameter84_value: Parameter value + :param parameter85_name: Parameter name + :param parameter85_value: Parameter value + :param parameter86_name: Parameter name + :param parameter86_value: Parameter value + :param parameter87_name: Parameter name + :param parameter87_value: Parameter value + :param parameter88_name: Parameter name + :param parameter88_value: Parameter value + :param parameter89_name: Parameter name + :param parameter89_value: Parameter value + :param parameter90_name: Parameter name + :param parameter90_value: Parameter value + :param parameter91_name: Parameter name + :param parameter91_value: Parameter value + :param parameter92_name: Parameter name + :param parameter92_value: Parameter value + :param parameter93_name: Parameter name + :param parameter93_value: Parameter value + :param parameter94_name: Parameter name + :param parameter94_value: Parameter value + :param parameter95_name: Parameter name + :param parameter95_value: Parameter value + :param parameter96_name: Parameter name + :param parameter96_value: Parameter value + :param parameter97_name: Parameter name + :param parameter97_value: Parameter value + :param parameter98_name: Parameter name + :param parameter98_value: Parameter value + :param parameter99_name: Parameter name + :param parameter99_value: Parameter value + + :returns: The created SiprecInstance + """ + + data = values.of( + { + "Name": name, + "ConnectorName": connector_name, + "Track": track, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Parameter1.Name": parameter1_name, + "Parameter1.Value": parameter1_value, + "Parameter2.Name": parameter2_name, + "Parameter2.Value": parameter2_value, + "Parameter3.Name": parameter3_name, + "Parameter3.Value": parameter3_value, + "Parameter4.Name": parameter4_name, + "Parameter4.Value": parameter4_value, + "Parameter5.Name": parameter5_name, + "Parameter5.Value": parameter5_value, + "Parameter6.Name": parameter6_name, + "Parameter6.Value": parameter6_value, + "Parameter7.Name": parameter7_name, + "Parameter7.Value": parameter7_value, + "Parameter8.Name": parameter8_name, + "Parameter8.Value": parameter8_value, + "Parameter9.Name": parameter9_name, + "Parameter9.Value": parameter9_value, + "Parameter10.Name": parameter10_name, + "Parameter10.Value": parameter10_value, + "Parameter11.Name": parameter11_name, + "Parameter11.Value": parameter11_value, + "Parameter12.Name": parameter12_name, + "Parameter12.Value": parameter12_value, + "Parameter13.Name": parameter13_name, + "Parameter13.Value": parameter13_value, + "Parameter14.Name": parameter14_name, + "Parameter14.Value": parameter14_value, + "Parameter15.Name": parameter15_name, + "Parameter15.Value": parameter15_value, + "Parameter16.Name": parameter16_name, + "Parameter16.Value": parameter16_value, + "Parameter17.Name": parameter17_name, + "Parameter17.Value": parameter17_value, + "Parameter18.Name": parameter18_name, + "Parameter18.Value": parameter18_value, + "Parameter19.Name": parameter19_name, + "Parameter19.Value": parameter19_value, + "Parameter20.Name": parameter20_name, + "Parameter20.Value": parameter20_value, + "Parameter21.Name": parameter21_name, + "Parameter21.Value": parameter21_value, + "Parameter22.Name": parameter22_name, + "Parameter22.Value": parameter22_value, + "Parameter23.Name": parameter23_name, + "Parameter23.Value": parameter23_value, + "Parameter24.Name": parameter24_name, + "Parameter24.Value": parameter24_value, + "Parameter25.Name": parameter25_name, + "Parameter25.Value": parameter25_value, + "Parameter26.Name": parameter26_name, + "Parameter26.Value": parameter26_value, + "Parameter27.Name": parameter27_name, + "Parameter27.Value": parameter27_value, + "Parameter28.Name": parameter28_name, + "Parameter28.Value": parameter28_value, + "Parameter29.Name": parameter29_name, + "Parameter29.Value": parameter29_value, + "Parameter30.Name": parameter30_name, + "Parameter30.Value": parameter30_value, + "Parameter31.Name": parameter31_name, + "Parameter31.Value": parameter31_value, + "Parameter32.Name": parameter32_name, + "Parameter32.Value": parameter32_value, + "Parameter33.Name": parameter33_name, + "Parameter33.Value": parameter33_value, + "Parameter34.Name": parameter34_name, + "Parameter34.Value": parameter34_value, + "Parameter35.Name": parameter35_name, + "Parameter35.Value": parameter35_value, + "Parameter36.Name": parameter36_name, + "Parameter36.Value": parameter36_value, + "Parameter37.Name": parameter37_name, + "Parameter37.Value": parameter37_value, + "Parameter38.Name": parameter38_name, + "Parameter38.Value": parameter38_value, + "Parameter39.Name": parameter39_name, + "Parameter39.Value": parameter39_value, + "Parameter40.Name": parameter40_name, + "Parameter40.Value": parameter40_value, + "Parameter41.Name": parameter41_name, + "Parameter41.Value": parameter41_value, + "Parameter42.Name": parameter42_name, + "Parameter42.Value": parameter42_value, + "Parameter43.Name": parameter43_name, + "Parameter43.Value": parameter43_value, + "Parameter44.Name": parameter44_name, + "Parameter44.Value": parameter44_value, + "Parameter45.Name": parameter45_name, + "Parameter45.Value": parameter45_value, + "Parameter46.Name": parameter46_name, + "Parameter46.Value": parameter46_value, + "Parameter47.Name": parameter47_name, + "Parameter47.Value": parameter47_value, + "Parameter48.Name": parameter48_name, + "Parameter48.Value": parameter48_value, + "Parameter49.Name": parameter49_name, + "Parameter49.Value": parameter49_value, + "Parameter50.Name": parameter50_name, + "Parameter50.Value": parameter50_value, + "Parameter51.Name": parameter51_name, + "Parameter51.Value": parameter51_value, + "Parameter52.Name": parameter52_name, + "Parameter52.Value": parameter52_value, + "Parameter53.Name": parameter53_name, + "Parameter53.Value": parameter53_value, + "Parameter54.Name": parameter54_name, + "Parameter54.Value": parameter54_value, + "Parameter55.Name": parameter55_name, + "Parameter55.Value": parameter55_value, + "Parameter56.Name": parameter56_name, + "Parameter56.Value": parameter56_value, + "Parameter57.Name": parameter57_name, + "Parameter57.Value": parameter57_value, + "Parameter58.Name": parameter58_name, + "Parameter58.Value": parameter58_value, + "Parameter59.Name": parameter59_name, + "Parameter59.Value": parameter59_value, + "Parameter60.Name": parameter60_name, + "Parameter60.Value": parameter60_value, + "Parameter61.Name": parameter61_name, + "Parameter61.Value": parameter61_value, + "Parameter62.Name": parameter62_name, + "Parameter62.Value": parameter62_value, + "Parameter63.Name": parameter63_name, + "Parameter63.Value": parameter63_value, + "Parameter64.Name": parameter64_name, + "Parameter64.Value": parameter64_value, + "Parameter65.Name": parameter65_name, + "Parameter65.Value": parameter65_value, + "Parameter66.Name": parameter66_name, + "Parameter66.Value": parameter66_value, + "Parameter67.Name": parameter67_name, + "Parameter67.Value": parameter67_value, + "Parameter68.Name": parameter68_name, + "Parameter68.Value": parameter68_value, + "Parameter69.Name": parameter69_name, + "Parameter69.Value": parameter69_value, + "Parameter70.Name": parameter70_name, + "Parameter70.Value": parameter70_value, + "Parameter71.Name": parameter71_name, + "Parameter71.Value": parameter71_value, + "Parameter72.Name": parameter72_name, + "Parameter72.Value": parameter72_value, + "Parameter73.Name": parameter73_name, + "Parameter73.Value": parameter73_value, + "Parameter74.Name": parameter74_name, + "Parameter74.Value": parameter74_value, + "Parameter75.Name": parameter75_name, + "Parameter75.Value": parameter75_value, + "Parameter76.Name": parameter76_name, + "Parameter76.Value": parameter76_value, + "Parameter77.Name": parameter77_name, + "Parameter77.Value": parameter77_value, + "Parameter78.Name": parameter78_name, + "Parameter78.Value": parameter78_value, + "Parameter79.Name": parameter79_name, + "Parameter79.Value": parameter79_value, + "Parameter80.Name": parameter80_name, + "Parameter80.Value": parameter80_value, + "Parameter81.Name": parameter81_name, + "Parameter81.Value": parameter81_value, + "Parameter82.Name": parameter82_name, + "Parameter82.Value": parameter82_value, + "Parameter83.Name": parameter83_name, + "Parameter83.Value": parameter83_value, + "Parameter84.Name": parameter84_name, + "Parameter84.Value": parameter84_value, + "Parameter85.Name": parameter85_name, + "Parameter85.Value": parameter85_value, + "Parameter86.Name": parameter86_name, + "Parameter86.Value": parameter86_value, + "Parameter87.Name": parameter87_name, + "Parameter87.Value": parameter87_value, + "Parameter88.Name": parameter88_name, + "Parameter88.Value": parameter88_value, + "Parameter89.Name": parameter89_name, + "Parameter89.Value": parameter89_value, + "Parameter90.Name": parameter90_name, + "Parameter90.Value": parameter90_value, + "Parameter91.Name": parameter91_name, + "Parameter91.Value": parameter91_value, + "Parameter92.Name": parameter92_name, + "Parameter92.Value": parameter92_value, + "Parameter93.Name": parameter93_name, + "Parameter93.Value": parameter93_value, + "Parameter94.Name": parameter94_name, + "Parameter94.Value": parameter94_value, + "Parameter95.Name": parameter95_name, + "Parameter95.Value": parameter95_value, + "Parameter96.Name": parameter96_name, + "Parameter96.Value": parameter96_value, + "Parameter97.Name": parameter97_name, + "Parameter97.Value": parameter97_value, + "Parameter98.Name": parameter98_name, + "Parameter98.Value": parameter98_value, + "Parameter99.Name": parameter99_name, + "Parameter99.Value": parameter99_value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SiprecInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def get(self, sid: str) -> SiprecContext: + """ + Constructs a SiprecContext + + :param sid: The SID of the Siprec resource, or the `name` used when creating the resource + """ + return SiprecContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> SiprecContext: + """ + Constructs a SiprecContext + + :param sid: The SID of the Siprec resource, or the `name` used when creating the resource + """ + return SiprecContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.SiprecList>" diff --git a/twilio/rest/api/v2010/account/call/stream.py b/twilio/rest/api/v2010/account/call/stream.py new file mode 100644 index 0000000000..1a506e6684 --- /dev/null +++ b/twilio/rest/api/v2010/account/call/stream.py @@ -0,0 +1,1563 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class StreamInstance(InstanceResource): + + class Status(object): + IN_PROGRESS = "in-progress" + STOPPED = "stopped" + + class Track(object): + INBOUND_TRACK = "inbound_track" + OUTBOUND_TRACK = "outbound_track" + BOTH_TRACKS = "both_tracks" + + class UpdateStatus(object): + STOPPED = "stopped" + + """ + :ivar sid: The SID of the Stream resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Stream resource. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Stream resource is associated with. + :ivar name: The user-specified name of this Stream, if one was given when the Stream was created. This can be used to stop the Stream. + :ivar status: + :ivar date_updated: The date and time in GMT that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + call_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.name: Optional[str] = payload.get("name") + self.status: Optional["StreamInstance.Status"] = payload.get("status") + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } + self._context: Optional[StreamContext] = None + + @property + def _proxy(self) -> "StreamContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: StreamContext for this StreamInstance + """ + if self._context is None: + self._context = StreamContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return self._context + + def update(self, status: "StreamInstance.UpdateStatus") -> "StreamInstance": + """ + Update the StreamInstance + + :param status: + + :returns: The updated StreamInstance + """ + return self._proxy.update( + status=status, + ) + + async def update_async( + self, status: "StreamInstance.UpdateStatus" + ) -> "StreamInstance": + """ + Asynchronous coroutine to update the StreamInstance + + :param status: + + :returns: The updated StreamInstance + """ + return await self._proxy.update_async( + status=status, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.StreamInstance {}>".format(context) + + +class StreamContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): + """ + Initialize the StreamContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Stream resource. + :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Stream resource is associated with. + :param sid: The SID or the `name` of the Stream resource to be stopped + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/Streams/{sid}.json".format( + **self._solution + ) + ) + + def update(self, status: "StreamInstance.UpdateStatus") -> StreamInstance: + """ + Update the StreamInstance + + :param status: + + :returns: The updated StreamInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, status: "StreamInstance.UpdateStatus" + ) -> StreamInstance: + """ + Asynchronous coroutine to update the StreamInstance + + :param status: + + :returns: The updated StreamInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.StreamContext {}>".format(context) + + +class StreamList(ListResource): + + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the StreamList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Stream resource. + :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Stream resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = "/Accounts/{account_sid}/Calls/{call_sid}/Streams.json".format( + **self._solution + ) + + def create( + self, + url: str, + name: Union[str, object] = values.unset, + track: Union["StreamInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> StreamInstance: + """ + Create the StreamInstance + + :param url: Relative or absolute URL where WebSocket connection will be established. + :param name: The user-specified name of this Stream, if one was given when the Stream was created. This can be used to stop the Stream. + :param track: + :param status_callback: Absolute URL to which Twilio sends status callback HTTP requests. + :param status_callback_method: The HTTP method Twilio uses when sending `status_callback` requests. Possible values are `GET` and `POST`. Default is `POST`. + :param parameter1_name: Parameter name + :param parameter1_value: Parameter value + :param parameter2_name: Parameter name + :param parameter2_value: Parameter value + :param parameter3_name: Parameter name + :param parameter3_value: Parameter value + :param parameter4_name: Parameter name + :param parameter4_value: Parameter value + :param parameter5_name: Parameter name + :param parameter5_value: Parameter value + :param parameter6_name: Parameter name + :param parameter6_value: Parameter value + :param parameter7_name: Parameter name + :param parameter7_value: Parameter value + :param parameter8_name: Parameter name + :param parameter8_value: Parameter value + :param parameter9_name: Parameter name + :param parameter9_value: Parameter value + :param parameter10_name: Parameter name + :param parameter10_value: Parameter value + :param parameter11_name: Parameter name + :param parameter11_value: Parameter value + :param parameter12_name: Parameter name + :param parameter12_value: Parameter value + :param parameter13_name: Parameter name + :param parameter13_value: Parameter value + :param parameter14_name: Parameter name + :param parameter14_value: Parameter value + :param parameter15_name: Parameter name + :param parameter15_value: Parameter value + :param parameter16_name: Parameter name + :param parameter16_value: Parameter value + :param parameter17_name: Parameter name + :param parameter17_value: Parameter value + :param parameter18_name: Parameter name + :param parameter18_value: Parameter value + :param parameter19_name: Parameter name + :param parameter19_value: Parameter value + :param parameter20_name: Parameter name + :param parameter20_value: Parameter value + :param parameter21_name: Parameter name + :param parameter21_value: Parameter value + :param parameter22_name: Parameter name + :param parameter22_value: Parameter value + :param parameter23_name: Parameter name + :param parameter23_value: Parameter value + :param parameter24_name: Parameter name + :param parameter24_value: Parameter value + :param parameter25_name: Parameter name + :param parameter25_value: Parameter value + :param parameter26_name: Parameter name + :param parameter26_value: Parameter value + :param parameter27_name: Parameter name + :param parameter27_value: Parameter value + :param parameter28_name: Parameter name + :param parameter28_value: Parameter value + :param parameter29_name: Parameter name + :param parameter29_value: Parameter value + :param parameter30_name: Parameter name + :param parameter30_value: Parameter value + :param parameter31_name: Parameter name + :param parameter31_value: Parameter value + :param parameter32_name: Parameter name + :param parameter32_value: Parameter value + :param parameter33_name: Parameter name + :param parameter33_value: Parameter value + :param parameter34_name: Parameter name + :param parameter34_value: Parameter value + :param parameter35_name: Parameter name + :param parameter35_value: Parameter value + :param parameter36_name: Parameter name + :param parameter36_value: Parameter value + :param parameter37_name: Parameter name + :param parameter37_value: Parameter value + :param parameter38_name: Parameter name + :param parameter38_value: Parameter value + :param parameter39_name: Parameter name + :param parameter39_value: Parameter value + :param parameter40_name: Parameter name + :param parameter40_value: Parameter value + :param parameter41_name: Parameter name + :param parameter41_value: Parameter value + :param parameter42_name: Parameter name + :param parameter42_value: Parameter value + :param parameter43_name: Parameter name + :param parameter43_value: Parameter value + :param parameter44_name: Parameter name + :param parameter44_value: Parameter value + :param parameter45_name: Parameter name + :param parameter45_value: Parameter value + :param parameter46_name: Parameter name + :param parameter46_value: Parameter value + :param parameter47_name: Parameter name + :param parameter47_value: Parameter value + :param parameter48_name: Parameter name + :param parameter48_value: Parameter value + :param parameter49_name: Parameter name + :param parameter49_value: Parameter value + :param parameter50_name: Parameter name + :param parameter50_value: Parameter value + :param parameter51_name: Parameter name + :param parameter51_value: Parameter value + :param parameter52_name: Parameter name + :param parameter52_value: Parameter value + :param parameter53_name: Parameter name + :param parameter53_value: Parameter value + :param parameter54_name: Parameter name + :param parameter54_value: Parameter value + :param parameter55_name: Parameter name + :param parameter55_value: Parameter value + :param parameter56_name: Parameter name + :param parameter56_value: Parameter value + :param parameter57_name: Parameter name + :param parameter57_value: Parameter value + :param parameter58_name: Parameter name + :param parameter58_value: Parameter value + :param parameter59_name: Parameter name + :param parameter59_value: Parameter value + :param parameter60_name: Parameter name + :param parameter60_value: Parameter value + :param parameter61_name: Parameter name + :param parameter61_value: Parameter value + :param parameter62_name: Parameter name + :param parameter62_value: Parameter value + :param parameter63_name: Parameter name + :param parameter63_value: Parameter value + :param parameter64_name: Parameter name + :param parameter64_value: Parameter value + :param parameter65_name: Parameter name + :param parameter65_value: Parameter value + :param parameter66_name: Parameter name + :param parameter66_value: Parameter value + :param parameter67_name: Parameter name + :param parameter67_value: Parameter value + :param parameter68_name: Parameter name + :param parameter68_value: Parameter value + :param parameter69_name: Parameter name + :param parameter69_value: Parameter value + :param parameter70_name: Parameter name + :param parameter70_value: Parameter value + :param parameter71_name: Parameter name + :param parameter71_value: Parameter value + :param parameter72_name: Parameter name + :param parameter72_value: Parameter value + :param parameter73_name: Parameter name + :param parameter73_value: Parameter value + :param parameter74_name: Parameter name + :param parameter74_value: Parameter value + :param parameter75_name: Parameter name + :param parameter75_value: Parameter value + :param parameter76_name: Parameter name + :param parameter76_value: Parameter value + :param parameter77_name: Parameter name + :param parameter77_value: Parameter value + :param parameter78_name: Parameter name + :param parameter78_value: Parameter value + :param parameter79_name: Parameter name + :param parameter79_value: Parameter value + :param parameter80_name: Parameter name + :param parameter80_value: Parameter value + :param parameter81_name: Parameter name + :param parameter81_value: Parameter value + :param parameter82_name: Parameter name + :param parameter82_value: Parameter value + :param parameter83_name: Parameter name + :param parameter83_value: Parameter value + :param parameter84_name: Parameter name + :param parameter84_value: Parameter value + :param parameter85_name: Parameter name + :param parameter85_value: Parameter value + :param parameter86_name: Parameter name + :param parameter86_value: Parameter value + :param parameter87_name: Parameter name + :param parameter87_value: Parameter value + :param parameter88_name: Parameter name + :param parameter88_value: Parameter value + :param parameter89_name: Parameter name + :param parameter89_value: Parameter value + :param parameter90_name: Parameter name + :param parameter90_value: Parameter value + :param parameter91_name: Parameter name + :param parameter91_value: Parameter value + :param parameter92_name: Parameter name + :param parameter92_value: Parameter value + :param parameter93_name: Parameter name + :param parameter93_value: Parameter value + :param parameter94_name: Parameter name + :param parameter94_value: Parameter value + :param parameter95_name: Parameter name + :param parameter95_value: Parameter value + :param parameter96_name: Parameter name + :param parameter96_value: Parameter value + :param parameter97_name: Parameter name + :param parameter97_value: Parameter value + :param parameter98_name: Parameter name + :param parameter98_value: Parameter value + :param parameter99_name: Parameter name + :param parameter99_value: Parameter value + + :returns: The created StreamInstance + """ + + data = values.of( + { + "Url": url, + "Name": name, + "Track": track, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Parameter1.Name": parameter1_name, + "Parameter1.Value": parameter1_value, + "Parameter2.Name": parameter2_name, + "Parameter2.Value": parameter2_value, + "Parameter3.Name": parameter3_name, + "Parameter3.Value": parameter3_value, + "Parameter4.Name": parameter4_name, + "Parameter4.Value": parameter4_value, + "Parameter5.Name": parameter5_name, + "Parameter5.Value": parameter5_value, + "Parameter6.Name": parameter6_name, + "Parameter6.Value": parameter6_value, + "Parameter7.Name": parameter7_name, + "Parameter7.Value": parameter7_value, + "Parameter8.Name": parameter8_name, + "Parameter8.Value": parameter8_value, + "Parameter9.Name": parameter9_name, + "Parameter9.Value": parameter9_value, + "Parameter10.Name": parameter10_name, + "Parameter10.Value": parameter10_value, + "Parameter11.Name": parameter11_name, + "Parameter11.Value": parameter11_value, + "Parameter12.Name": parameter12_name, + "Parameter12.Value": parameter12_value, + "Parameter13.Name": parameter13_name, + "Parameter13.Value": parameter13_value, + "Parameter14.Name": parameter14_name, + "Parameter14.Value": parameter14_value, + "Parameter15.Name": parameter15_name, + "Parameter15.Value": parameter15_value, + "Parameter16.Name": parameter16_name, + "Parameter16.Value": parameter16_value, + "Parameter17.Name": parameter17_name, + "Parameter17.Value": parameter17_value, + "Parameter18.Name": parameter18_name, + "Parameter18.Value": parameter18_value, + "Parameter19.Name": parameter19_name, + "Parameter19.Value": parameter19_value, + "Parameter20.Name": parameter20_name, + "Parameter20.Value": parameter20_value, + "Parameter21.Name": parameter21_name, + "Parameter21.Value": parameter21_value, + "Parameter22.Name": parameter22_name, + "Parameter22.Value": parameter22_value, + "Parameter23.Name": parameter23_name, + "Parameter23.Value": parameter23_value, + "Parameter24.Name": parameter24_name, + "Parameter24.Value": parameter24_value, + "Parameter25.Name": parameter25_name, + "Parameter25.Value": parameter25_value, + "Parameter26.Name": parameter26_name, + "Parameter26.Value": parameter26_value, + "Parameter27.Name": parameter27_name, + "Parameter27.Value": parameter27_value, + "Parameter28.Name": parameter28_name, + "Parameter28.Value": parameter28_value, + "Parameter29.Name": parameter29_name, + "Parameter29.Value": parameter29_value, + "Parameter30.Name": parameter30_name, + "Parameter30.Value": parameter30_value, + "Parameter31.Name": parameter31_name, + "Parameter31.Value": parameter31_value, + "Parameter32.Name": parameter32_name, + "Parameter32.Value": parameter32_value, + "Parameter33.Name": parameter33_name, + "Parameter33.Value": parameter33_value, + "Parameter34.Name": parameter34_name, + "Parameter34.Value": parameter34_value, + "Parameter35.Name": parameter35_name, + "Parameter35.Value": parameter35_value, + "Parameter36.Name": parameter36_name, + "Parameter36.Value": parameter36_value, + "Parameter37.Name": parameter37_name, + "Parameter37.Value": parameter37_value, + "Parameter38.Name": parameter38_name, + "Parameter38.Value": parameter38_value, + "Parameter39.Name": parameter39_name, + "Parameter39.Value": parameter39_value, + "Parameter40.Name": parameter40_name, + "Parameter40.Value": parameter40_value, + "Parameter41.Name": parameter41_name, + "Parameter41.Value": parameter41_value, + "Parameter42.Name": parameter42_name, + "Parameter42.Value": parameter42_value, + "Parameter43.Name": parameter43_name, + "Parameter43.Value": parameter43_value, + "Parameter44.Name": parameter44_name, + "Parameter44.Value": parameter44_value, + "Parameter45.Name": parameter45_name, + "Parameter45.Value": parameter45_value, + "Parameter46.Name": parameter46_name, + "Parameter46.Value": parameter46_value, + "Parameter47.Name": parameter47_name, + "Parameter47.Value": parameter47_value, + "Parameter48.Name": parameter48_name, + "Parameter48.Value": parameter48_value, + "Parameter49.Name": parameter49_name, + "Parameter49.Value": parameter49_value, + "Parameter50.Name": parameter50_name, + "Parameter50.Value": parameter50_value, + "Parameter51.Name": parameter51_name, + "Parameter51.Value": parameter51_value, + "Parameter52.Name": parameter52_name, + "Parameter52.Value": parameter52_value, + "Parameter53.Name": parameter53_name, + "Parameter53.Value": parameter53_value, + "Parameter54.Name": parameter54_name, + "Parameter54.Value": parameter54_value, + "Parameter55.Name": parameter55_name, + "Parameter55.Value": parameter55_value, + "Parameter56.Name": parameter56_name, + "Parameter56.Value": parameter56_value, + "Parameter57.Name": parameter57_name, + "Parameter57.Value": parameter57_value, + "Parameter58.Name": parameter58_name, + "Parameter58.Value": parameter58_value, + "Parameter59.Name": parameter59_name, + "Parameter59.Value": parameter59_value, + "Parameter60.Name": parameter60_name, + "Parameter60.Value": parameter60_value, + "Parameter61.Name": parameter61_name, + "Parameter61.Value": parameter61_value, + "Parameter62.Name": parameter62_name, + "Parameter62.Value": parameter62_value, + "Parameter63.Name": parameter63_name, + "Parameter63.Value": parameter63_value, + "Parameter64.Name": parameter64_name, + "Parameter64.Value": parameter64_value, + "Parameter65.Name": parameter65_name, + "Parameter65.Value": parameter65_value, + "Parameter66.Name": parameter66_name, + "Parameter66.Value": parameter66_value, + "Parameter67.Name": parameter67_name, + "Parameter67.Value": parameter67_value, + "Parameter68.Name": parameter68_name, + "Parameter68.Value": parameter68_value, + "Parameter69.Name": parameter69_name, + "Parameter69.Value": parameter69_value, + "Parameter70.Name": parameter70_name, + "Parameter70.Value": parameter70_value, + "Parameter71.Name": parameter71_name, + "Parameter71.Value": parameter71_value, + "Parameter72.Name": parameter72_name, + "Parameter72.Value": parameter72_value, + "Parameter73.Name": parameter73_name, + "Parameter73.Value": parameter73_value, + "Parameter74.Name": parameter74_name, + "Parameter74.Value": parameter74_value, + "Parameter75.Name": parameter75_name, + "Parameter75.Value": parameter75_value, + "Parameter76.Name": parameter76_name, + "Parameter76.Value": parameter76_value, + "Parameter77.Name": parameter77_name, + "Parameter77.Value": parameter77_value, + "Parameter78.Name": parameter78_name, + "Parameter78.Value": parameter78_value, + "Parameter79.Name": parameter79_name, + "Parameter79.Value": parameter79_value, + "Parameter80.Name": parameter80_name, + "Parameter80.Value": parameter80_value, + "Parameter81.Name": parameter81_name, + "Parameter81.Value": parameter81_value, + "Parameter82.Name": parameter82_name, + "Parameter82.Value": parameter82_value, + "Parameter83.Name": parameter83_name, + "Parameter83.Value": parameter83_value, + "Parameter84.Name": parameter84_name, + "Parameter84.Value": parameter84_value, + "Parameter85.Name": parameter85_name, + "Parameter85.Value": parameter85_value, + "Parameter86.Name": parameter86_name, + "Parameter86.Value": parameter86_value, + "Parameter87.Name": parameter87_name, + "Parameter87.Value": parameter87_value, + "Parameter88.Name": parameter88_name, + "Parameter88.Value": parameter88_value, + "Parameter89.Name": parameter89_name, + "Parameter89.Value": parameter89_value, + "Parameter90.Name": parameter90_name, + "Parameter90.Value": parameter90_value, + "Parameter91.Name": parameter91_name, + "Parameter91.Value": parameter91_value, + "Parameter92.Name": parameter92_name, + "Parameter92.Value": parameter92_value, + "Parameter93.Name": parameter93_name, + "Parameter93.Value": parameter93_value, + "Parameter94.Name": parameter94_name, + "Parameter94.Value": parameter94_value, + "Parameter95.Name": parameter95_name, + "Parameter95.Value": parameter95_value, + "Parameter96.Name": parameter96_name, + "Parameter96.Value": parameter96_value, + "Parameter97.Name": parameter97_name, + "Parameter97.Value": parameter97_value, + "Parameter98.Name": parameter98_name, + "Parameter98.Value": parameter98_value, + "Parameter99.Name": parameter99_name, + "Parameter99.Value": parameter99_value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_async( + self, + url: str, + name: Union[str, object] = values.unset, + track: Union["StreamInstance.Track", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + parameter1_name: Union[str, object] = values.unset, + parameter1_value: Union[str, object] = values.unset, + parameter2_name: Union[str, object] = values.unset, + parameter2_value: Union[str, object] = values.unset, + parameter3_name: Union[str, object] = values.unset, + parameter3_value: Union[str, object] = values.unset, + parameter4_name: Union[str, object] = values.unset, + parameter4_value: Union[str, object] = values.unset, + parameter5_name: Union[str, object] = values.unset, + parameter5_value: Union[str, object] = values.unset, + parameter6_name: Union[str, object] = values.unset, + parameter6_value: Union[str, object] = values.unset, + parameter7_name: Union[str, object] = values.unset, + parameter7_value: Union[str, object] = values.unset, + parameter8_name: Union[str, object] = values.unset, + parameter8_value: Union[str, object] = values.unset, + parameter9_name: Union[str, object] = values.unset, + parameter9_value: Union[str, object] = values.unset, + parameter10_name: Union[str, object] = values.unset, + parameter10_value: Union[str, object] = values.unset, + parameter11_name: Union[str, object] = values.unset, + parameter11_value: Union[str, object] = values.unset, + parameter12_name: Union[str, object] = values.unset, + parameter12_value: Union[str, object] = values.unset, + parameter13_name: Union[str, object] = values.unset, + parameter13_value: Union[str, object] = values.unset, + parameter14_name: Union[str, object] = values.unset, + parameter14_value: Union[str, object] = values.unset, + parameter15_name: Union[str, object] = values.unset, + parameter15_value: Union[str, object] = values.unset, + parameter16_name: Union[str, object] = values.unset, + parameter16_value: Union[str, object] = values.unset, + parameter17_name: Union[str, object] = values.unset, + parameter17_value: Union[str, object] = values.unset, + parameter18_name: Union[str, object] = values.unset, + parameter18_value: Union[str, object] = values.unset, + parameter19_name: Union[str, object] = values.unset, + parameter19_value: Union[str, object] = values.unset, + parameter20_name: Union[str, object] = values.unset, + parameter20_value: Union[str, object] = values.unset, + parameter21_name: Union[str, object] = values.unset, + parameter21_value: Union[str, object] = values.unset, + parameter22_name: Union[str, object] = values.unset, + parameter22_value: Union[str, object] = values.unset, + parameter23_name: Union[str, object] = values.unset, + parameter23_value: Union[str, object] = values.unset, + parameter24_name: Union[str, object] = values.unset, + parameter24_value: Union[str, object] = values.unset, + parameter25_name: Union[str, object] = values.unset, + parameter25_value: Union[str, object] = values.unset, + parameter26_name: Union[str, object] = values.unset, + parameter26_value: Union[str, object] = values.unset, + parameter27_name: Union[str, object] = values.unset, + parameter27_value: Union[str, object] = values.unset, + parameter28_name: Union[str, object] = values.unset, + parameter28_value: Union[str, object] = values.unset, + parameter29_name: Union[str, object] = values.unset, + parameter29_value: Union[str, object] = values.unset, + parameter30_name: Union[str, object] = values.unset, + parameter30_value: Union[str, object] = values.unset, + parameter31_name: Union[str, object] = values.unset, + parameter31_value: Union[str, object] = values.unset, + parameter32_name: Union[str, object] = values.unset, + parameter32_value: Union[str, object] = values.unset, + parameter33_name: Union[str, object] = values.unset, + parameter33_value: Union[str, object] = values.unset, + parameter34_name: Union[str, object] = values.unset, + parameter34_value: Union[str, object] = values.unset, + parameter35_name: Union[str, object] = values.unset, + parameter35_value: Union[str, object] = values.unset, + parameter36_name: Union[str, object] = values.unset, + parameter36_value: Union[str, object] = values.unset, + parameter37_name: Union[str, object] = values.unset, + parameter37_value: Union[str, object] = values.unset, + parameter38_name: Union[str, object] = values.unset, + parameter38_value: Union[str, object] = values.unset, + parameter39_name: Union[str, object] = values.unset, + parameter39_value: Union[str, object] = values.unset, + parameter40_name: Union[str, object] = values.unset, + parameter40_value: Union[str, object] = values.unset, + parameter41_name: Union[str, object] = values.unset, + parameter41_value: Union[str, object] = values.unset, + parameter42_name: Union[str, object] = values.unset, + parameter42_value: Union[str, object] = values.unset, + parameter43_name: Union[str, object] = values.unset, + parameter43_value: Union[str, object] = values.unset, + parameter44_name: Union[str, object] = values.unset, + parameter44_value: Union[str, object] = values.unset, + parameter45_name: Union[str, object] = values.unset, + parameter45_value: Union[str, object] = values.unset, + parameter46_name: Union[str, object] = values.unset, + parameter46_value: Union[str, object] = values.unset, + parameter47_name: Union[str, object] = values.unset, + parameter47_value: Union[str, object] = values.unset, + parameter48_name: Union[str, object] = values.unset, + parameter48_value: Union[str, object] = values.unset, + parameter49_name: Union[str, object] = values.unset, + parameter49_value: Union[str, object] = values.unset, + parameter50_name: Union[str, object] = values.unset, + parameter50_value: Union[str, object] = values.unset, + parameter51_name: Union[str, object] = values.unset, + parameter51_value: Union[str, object] = values.unset, + parameter52_name: Union[str, object] = values.unset, + parameter52_value: Union[str, object] = values.unset, + parameter53_name: Union[str, object] = values.unset, + parameter53_value: Union[str, object] = values.unset, + parameter54_name: Union[str, object] = values.unset, + parameter54_value: Union[str, object] = values.unset, + parameter55_name: Union[str, object] = values.unset, + parameter55_value: Union[str, object] = values.unset, + parameter56_name: Union[str, object] = values.unset, + parameter56_value: Union[str, object] = values.unset, + parameter57_name: Union[str, object] = values.unset, + parameter57_value: Union[str, object] = values.unset, + parameter58_name: Union[str, object] = values.unset, + parameter58_value: Union[str, object] = values.unset, + parameter59_name: Union[str, object] = values.unset, + parameter59_value: Union[str, object] = values.unset, + parameter60_name: Union[str, object] = values.unset, + parameter60_value: Union[str, object] = values.unset, + parameter61_name: Union[str, object] = values.unset, + parameter61_value: Union[str, object] = values.unset, + parameter62_name: Union[str, object] = values.unset, + parameter62_value: Union[str, object] = values.unset, + parameter63_name: Union[str, object] = values.unset, + parameter63_value: Union[str, object] = values.unset, + parameter64_name: Union[str, object] = values.unset, + parameter64_value: Union[str, object] = values.unset, + parameter65_name: Union[str, object] = values.unset, + parameter65_value: Union[str, object] = values.unset, + parameter66_name: Union[str, object] = values.unset, + parameter66_value: Union[str, object] = values.unset, + parameter67_name: Union[str, object] = values.unset, + parameter67_value: Union[str, object] = values.unset, + parameter68_name: Union[str, object] = values.unset, + parameter68_value: Union[str, object] = values.unset, + parameter69_name: Union[str, object] = values.unset, + parameter69_value: Union[str, object] = values.unset, + parameter70_name: Union[str, object] = values.unset, + parameter70_value: Union[str, object] = values.unset, + parameter71_name: Union[str, object] = values.unset, + parameter71_value: Union[str, object] = values.unset, + parameter72_name: Union[str, object] = values.unset, + parameter72_value: Union[str, object] = values.unset, + parameter73_name: Union[str, object] = values.unset, + parameter73_value: Union[str, object] = values.unset, + parameter74_name: Union[str, object] = values.unset, + parameter74_value: Union[str, object] = values.unset, + parameter75_name: Union[str, object] = values.unset, + parameter75_value: Union[str, object] = values.unset, + parameter76_name: Union[str, object] = values.unset, + parameter76_value: Union[str, object] = values.unset, + parameter77_name: Union[str, object] = values.unset, + parameter77_value: Union[str, object] = values.unset, + parameter78_name: Union[str, object] = values.unset, + parameter78_value: Union[str, object] = values.unset, + parameter79_name: Union[str, object] = values.unset, + parameter79_value: Union[str, object] = values.unset, + parameter80_name: Union[str, object] = values.unset, + parameter80_value: Union[str, object] = values.unset, + parameter81_name: Union[str, object] = values.unset, + parameter81_value: Union[str, object] = values.unset, + parameter82_name: Union[str, object] = values.unset, + parameter82_value: Union[str, object] = values.unset, + parameter83_name: Union[str, object] = values.unset, + parameter83_value: Union[str, object] = values.unset, + parameter84_name: Union[str, object] = values.unset, + parameter84_value: Union[str, object] = values.unset, + parameter85_name: Union[str, object] = values.unset, + parameter85_value: Union[str, object] = values.unset, + parameter86_name: Union[str, object] = values.unset, + parameter86_value: Union[str, object] = values.unset, + parameter87_name: Union[str, object] = values.unset, + parameter87_value: Union[str, object] = values.unset, + parameter88_name: Union[str, object] = values.unset, + parameter88_value: Union[str, object] = values.unset, + parameter89_name: Union[str, object] = values.unset, + parameter89_value: Union[str, object] = values.unset, + parameter90_name: Union[str, object] = values.unset, + parameter90_value: Union[str, object] = values.unset, + parameter91_name: Union[str, object] = values.unset, + parameter91_value: Union[str, object] = values.unset, + parameter92_name: Union[str, object] = values.unset, + parameter92_value: Union[str, object] = values.unset, + parameter93_name: Union[str, object] = values.unset, + parameter93_value: Union[str, object] = values.unset, + parameter94_name: Union[str, object] = values.unset, + parameter94_value: Union[str, object] = values.unset, + parameter95_name: Union[str, object] = values.unset, + parameter95_value: Union[str, object] = values.unset, + parameter96_name: Union[str, object] = values.unset, + parameter96_value: Union[str, object] = values.unset, + parameter97_name: Union[str, object] = values.unset, + parameter97_value: Union[str, object] = values.unset, + parameter98_name: Union[str, object] = values.unset, + parameter98_value: Union[str, object] = values.unset, + parameter99_name: Union[str, object] = values.unset, + parameter99_value: Union[str, object] = values.unset, + ) -> StreamInstance: + """ + Asynchronously create the StreamInstance + + :param url: Relative or absolute URL where WebSocket connection will be established. + :param name: The user-specified name of this Stream, if one was given when the Stream was created. This can be used to stop the Stream. + :param track: + :param status_callback: Absolute URL to which Twilio sends status callback HTTP requests. + :param status_callback_method: The HTTP method Twilio uses when sending `status_callback` requests. Possible values are `GET` and `POST`. Default is `POST`. + :param parameter1_name: Parameter name + :param parameter1_value: Parameter value + :param parameter2_name: Parameter name + :param parameter2_value: Parameter value + :param parameter3_name: Parameter name + :param parameter3_value: Parameter value + :param parameter4_name: Parameter name + :param parameter4_value: Parameter value + :param parameter5_name: Parameter name + :param parameter5_value: Parameter value + :param parameter6_name: Parameter name + :param parameter6_value: Parameter value + :param parameter7_name: Parameter name + :param parameter7_value: Parameter value + :param parameter8_name: Parameter name + :param parameter8_value: Parameter value + :param parameter9_name: Parameter name + :param parameter9_value: Parameter value + :param parameter10_name: Parameter name + :param parameter10_value: Parameter value + :param parameter11_name: Parameter name + :param parameter11_value: Parameter value + :param parameter12_name: Parameter name + :param parameter12_value: Parameter value + :param parameter13_name: Parameter name + :param parameter13_value: Parameter value + :param parameter14_name: Parameter name + :param parameter14_value: Parameter value + :param parameter15_name: Parameter name + :param parameter15_value: Parameter value + :param parameter16_name: Parameter name + :param parameter16_value: Parameter value + :param parameter17_name: Parameter name + :param parameter17_value: Parameter value + :param parameter18_name: Parameter name + :param parameter18_value: Parameter value + :param parameter19_name: Parameter name + :param parameter19_value: Parameter value + :param parameter20_name: Parameter name + :param parameter20_value: Parameter value + :param parameter21_name: Parameter name + :param parameter21_value: Parameter value + :param parameter22_name: Parameter name + :param parameter22_value: Parameter value + :param parameter23_name: Parameter name + :param parameter23_value: Parameter value + :param parameter24_name: Parameter name + :param parameter24_value: Parameter value + :param parameter25_name: Parameter name + :param parameter25_value: Parameter value + :param parameter26_name: Parameter name + :param parameter26_value: Parameter value + :param parameter27_name: Parameter name + :param parameter27_value: Parameter value + :param parameter28_name: Parameter name + :param parameter28_value: Parameter value + :param parameter29_name: Parameter name + :param parameter29_value: Parameter value + :param parameter30_name: Parameter name + :param parameter30_value: Parameter value + :param parameter31_name: Parameter name + :param parameter31_value: Parameter value + :param parameter32_name: Parameter name + :param parameter32_value: Parameter value + :param parameter33_name: Parameter name + :param parameter33_value: Parameter value + :param parameter34_name: Parameter name + :param parameter34_value: Parameter value + :param parameter35_name: Parameter name + :param parameter35_value: Parameter value + :param parameter36_name: Parameter name + :param parameter36_value: Parameter value + :param parameter37_name: Parameter name + :param parameter37_value: Parameter value + :param parameter38_name: Parameter name + :param parameter38_value: Parameter value + :param parameter39_name: Parameter name + :param parameter39_value: Parameter value + :param parameter40_name: Parameter name + :param parameter40_value: Parameter value + :param parameter41_name: Parameter name + :param parameter41_value: Parameter value + :param parameter42_name: Parameter name + :param parameter42_value: Parameter value + :param parameter43_name: Parameter name + :param parameter43_value: Parameter value + :param parameter44_name: Parameter name + :param parameter44_value: Parameter value + :param parameter45_name: Parameter name + :param parameter45_value: Parameter value + :param parameter46_name: Parameter name + :param parameter46_value: Parameter value + :param parameter47_name: Parameter name + :param parameter47_value: Parameter value + :param parameter48_name: Parameter name + :param parameter48_value: Parameter value + :param parameter49_name: Parameter name + :param parameter49_value: Parameter value + :param parameter50_name: Parameter name + :param parameter50_value: Parameter value + :param parameter51_name: Parameter name + :param parameter51_value: Parameter value + :param parameter52_name: Parameter name + :param parameter52_value: Parameter value + :param parameter53_name: Parameter name + :param parameter53_value: Parameter value + :param parameter54_name: Parameter name + :param parameter54_value: Parameter value + :param parameter55_name: Parameter name + :param parameter55_value: Parameter value + :param parameter56_name: Parameter name + :param parameter56_value: Parameter value + :param parameter57_name: Parameter name + :param parameter57_value: Parameter value + :param parameter58_name: Parameter name + :param parameter58_value: Parameter value + :param parameter59_name: Parameter name + :param parameter59_value: Parameter value + :param parameter60_name: Parameter name + :param parameter60_value: Parameter value + :param parameter61_name: Parameter name + :param parameter61_value: Parameter value + :param parameter62_name: Parameter name + :param parameter62_value: Parameter value + :param parameter63_name: Parameter name + :param parameter63_value: Parameter value + :param parameter64_name: Parameter name + :param parameter64_value: Parameter value + :param parameter65_name: Parameter name + :param parameter65_value: Parameter value + :param parameter66_name: Parameter name + :param parameter66_value: Parameter value + :param parameter67_name: Parameter name + :param parameter67_value: Parameter value + :param parameter68_name: Parameter name + :param parameter68_value: Parameter value + :param parameter69_name: Parameter name + :param parameter69_value: Parameter value + :param parameter70_name: Parameter name + :param parameter70_value: Parameter value + :param parameter71_name: Parameter name + :param parameter71_value: Parameter value + :param parameter72_name: Parameter name + :param parameter72_value: Parameter value + :param parameter73_name: Parameter name + :param parameter73_value: Parameter value + :param parameter74_name: Parameter name + :param parameter74_value: Parameter value + :param parameter75_name: Parameter name + :param parameter75_value: Parameter value + :param parameter76_name: Parameter name + :param parameter76_value: Parameter value + :param parameter77_name: Parameter name + :param parameter77_value: Parameter value + :param parameter78_name: Parameter name + :param parameter78_value: Parameter value + :param parameter79_name: Parameter name + :param parameter79_value: Parameter value + :param parameter80_name: Parameter name + :param parameter80_value: Parameter value + :param parameter81_name: Parameter name + :param parameter81_value: Parameter value + :param parameter82_name: Parameter name + :param parameter82_value: Parameter value + :param parameter83_name: Parameter name + :param parameter83_value: Parameter value + :param parameter84_name: Parameter name + :param parameter84_value: Parameter value + :param parameter85_name: Parameter name + :param parameter85_value: Parameter value + :param parameter86_name: Parameter name + :param parameter86_value: Parameter value + :param parameter87_name: Parameter name + :param parameter87_value: Parameter value + :param parameter88_name: Parameter name + :param parameter88_value: Parameter value + :param parameter89_name: Parameter name + :param parameter89_value: Parameter value + :param parameter90_name: Parameter name + :param parameter90_value: Parameter value + :param parameter91_name: Parameter name + :param parameter91_value: Parameter value + :param parameter92_name: Parameter name + :param parameter92_value: Parameter value + :param parameter93_name: Parameter name + :param parameter93_value: Parameter value + :param parameter94_name: Parameter name + :param parameter94_value: Parameter value + :param parameter95_name: Parameter name + :param parameter95_value: Parameter value + :param parameter96_name: Parameter name + :param parameter96_value: Parameter value + :param parameter97_name: Parameter name + :param parameter97_value: Parameter value + :param parameter98_name: Parameter name + :param parameter98_value: Parameter value + :param parameter99_name: Parameter name + :param parameter99_value: Parameter value + + :returns: The created StreamInstance + """ + + data = values.of( + { + "Url": url, + "Name": name, + "Track": track, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Parameter1.Name": parameter1_name, + "Parameter1.Value": parameter1_value, + "Parameter2.Name": parameter2_name, + "Parameter2.Value": parameter2_value, + "Parameter3.Name": parameter3_name, + "Parameter3.Value": parameter3_value, + "Parameter4.Name": parameter4_name, + "Parameter4.Value": parameter4_value, + "Parameter5.Name": parameter5_name, + "Parameter5.Value": parameter5_value, + "Parameter6.Name": parameter6_name, + "Parameter6.Value": parameter6_value, + "Parameter7.Name": parameter7_name, + "Parameter7.Value": parameter7_value, + "Parameter8.Name": parameter8_name, + "Parameter8.Value": parameter8_value, + "Parameter9.Name": parameter9_name, + "Parameter9.Value": parameter9_value, + "Parameter10.Name": parameter10_name, + "Parameter10.Value": parameter10_value, + "Parameter11.Name": parameter11_name, + "Parameter11.Value": parameter11_value, + "Parameter12.Name": parameter12_name, + "Parameter12.Value": parameter12_value, + "Parameter13.Name": parameter13_name, + "Parameter13.Value": parameter13_value, + "Parameter14.Name": parameter14_name, + "Parameter14.Value": parameter14_value, + "Parameter15.Name": parameter15_name, + "Parameter15.Value": parameter15_value, + "Parameter16.Name": parameter16_name, + "Parameter16.Value": parameter16_value, + "Parameter17.Name": parameter17_name, + "Parameter17.Value": parameter17_value, + "Parameter18.Name": parameter18_name, + "Parameter18.Value": parameter18_value, + "Parameter19.Name": parameter19_name, + "Parameter19.Value": parameter19_value, + "Parameter20.Name": parameter20_name, + "Parameter20.Value": parameter20_value, + "Parameter21.Name": parameter21_name, + "Parameter21.Value": parameter21_value, + "Parameter22.Name": parameter22_name, + "Parameter22.Value": parameter22_value, + "Parameter23.Name": parameter23_name, + "Parameter23.Value": parameter23_value, + "Parameter24.Name": parameter24_name, + "Parameter24.Value": parameter24_value, + "Parameter25.Name": parameter25_name, + "Parameter25.Value": parameter25_value, + "Parameter26.Name": parameter26_name, + "Parameter26.Value": parameter26_value, + "Parameter27.Name": parameter27_name, + "Parameter27.Value": parameter27_value, + "Parameter28.Name": parameter28_name, + "Parameter28.Value": parameter28_value, + "Parameter29.Name": parameter29_name, + "Parameter29.Value": parameter29_value, + "Parameter30.Name": parameter30_name, + "Parameter30.Value": parameter30_value, + "Parameter31.Name": parameter31_name, + "Parameter31.Value": parameter31_value, + "Parameter32.Name": parameter32_name, + "Parameter32.Value": parameter32_value, + "Parameter33.Name": parameter33_name, + "Parameter33.Value": parameter33_value, + "Parameter34.Name": parameter34_name, + "Parameter34.Value": parameter34_value, + "Parameter35.Name": parameter35_name, + "Parameter35.Value": parameter35_value, + "Parameter36.Name": parameter36_name, + "Parameter36.Value": parameter36_value, + "Parameter37.Name": parameter37_name, + "Parameter37.Value": parameter37_value, + "Parameter38.Name": parameter38_name, + "Parameter38.Value": parameter38_value, + "Parameter39.Name": parameter39_name, + "Parameter39.Value": parameter39_value, + "Parameter40.Name": parameter40_name, + "Parameter40.Value": parameter40_value, + "Parameter41.Name": parameter41_name, + "Parameter41.Value": parameter41_value, + "Parameter42.Name": parameter42_name, + "Parameter42.Value": parameter42_value, + "Parameter43.Name": parameter43_name, + "Parameter43.Value": parameter43_value, + "Parameter44.Name": parameter44_name, + "Parameter44.Value": parameter44_value, + "Parameter45.Name": parameter45_name, + "Parameter45.Value": parameter45_value, + "Parameter46.Name": parameter46_name, + "Parameter46.Value": parameter46_value, + "Parameter47.Name": parameter47_name, + "Parameter47.Value": parameter47_value, + "Parameter48.Name": parameter48_name, + "Parameter48.Value": parameter48_value, + "Parameter49.Name": parameter49_name, + "Parameter49.Value": parameter49_value, + "Parameter50.Name": parameter50_name, + "Parameter50.Value": parameter50_value, + "Parameter51.Name": parameter51_name, + "Parameter51.Value": parameter51_value, + "Parameter52.Name": parameter52_name, + "Parameter52.Value": parameter52_value, + "Parameter53.Name": parameter53_name, + "Parameter53.Value": parameter53_value, + "Parameter54.Name": parameter54_name, + "Parameter54.Value": parameter54_value, + "Parameter55.Name": parameter55_name, + "Parameter55.Value": parameter55_value, + "Parameter56.Name": parameter56_name, + "Parameter56.Value": parameter56_value, + "Parameter57.Name": parameter57_name, + "Parameter57.Value": parameter57_value, + "Parameter58.Name": parameter58_name, + "Parameter58.Value": parameter58_value, + "Parameter59.Name": parameter59_name, + "Parameter59.Value": parameter59_value, + "Parameter60.Name": parameter60_name, + "Parameter60.Value": parameter60_value, + "Parameter61.Name": parameter61_name, + "Parameter61.Value": parameter61_value, + "Parameter62.Name": parameter62_name, + "Parameter62.Value": parameter62_value, + "Parameter63.Name": parameter63_name, + "Parameter63.Value": parameter63_value, + "Parameter64.Name": parameter64_name, + "Parameter64.Value": parameter64_value, + "Parameter65.Name": parameter65_name, + "Parameter65.Value": parameter65_value, + "Parameter66.Name": parameter66_name, + "Parameter66.Value": parameter66_value, + "Parameter67.Name": parameter67_name, + "Parameter67.Value": parameter67_value, + "Parameter68.Name": parameter68_name, + "Parameter68.Value": parameter68_value, + "Parameter69.Name": parameter69_name, + "Parameter69.Value": parameter69_value, + "Parameter70.Name": parameter70_name, + "Parameter70.Value": parameter70_value, + "Parameter71.Name": parameter71_name, + "Parameter71.Value": parameter71_value, + "Parameter72.Name": parameter72_name, + "Parameter72.Value": parameter72_value, + "Parameter73.Name": parameter73_name, + "Parameter73.Value": parameter73_value, + "Parameter74.Name": parameter74_name, + "Parameter74.Value": parameter74_value, + "Parameter75.Name": parameter75_name, + "Parameter75.Value": parameter75_value, + "Parameter76.Name": parameter76_name, + "Parameter76.Value": parameter76_value, + "Parameter77.Name": parameter77_name, + "Parameter77.Value": parameter77_value, + "Parameter78.Name": parameter78_name, + "Parameter78.Value": parameter78_value, + "Parameter79.Name": parameter79_name, + "Parameter79.Value": parameter79_value, + "Parameter80.Name": parameter80_name, + "Parameter80.Value": parameter80_value, + "Parameter81.Name": parameter81_name, + "Parameter81.Value": parameter81_value, + "Parameter82.Name": parameter82_name, + "Parameter82.Value": parameter82_value, + "Parameter83.Name": parameter83_name, + "Parameter83.Value": parameter83_value, + "Parameter84.Name": parameter84_name, + "Parameter84.Value": parameter84_value, + "Parameter85.Name": parameter85_name, + "Parameter85.Value": parameter85_value, + "Parameter86.Name": parameter86_name, + "Parameter86.Value": parameter86_value, + "Parameter87.Name": parameter87_name, + "Parameter87.Value": parameter87_value, + "Parameter88.Name": parameter88_name, + "Parameter88.Value": parameter88_value, + "Parameter89.Name": parameter89_name, + "Parameter89.Value": parameter89_value, + "Parameter90.Name": parameter90_name, + "Parameter90.Value": parameter90_value, + "Parameter91.Name": parameter91_name, + "Parameter91.Value": parameter91_value, + "Parameter92.Name": parameter92_name, + "Parameter92.Value": parameter92_value, + "Parameter93.Name": parameter93_name, + "Parameter93.Value": parameter93_value, + "Parameter94.Name": parameter94_name, + "Parameter94.Value": parameter94_value, + "Parameter95.Name": parameter95_name, + "Parameter95.Value": parameter95_value, + "Parameter96.Name": parameter96_name, + "Parameter96.Value": parameter96_value, + "Parameter97.Name": parameter97_name, + "Parameter97.Value": parameter97_value, + "Parameter98.Name": parameter98_name, + "Parameter98.Value": parameter98_value, + "Parameter99.Name": parameter99_name, + "Parameter99.Value": parameter99_value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return StreamInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def get(self, sid: str) -> StreamContext: + """ + Constructs a StreamContext + + :param sid: The SID or the `name` of the Stream resource to be stopped + """ + return StreamContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> StreamContext: + """ + Constructs a StreamContext + + :param sid: The SID or the `name` of the Stream resource to be stopped + """ + return StreamContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.StreamList>" diff --git a/twilio/rest/api/v2010/account/call/transcription.py b/twilio/rest/api/v2010/account/call/transcription.py new file mode 100644 index 0000000000..4f8f9125b6 --- /dev/null +++ b/twilio/rest/api/v2010/account/call/transcription.py @@ -0,0 +1,439 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TranscriptionInstance(InstanceResource): + + class Status(object): + IN_PROGRESS = "in-progress" + STOPPED = "stopped" + + class Track(object): + INBOUND_TRACK = "inbound_track" + OUTBOUND_TRACK = "outbound_track" + BOTH_TRACKS = "both_tracks" + + class UpdateStatus(object): + STOPPED = "stopped" + + """ + :ivar sid: The SID of the Transcription resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Transcription resource. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Transcription resource is associated with. + :ivar name: The user-specified name of this Transcription, if one was given when the Transcription was created. This may be used to stop the Transcription. + :ivar status: + :ivar date_updated: The date and time in GMT that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar uri: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + call_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.name: Optional[str] = payload.get("name") + self.status: Optional["TranscriptionInstance.Status"] = payload.get("status") + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } + self._context: Optional[TranscriptionContext] = None + + @property + def _proxy(self) -> "TranscriptionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TranscriptionContext for this TranscriptionInstance + """ + if self._context is None: + self._context = TranscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return self._context + + def update( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> "TranscriptionInstance": + """ + Update the TranscriptionInstance + + :param status: + + :returns: The updated TranscriptionInstance + """ + return self._proxy.update( + status=status, + ) + + async def update_async( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> "TranscriptionInstance": + """ + Asynchronous coroutine to update the TranscriptionInstance + + :param status: + + :returns: The updated TranscriptionInstance + """ + return await self._proxy.update_async( + status=status, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.TranscriptionInstance {}>".format(context) + + +class TranscriptionContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): + """ + Initialize the TranscriptionContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Transcription resource. + :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Transcription resource is associated with. + :param sid: The SID of the Transcription resource, or the `name` used when creating the resource + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/Transcriptions/{sid}.json".format( + **self._solution + ) + ) + + def update( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> TranscriptionInstance: + """ + Update the TranscriptionInstance + + :param status: + + :returns: The updated TranscriptionInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> TranscriptionInstance: + """ + Asynchronous coroutine to update the TranscriptionInstance + + :param status: + + :returns: The updated TranscriptionInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.TranscriptionContext {}>".format(context) + + +class TranscriptionList(ListResource): + + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the TranscriptionList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Transcription resource. + :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Transcription resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/Transcriptions.json".format( + **self._solution + ) + ) + + def create( + self, + name: Union[str, object] = values.unset, + track: Union["TranscriptionInstance.Track", object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + inbound_track_label: Union[str, object] = values.unset, + outbound_track_label: Union[str, object] = values.unset, + partial_results: Union[bool, object] = values.unset, + language_code: Union[str, object] = values.unset, + transcription_engine: Union[str, object] = values.unset, + profanity_filter: Union[bool, object] = values.unset, + speech_model: Union[str, object] = values.unset, + hints: Union[str, object] = values.unset, + enable_automatic_punctuation: Union[bool, object] = values.unset, + intelligence_service: Union[str, object] = values.unset, + ) -> TranscriptionInstance: + """ + Create the TranscriptionInstance + + :param name: The user-specified name of this Transcription, if one was given when the Transcription was created. This may be used to stop the Transcription. + :param track: + :param status_callback_url: Absolute URL of the status callback. + :param status_callback_method: The http method for the status_callback (one of GET, POST). + :param inbound_track_label: Friendly name given to the Inbound Track + :param outbound_track_label: Friendly name given to the Outbound Track + :param partial_results: Indicates if partial results are going to be sent to the customer + :param language_code: Language code used by the transcription engine, specified in [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) format + :param transcription_engine: Definition of the transcription engine to be used, among those supported by Twilio + :param profanity_filter: indicates if the server will attempt to filter out profanities, replacing all but the initial character in each filtered word with asterisks + :param speech_model: Recognition model used by the transcription engine, among those supported by the provider + :param hints: A Phrase contains words and phrase \\\"hints\\\" so that the speech recognition engine is more likely to recognize them. + :param enable_automatic_punctuation: The provider will add punctuation to recognition result + :param intelligence_service: The SID or unique name of the [Intelligence Service](https://www.twilio.com/docs/conversational-intelligence/api/service-resource) for persisting transcripts and running post-call Language Operators . + + :returns: The created TranscriptionInstance + """ + + data = values.of( + { + "Name": name, + "Track": track, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "InboundTrackLabel": inbound_track_label, + "OutboundTrackLabel": outbound_track_label, + "PartialResults": serialize.boolean_to_string(partial_results), + "LanguageCode": language_code, + "TranscriptionEngine": transcription_engine, + "ProfanityFilter": serialize.boolean_to_string(profanity_filter), + "SpeechModel": speech_model, + "Hints": hints, + "EnableAutomaticPunctuation": serialize.boolean_to_string( + enable_automatic_punctuation + ), + "IntelligenceService": intelligence_service, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_async( + self, + name: Union[str, object] = values.unset, + track: Union["TranscriptionInstance.Track", object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + inbound_track_label: Union[str, object] = values.unset, + outbound_track_label: Union[str, object] = values.unset, + partial_results: Union[bool, object] = values.unset, + language_code: Union[str, object] = values.unset, + transcription_engine: Union[str, object] = values.unset, + profanity_filter: Union[bool, object] = values.unset, + speech_model: Union[str, object] = values.unset, + hints: Union[str, object] = values.unset, + enable_automatic_punctuation: Union[bool, object] = values.unset, + intelligence_service: Union[str, object] = values.unset, + ) -> TranscriptionInstance: + """ + Asynchronously create the TranscriptionInstance + + :param name: The user-specified name of this Transcription, if one was given when the Transcription was created. This may be used to stop the Transcription. + :param track: + :param status_callback_url: Absolute URL of the status callback. + :param status_callback_method: The http method for the status_callback (one of GET, POST). + :param inbound_track_label: Friendly name given to the Inbound Track + :param outbound_track_label: Friendly name given to the Outbound Track + :param partial_results: Indicates if partial results are going to be sent to the customer + :param language_code: Language code used by the transcription engine, specified in [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) format + :param transcription_engine: Definition of the transcription engine to be used, among those supported by Twilio + :param profanity_filter: indicates if the server will attempt to filter out profanities, replacing all but the initial character in each filtered word with asterisks + :param speech_model: Recognition model used by the transcription engine, among those supported by the provider + :param hints: A Phrase contains words and phrase \\\"hints\\\" so that the speech recognition engine is more likely to recognize them. + :param enable_automatic_punctuation: The provider will add punctuation to recognition result + :param intelligence_service: The SID or unique name of the [Intelligence Service](https://www.twilio.com/docs/conversational-intelligence/api/service-resource) for persisting transcripts and running post-call Language Operators . + + :returns: The created TranscriptionInstance + """ + + data = values.of( + { + "Name": name, + "Track": track, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "InboundTrackLabel": inbound_track_label, + "OutboundTrackLabel": outbound_track_label, + "PartialResults": serialize.boolean_to_string(partial_results), + "LanguageCode": language_code, + "TranscriptionEngine": transcription_engine, + "ProfanityFilter": serialize.boolean_to_string(profanity_filter), + "SpeechModel": speech_model, + "Hints": hints, + "EnableAutomaticPunctuation": serialize.boolean_to_string( + enable_automatic_punctuation + ), + "IntelligenceService": intelligence_service, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def get(self, sid: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param sid: The SID of the Transcription resource, or the `name` used when creating the resource + """ + return TranscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param sid: The SID of the Transcription resource, or the `name` used when creating the resource + """ + return TranscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.TranscriptionList>" diff --git a/twilio/rest/api/v2010/account/call/user_defined_message.py b/twilio/rest/api/v2010/account/call/user_defined_message.py new file mode 100644 index 0000000000..bc66f8b8e1 --- /dev/null +++ b/twilio/rest/api/v2010/account/call/user_defined_message.py @@ -0,0 +1,159 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class UserDefinedMessageInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created User Defined Message. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the User Defined Message is associated with. + :ivar sid: The SID that uniquely identifies this User Defined Message. + :ivar date_created: The date that this User Defined Message was created, given in RFC 2822 format. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], account_sid: str, call_sid: str + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.sid: Optional[str] = payload.get("sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.UserDefinedMessageInstance {}>".format(context) + + +class UserDefinedMessageList(ListResource): + + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the UserDefinedMessageList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created User Defined Message. + :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the User Defined Message is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/UserDefinedMessages.json".format( + **self._solution + ) + ) + + def create( + self, content: str, idempotency_key: Union[str, object] = values.unset + ) -> UserDefinedMessageInstance: + """ + Create the UserDefinedMessageInstance + + :param content: The User Defined Message in the form of URL-encoded JSON string. + :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. + + :returns: The created UserDefinedMessageInstance + """ + + data = values.of( + { + "Content": content, + "IdempotencyKey": idempotency_key, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserDefinedMessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_async( + self, content: str, idempotency_key: Union[str, object] = values.unset + ) -> UserDefinedMessageInstance: + """ + Asynchronously create the UserDefinedMessageInstance + + :param content: The User Defined Message in the form of URL-encoded JSON string. + :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. + + :returns: The created UserDefinedMessageInstance + """ + + data = values.of( + { + "Content": content, + "IdempotencyKey": idempotency_key, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserDefinedMessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.UserDefinedMessageList>" diff --git a/twilio/rest/api/v2010/account/call/user_defined_message_subscription.py b/twilio/rest/api/v2010/account/call/user_defined_message_subscription.py new file mode 100644 index 0000000000..66923d4b79 --- /dev/null +++ b/twilio/rest/api/v2010/account/call/user_defined_message_subscription.py @@ -0,0 +1,300 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class UserDefinedMessageSubscriptionInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that subscribed to the User Defined Messages. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the User Defined Message Subscription is associated with. This refers to the Call SID that is producing the User Defined Messages. + :ivar sid: The SID that uniquely identifies this User Defined Message Subscription. + :ivar date_created: The date that this User Defined Message Subscription was created, given in RFC 2822 format. + :ivar uri: The URI of the User Defined Message Subscription Resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + call_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.sid: Optional[str] = payload.get("sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserDefinedMessageSubscriptionContext] = None + + @property + def _proxy(self) -> "UserDefinedMessageSubscriptionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserDefinedMessageSubscriptionContext for this UserDefinedMessageSubscriptionInstance + """ + if self._context is None: + self._context = UserDefinedMessageSubscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserDefinedMessageSubscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserDefinedMessageSubscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.UserDefinedMessageSubscriptionInstance {}>".format( + context + ) + + +class UserDefinedMessageSubscriptionContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): + """ + Initialize the UserDefinedMessageSubscriptionContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that subscribed to the User Defined Messages. + :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the User Defined Message Subscription is associated with. This refers to the Call SID that is producing the User Defined Messages. + :param sid: The SID that uniquely identifies this User Defined Message Subscription. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Calls/{call_sid}/UserDefinedMessageSubscriptions/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the UserDefinedMessageSubscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserDefinedMessageSubscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.UserDefinedMessageSubscriptionContext {}>".format( + context + ) + + +class UserDefinedMessageSubscriptionList(ListResource): + + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the UserDefinedMessageSubscriptionList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that subscribed to the User Defined Messages. + :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the User Defined Messages subscription is associated with. This refers to the Call SID that is producing the user defined messages. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = "/Accounts/{account_sid}/Calls/{call_sid}/UserDefinedMessageSubscriptions.json".format( + **self._solution + ) + + def create( + self, + callback: str, + idempotency_key: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + ) -> UserDefinedMessageSubscriptionInstance: + """ + Create the UserDefinedMessageSubscriptionInstance + + :param callback: The URL we should call using the `method` to send user defined events to your application. URLs must contain a valid hostname (underscores are not permitted). + :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. + :param method: The HTTP method Twilio will use when requesting the above `Url`. Either `GET` or `POST`. Default is `POST`. + + :returns: The created UserDefinedMessageSubscriptionInstance + """ + + data = values.of( + { + "Callback": callback, + "IdempotencyKey": idempotency_key, + "Method": method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserDefinedMessageSubscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + async def create_async( + self, + callback: str, + idempotency_key: Union[str, object] = values.unset, + method: Union[str, object] = values.unset, + ) -> UserDefinedMessageSubscriptionInstance: + """ + Asynchronously create the UserDefinedMessageSubscriptionInstance + + :param callback: The URL we should call using the `method` to send user defined events to your application. URLs must contain a valid hostname (underscores are not permitted). + :param idempotency_key: A unique string value to identify API call. This should be a unique string value per API call and can be a randomly generated. + :param method: The HTTP method Twilio will use when requesting the above `Url`. Either `GET` or `POST`. Default is `POST`. + + :returns: The created UserDefinedMessageSubscriptionInstance + """ + + data = values.of( + { + "Callback": callback, + "IdempotencyKey": idempotency_key, + "Method": method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserDefinedMessageSubscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def get(self, sid: str) -> UserDefinedMessageSubscriptionContext: + """ + Constructs a UserDefinedMessageSubscriptionContext + + :param sid: The SID that uniquely identifies this User Defined Message Subscription. + """ + return UserDefinedMessageSubscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> UserDefinedMessageSubscriptionContext: + """ + Constructs a UserDefinedMessageSubscriptionContext + + :param sid: The SID that uniquely identifies this User Defined Message Subscription. + """ + return UserDefinedMessageSubscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.UserDefinedMessageSubscriptionList>" diff --git a/twilio/rest/api/v2010/account/conference/__init__.py b/twilio/rest/api/v2010/account/conference/__init__.py new file mode 100644 index 0000000000..672d9d0fea --- /dev/null +++ b/twilio/rest/api/v2010/account/conference/__init__.py @@ -0,0 +1,791 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.conference.participant import ParticipantList +from twilio.rest.api.v2010.account.conference.recording import RecordingList + + +class ConferenceInstance(InstanceResource): + + class ReasonConferenceEnded(object): + CONFERENCE_ENDED_VIA_API = "conference-ended-via-api" + PARTICIPANT_WITH_END_CONFERENCE_ON_EXIT_LEFT = ( + "participant-with-end-conference-on-exit-left" + ) + PARTICIPANT_WITH_END_CONFERENCE_ON_EXIT_KICKED = ( + "participant-with-end-conference-on-exit-kicked" + ) + LAST_PARTICIPANT_KICKED = "last-participant-kicked" + LAST_PARTICIPANT_LEFT = "last-participant-left" + + class Status(object): + INIT = "init" + IN_PROGRESS = "in-progress" + COMPLETED = "completed" + + class UpdateStatus(object): + COMPLETED = "completed" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Conference resource. + :ivar date_created: The date and time in UTC that this resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in UTC that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar api_version: The API version used to create this conference. + :ivar friendly_name: A string that you assigned to describe this conference room. Maximum length is 128 characters. + :ivar region: A string that represents the Twilio Region where the conference audio was mixed. May be `us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, and `jp1`. Basic conference audio will always be mixed in `us1`. Global Conference audio will be mixed nearest to the majority of participants. + :ivar sid: The unique, Twilio-provided string used to identify this Conference resource. + :ivar status: + :ivar uri: The URI of this resource, relative to `https://api.twilio.com`. + :ivar subresource_uris: A list of related resources identified by their URIs relative to `https://api.twilio.com`. + :ivar reason_conference_ended: + :ivar call_sid_ending_conference: The call SID that caused the conference to end. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.api_version: Optional[str] = payload.get("api_version") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.region: Optional[str] = payload.get("region") + self.sid: Optional[str] = payload.get("sid") + self.status: Optional["ConferenceInstance.Status"] = payload.get("status") + self.uri: Optional[str] = payload.get("uri") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.reason_conference_ended: Optional[ + "ConferenceInstance.ReasonConferenceEnded" + ] = payload.get("reason_conference_ended") + self.call_sid_ending_conference: Optional[str] = payload.get( + "call_sid_ending_conference" + ) + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[ConferenceContext] = None + + @property + def _proxy(self) -> "ConferenceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConferenceContext for this ConferenceInstance + """ + if self._context is None: + self._context = ConferenceContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ConferenceInstance": + """ + Fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConferenceInstance": + """ + Asynchronous coroutine to fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> "ConferenceInstance": + """ + Update the ConferenceInstance + + :param status: + :param announce_url: The URL we should call to announce something into the conference. The URL may return an MP3 file, a WAV file, or a TwiML document that contains `<Play>`, `<Say>`, `<Pause>`, or `<Redirect>` verbs. + :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` + + :returns: The updated ConferenceInstance + """ + return self._proxy.update( + status=status, + announce_url=announce_url, + announce_method=announce_method, + ) + + async def update_async( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> "ConferenceInstance": + """ + Asynchronous coroutine to update the ConferenceInstance + + :param status: + :param announce_url: The URL we should call to announce something into the conference. The URL may return an MP3 file, a WAV file, or a TwiML document that contains `<Play>`, `<Say>`, `<Pause>`, or `<Redirect>` verbs. + :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` + + :returns: The updated ConferenceInstance + """ + return await self._proxy.update_async( + status=status, + announce_url=announce_url, + announce_method=announce_method, + ) + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + return self._proxy.participants + + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + return self._proxy.recordings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.ConferenceInstance {}>".format(context) + + +class ConferenceContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the ConferenceContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Conference resource(s) to update. + :param sid: The Twilio-provided string that uniquely identifies the Conference resource to update + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Conferences/{sid}.json".format( + **self._solution + ) + + self._participants: Optional[ParticipantList] = None + self._recordings: Optional[RecordingList] = None + + def fetch(self) -> ConferenceInstance: + """ + Fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ConferenceInstance: + """ + Asynchronous coroutine to fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> ConferenceInstance: + """ + Update the ConferenceInstance + + :param status: + :param announce_url: The URL we should call to announce something into the conference. The URL may return an MP3 file, a WAV file, or a TwiML document that contains `<Play>`, `<Say>`, `<Pause>`, or `<Redirect>` verbs. + :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` + + :returns: The updated ConferenceInstance + """ + + data = values.of( + { + "Status": status, + "AnnounceUrl": announce_url, + "AnnounceMethod": announce_method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + status: Union["ConferenceInstance.UpdateStatus", object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + ) -> ConferenceInstance: + """ + Asynchronous coroutine to update the ConferenceInstance + + :param status: + :param announce_url: The URL we should call to announce something into the conference. The URL may return an MP3 file, a WAV file, or a TwiML document that contains `<Play>`, `<Say>`, `<Pause>`, or `<Redirect>` verbs. + :param announce_method: The HTTP method used to call `announce_url`. Can be: `GET` or `POST` and the default is `POST` + + :returns: The updated ConferenceInstance + """ + + data = values.of( + { + "Status": status, + "AnnounceUrl": announce_url, + "AnnounceMethod": announce_method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + if self._participants is None: + self._participants = ParticipantList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._participants + + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + if self._recordings is None: + self._recordings = RecordingList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._recordings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.ConferenceContext {}>".format(context) + + +class ConferencePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConferenceInstance: + """ + Build an instance of ConferenceInstance + + :param payload: Payload response from the API + """ + return ConferenceInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.ConferencePage>" + + +class ConferenceList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the ConferenceList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Conference resource(s) to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Conferences.json".format(**self._solution) + + def stream( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConferenceInstance]: + """ + Streams ConferenceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param date date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param str friendly_name: The string that identifies the Conference resources to read. + :param "ConferenceInstance.Status" status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + date_updated=date_updated, + date_updated_before=date_updated_before, + date_updated_after=date_updated_after, + friendly_name=friendly_name, + status=status, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConferenceInstance]: + """ + Asynchronously streams ConferenceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param date date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param str friendly_name: The string that identifies the Conference resources to read. + :param "ConferenceInstance.Status" status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + date_updated=date_updated, + date_updated_before=date_updated_before, + date_updated_after=date_updated_after, + friendly_name=friendly_name, + status=status, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConferenceInstance]: + """ + Lists ConferenceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param date date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param str friendly_name: The string that identifies the Conference resources to read. + :param "ConferenceInstance.Status" status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + date_updated=date_updated, + date_updated_before=date_updated_before, + date_updated_after=date_updated_after, + friendly_name=friendly_name, + status=status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConferenceInstance]: + """ + Asynchronously lists ConferenceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param date date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param str friendly_name: The string that identifies the Conference resources to read. + :param "ConferenceInstance.Status" status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + date_updated=date_updated, + date_updated_before=date_updated_before, + date_updated_after=date_updated_after, + friendly_name=friendly_name, + status=status, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConferencePage: + """ + Retrieve a single page of ConferenceInstance records from the API. + Request is executed immediately + + :param date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param friendly_name: The string that identifies the Conference resources to read. + :param status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConferenceInstance + """ + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "DateUpdated": serialize.iso8601_date(date_updated), + "DateUpdated<": serialize.iso8601_date(date_updated_before), + "DateUpdated>": serialize.iso8601_date(date_updated_after), + "FriendlyName": friendly_name, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConferencePage(self._version, response, self._solution) + + async def page_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + date_updated: Union[date, object] = values.unset, + date_updated_before: Union[date, object] = values.unset, + date_updated_after: Union[date, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union["ConferenceInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConferencePage: + """ + Asynchronously retrieve a single page of ConferenceInstance records from the API. + Request is executed immediately + + :param date_created: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date_created_before: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date_created_after: Only include conferences that were created on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read conferences that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read conferences that were created on or after midnight of this date. + :param date_updated: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date_updated_before: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param date_updated_after: Only include conferences that were last updated on this date. Specify a date as `YYYY-MM-DD` in UTC, for example: `2009-07-06`, to read only conferences that were last updated on this date. You can also specify an inequality, such as `DateUpdated<=YYYY-MM-DD`, to read conferences that were last updated on or before midnight of this date, and `DateUpdated>=YYYY-MM-DD` to read conferences that were last updated on or after midnight of this date. + :param friendly_name: The string that identifies the Conference resources to read. + :param status: The status of the resources to read. Can be: `init`, `in-progress`, or `completed`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConferenceInstance + """ + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "DateUpdated": serialize.iso8601_date(date_updated), + "DateUpdated<": serialize.iso8601_date(date_updated_before), + "DateUpdated>": serialize.iso8601_date(date_updated_after), + "FriendlyName": friendly_name, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConferencePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ConferencePage: + """ + Retrieve a specific page of ConferenceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConferenceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConferencePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ConferencePage: + """ + Asynchronously retrieve a specific page of ConferenceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConferenceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConferencePage(self._version, response, self._solution) + + def get(self, sid: str) -> ConferenceContext: + """ + Constructs a ConferenceContext + + :param sid: The Twilio-provided string that uniquely identifies the Conference resource to update + """ + return ConferenceContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ConferenceContext: + """ + Constructs a ConferenceContext + + :param sid: The Twilio-provided string that uniquely identifies the Conference resource to update + """ + return ConferenceContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.ConferenceList>" diff --git a/twilio/rest/api/v2010/account/conference/participant.py b/twilio/rest/api/v2010/account/conference/participant.py new file mode 100644 index 0000000000..3c49e5387c --- /dev/null +++ b/twilio/rest/api/v2010/account/conference/participant.py @@ -0,0 +1,1201 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ParticipantInstance(InstanceResource): + + class Status(object): + QUEUED = "queued" + CONNECTING = "connecting" + RINGING = "ringing" + CONNECTED = "connected" + COMPLETE = "complete" + FAILED = "failed" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Participant resource. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Participant resource is associated with. + :ivar label: The user-specified label of this participant, if one was given when the participant was created. This may be used to fetch, update or delete the participant. + :ivar call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + :ivar coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :ivar conference_sid: The SID of the conference the participant is in. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar end_conference_on_exit: Whether the conference ends when the participant leaves. Can be: `true` or `false` and the default is `false`. If `true`, the conference ends and all other participants drop out when the participant leaves. + :ivar muted: Whether the participant is muted. Can be `true` or `false`. + :ivar hold: Whether the participant is on hold. Can be `true` or `false`. + :ivar start_conference_on_enter: Whether the conference starts when the participant joins the conference, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :ivar status: + :ivar queue_time: The wait time in milliseconds before participant's call is placed. Only available in the response to a create participant request. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + conference_sid: str, + call_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.label: Optional[str] = payload.get("label") + self.call_sid_to_coach: Optional[str] = payload.get("call_sid_to_coach") + self.coaching: Optional[bool] = payload.get("coaching") + self.conference_sid: Optional[str] = payload.get("conference_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.end_conference_on_exit: Optional[bool] = payload.get( + "end_conference_on_exit" + ) + self.muted: Optional[bool] = payload.get("muted") + self.hold: Optional[bool] = payload.get("hold") + self.start_conference_on_enter: Optional[bool] = payload.get( + "start_conference_on_enter" + ) + self.status: Optional["ParticipantInstance.Status"] = payload.get("status") + self.queue_time: Optional[str] = payload.get("queue_time") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "conference_sid": conference_sid, + "call_sid": call_sid or self.call_sid, + } + self._context: Optional[ParticipantContext] = None + + @property + def _proxy(self) -> "ParticipantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ParticipantContext for this ParticipantInstance + """ + if self._context is None: + self._context = ParticipantContext( + self._version, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ParticipantInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ParticipantInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ParticipantInstance": + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ParticipantInstance": + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + hold_url: Union[str, object] = values.unset, + hold_method: Union[str, object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + beep_on_exit: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + ) -> "ParticipantInstance": + """ + Update the ParticipantInstance + + :param muted: Whether the participant should be muted. Can be `true` or `false`. `true` will mute the participant, and `false` will un-mute them. Anything value other than `true` or `false` is interpreted as `false`. + :param hold: Whether the participant should be on hold. Can be: `true` or `false`. `true` puts the participant on hold, and `false` lets them rejoin the conference. + :param hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold. The URL may return an MP3 file, a WAV file, or a TwiML document that contains `<Play>`, `<Say>`, `<Pause>`, or `<Redirect>` verbs. + :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. + :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains `<Play>`, `<Say>`, `<Pause>`, or `<Redirect>` verbs. + :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [<Conference> TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + + :returns: The updated ParticipantInstance + """ + return self._proxy.update( + muted=muted, + hold=hold, + hold_url=hold_url, + hold_method=hold_method, + announce_url=announce_url, + announce_method=announce_method, + wait_url=wait_url, + wait_method=wait_method, + beep_on_exit=beep_on_exit, + end_conference_on_exit=end_conference_on_exit, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, + ) + + async def update_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + hold_url: Union[str, object] = values.unset, + hold_method: Union[str, object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + beep_on_exit: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + ) -> "ParticipantInstance": + """ + Asynchronous coroutine to update the ParticipantInstance + + :param muted: Whether the participant should be muted. Can be `true` or `false`. `true` will mute the participant, and `false` will un-mute them. Anything value other than `true` or `false` is interpreted as `false`. + :param hold: Whether the participant should be on hold. Can be: `true` or `false`. `true` puts the participant on hold, and `false` lets them rejoin the conference. + :param hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold. The URL may return an MP3 file, a WAV file, or a TwiML document that contains `<Play>`, `<Say>`, `<Pause>`, or `<Redirect>` verbs. + :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. + :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains `<Play>`, `<Say>`, `<Pause>`, or `<Redirect>` verbs. + :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [<Conference> TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + + :returns: The updated ParticipantInstance + """ + return await self._proxy.update_async( + muted=muted, + hold=hold, + hold_url=hold_url, + hold_method=hold_method, + announce_url=announce_url, + announce_method=announce_method, + wait_url=wait_url, + wait_method=wait_method, + beep_on_exit=beep_on_exit, + end_conference_on_exit=end_conference_on_exit, + coaching=coaching, + call_sid_to_coach=call_sid_to_coach, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.ParticipantInstance {}>".format(context) + + +class ParticipantContext(InstanceContext): + + def __init__( + self, version: Version, account_sid: str, conference_sid: str, call_sid: str + ): + """ + Initialize the ParticipantContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Participant resources to update. + :param conference_sid: The SID of the conference with the participant to update. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID or label of the participant to update. Non URL safe characters in a label must be percent encoded, for example, a space character is represented as %20. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "conference_sid": conference_sid, + "call_sid": call_sid, + } + self._uri = "/Accounts/{account_sid}/Conferences/{conference_sid}/Participants/{call_sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the ParticipantInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ParticipantInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + + def update( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + hold_url: Union[str, object] = values.unset, + hold_method: Union[str, object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + beep_on_exit: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Update the ParticipantInstance + + :param muted: Whether the participant should be muted. Can be `true` or `false`. `true` will mute the participant, and `false` will un-mute them. Anything value other than `true` or `false` is interpreted as `false`. + :param hold: Whether the participant should be on hold. Can be: `true` or `false`. `true` puts the participant on hold, and `false` lets them rejoin the conference. + :param hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold. The URL may return an MP3 file, a WAV file, or a TwiML document that contains `<Play>`, `<Say>`, `<Pause>`, or `<Redirect>` verbs. + :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. + :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains `<Play>`, `<Say>`, `<Pause>`, or `<Redirect>` verbs. + :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [<Conference> TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + + :returns: The updated ParticipantInstance + """ + + data = values.of( + { + "Muted": serialize.boolean_to_string(muted), + "Hold": serialize.boolean_to_string(hold), + "HoldUrl": hold_url, + "HoldMethod": hold_method, + "AnnounceUrl": announce_url, + "AnnounceMethod": announce_method, + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "BeepOnExit": serialize.boolean_to_string(beep_on_exit), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "Coaching": serialize.boolean_to_string(coaching), + "CallSidToCoach": call_sid_to_coach, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + + async def update_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + hold_url: Union[str, object] = values.unset, + hold_method: Union[str, object] = values.unset, + announce_url: Union[str, object] = values.unset, + announce_method: Union[str, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + beep_on_exit: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronous coroutine to update the ParticipantInstance + + :param muted: Whether the participant should be muted. Can be `true` or `false`. `true` will mute the participant, and `false` will un-mute them. Anything value other than `true` or `false` is interpreted as `false`. + :param hold: Whether the participant should be on hold. Can be: `true` or `false`. `true` puts the participant on hold, and `false` lets them rejoin the conference. + :param hold_url: The URL we call using the `hold_method` for music that plays when the participant is on hold. The URL may return an MP3 file, a WAV file, or a TwiML document that contains `<Play>`, `<Say>`, `<Pause>`, or `<Redirect>` verbs. + :param hold_method: The HTTP method we should use to call `hold_url`. Can be: `GET` or `POST` and the default is `GET`. + :param announce_url: The URL we call using the `announce_method` for an announcement to the participant. The URL may return an MP3 file, a WAV file, or a TwiML document that contains `<Play>`, `<Say>`, `<Pause>`, or `<Redirect>` verbs. + :param announce_method: The HTTP method we should use to call `announce_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [<Conference> TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param beep_on_exit: Whether to play a notification beep to the conference when the participant exits. Can be: `true` or `false`. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + + :returns: The updated ParticipantInstance + """ + + data = values.of( + { + "Muted": serialize.boolean_to_string(muted), + "Hold": serialize.boolean_to_string(hold), + "HoldUrl": hold_url, + "HoldMethod": hold_method, + "AnnounceUrl": announce_url, + "AnnounceMethod": announce_method, + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "BeepOnExit": serialize.boolean_to_string(beep_on_exit), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "Coaching": serialize.boolean_to_string(coaching), + "CallSidToCoach": call_sid_to_coach, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.ParticipantContext {}>".format(context) + + +class ParticipantPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: + """ + Build an instance of ParticipantInstance + + :param payload: Payload response from the API + """ + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.ParticipantPage>" + + +class ParticipantList(ListResource): + + def __init__(self, version: Version, account_sid: str, conference_sid: str): + """ + Initialize the ParticipantList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Participant resources to read. + :param conference_sid: The SID of the conference with the participants to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "conference_sid": conference_sid, + } + self._uri = "/Accounts/{account_sid}/Conferences/{conference_sid}/Participants.json".format( + **self._solution + ) + + def create( + self, + from_: str, + to: str, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[List[str], object] = values.unset, + label: Union[str, object] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[List[str], object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + conference_recording_status_callback_event: Union[ + List[str], object + ] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + byoc: Union[str, object] = values.unset, + caller_id: Union[str, object] = values.unset, + call_reason: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + machine_detection: Union[str, object] = values.unset, + machine_detection_timeout: Union[int, object] = values.unset, + machine_detection_speech_threshold: Union[int, object] = values.unset, + machine_detection_speech_end_threshold: Union[int, object] = values.unset, + machine_detection_silence_timeout: Union[int, object] = values.unset, + amd_status_callback: Union[str, object] = values.unset, + amd_status_callback_method: Union[str, object] = values.unset, + trim: Union[str, object] = values.unset, + call_token: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Create the ParticipantInstance + + :param from_: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `from` must also be a phone number. If `to` is sip address, this value of `from` should be a username portion to be used to populate the P-Asserted-Identity header that is passed to the SIP endpoint. + :param to: The phone number, SIP address, or Client identifier that received this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `sip:name@company.com`. Client identifiers are formatted `client:name`. [Custom parameters](https://www.twilio.com/docs/voice/api/conference-participant-resource#custom-parameters) may also be specified. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` and `POST` and defaults to `POST`. + :param status_callback_event: The conference state changes that should generate a call to `status_callback`. Can be: `initiated`, `ringing`, `answered`, and `completed`. Separate multiple values with a space. The default value is `completed`. + :param label: A label for this participant. If one is supplied, it may subsequently be used to fetch, update or delete the participant. + :param timeout: The number of seconds that we should allow the phone to ring before assuming there is no answer. Can be an integer between `5` and `600`, inclusive. The default value is `60`. We always add a 5-second timeout buffer to outgoing calls, so value of 10 would result in an actual timeout that was closer to 15 seconds. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Can be `true` or `false` and the default is `false`. + :param beep: Whether to play a notification beep to the conference when the participant joins. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [<Conference> TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. Can be: `true` or `false` and defaults to `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_record: Whether to record the conference the participant is joining. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from the conference recording. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference state changes that should generate a call to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `modify`, `speaker`, and `announcement`. Separate multiple values with a space. Defaults to `start end`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param recording_status_callback_event: The recording state changes that should generate a call to `recording_status_callback`. Can be: `started`, `in-progress`, `paused`, `resumed`, `stopped`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'`. + :param conference_recording_status_callback_event: The conference recording state changes that generate a call to `conference_recording_status_callback`. Can be: `in-progress`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'` + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + :param jitter_buffer_size: Jitter buffer size for the connecting participant. Twilio will use this setting to apply Jitter Buffer before participant's audio is mixed into the conference. Can be: `off`, `small`, `medium`, and `large`. Default to `large`. + :param byoc: The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) + :param caller_id: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `callerId` must also be a phone number. If `to` is sip address, this value of `callerId` should be a username portion to be used to populate the From header that is passed to the SIP endpoint. + :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is sent from Twilio. `both` records the audio that is received and sent by Twilio. + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). + :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. + :param machine_detection_speech_threshold: The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. + :param machine_detection_speech_end_threshold: The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. + :param machine_detection_silence_timeout: The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. + :param amd_status_callback: The URL that we should call using the `amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. + :param amd_status_callback_method: The HTTP method we should use when calling the `amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param trim: Whether to trim any leading and trailing silence from the participant recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. + :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. + + :returns: The created ParticipantInstance + """ + + data = values.of( + { + "From": from_, + "To": to, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Label": label, + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), + "Beep": beep, + "StartConferenceOnEnter": serialize.boolean_to_string( + start_conference_on_enter + ), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "EarlyMedia": serialize.boolean_to_string(early_media), + "MaxParticipants": max_participants, + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "Region": region, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "RecordingStatusCallbackEvent": serialize.map( + recording_status_callback_event, lambda e: e + ), + "ConferenceRecordingStatusCallbackEvent": serialize.map( + conference_recording_status_callback_event, lambda e: e + ), + "Coaching": serialize.boolean_to_string(coaching), + "CallSidToCoach": call_sid_to_coach, + "JitterBufferSize": jitter_buffer_size, + "Byoc": byoc, + "CallerId": caller_id, + "CallReason": call_reason, + "RecordingTrack": recording_track, + "TimeLimit": time_limit, + "MachineDetection": machine_detection, + "MachineDetectionTimeout": machine_detection_timeout, + "MachineDetectionSpeechThreshold": machine_detection_speech_threshold, + "MachineDetectionSpeechEndThreshold": machine_detection_speech_end_threshold, + "MachineDetectionSilenceTimeout": machine_detection_silence_timeout, + "AmdStatusCallback": amd_status_callback, + "AmdStatusCallbackMethod": amd_status_callback_method, + "Trim": trim, + "CallToken": call_token, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + ) + + async def create_async( + self, + from_: str, + to: str, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[List[str], object] = values.unset, + label: Union[str, object] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[List[str], object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + recording_status_callback_event: Union[List[str], object] = values.unset, + conference_recording_status_callback_event: Union[ + List[str], object + ] = values.unset, + coaching: Union[bool, object] = values.unset, + call_sid_to_coach: Union[str, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + byoc: Union[str, object] = values.unset, + caller_id: Union[str, object] = values.unset, + call_reason: Union[str, object] = values.unset, + recording_track: Union[str, object] = values.unset, + time_limit: Union[int, object] = values.unset, + machine_detection: Union[str, object] = values.unset, + machine_detection_timeout: Union[int, object] = values.unset, + machine_detection_speech_threshold: Union[int, object] = values.unset, + machine_detection_speech_end_threshold: Union[int, object] = values.unset, + machine_detection_silence_timeout: Union[int, object] = values.unset, + amd_status_callback: Union[str, object] = values.unset, + amd_status_callback_method: Union[str, object] = values.unset, + trim: Union[str, object] = values.unset, + call_token: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronously create the ParticipantInstance + + :param from_: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `from` must also be a phone number. If `to` is sip address, this value of `from` should be a username portion to be used to populate the P-Asserted-Identity header that is passed to the SIP endpoint. + :param to: The phone number, SIP address, or Client identifier that received this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). SIP addresses are formatted as `sip:name@company.com`. Client identifiers are formatted `client:name`. [Custom parameters](https://www.twilio.com/docs/voice/api/conference-participant-resource#custom-parameters) may also be specified. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` and `POST` and defaults to `POST`. + :param status_callback_event: The conference state changes that should generate a call to `status_callback`. Can be: `initiated`, `ringing`, `answered`, and `completed`. Separate multiple values with a space. The default value is `completed`. + :param label: A label for this participant. If one is supplied, it may subsequently be used to fetch, update or delete the participant. + :param timeout: The number of seconds that we should allow the phone to ring before assuming there is no answer. Can be an integer between `5` and `600`, inclusive. The default value is `60`. We always add a 5-second timeout buffer to outgoing calls, so value of 10 would result in an actual timeout that was closer to 15 seconds. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Can be `true` or `false` and the default is `false`. + :param beep: Whether to play a notification beep to the conference when the participant joins. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the participant leaves. Can be: `true` or `false` and defaults to `false`. + :param wait_url: The URL that Twilio calls using the `wait_method` before the conference has started. The URL may return an MP3 file, a WAV file, or a TwiML document. The default value is the URL of our standard hold music. If you do not want anything to play while waiting for the conference to start, specify an empty string by setting `wait_url` to `''`. For more details on the allowable verbs within the `waitUrl`, see the `waitUrl` attribute in the [<Conference> TwiML instruction](https://www.twilio.com/docs/voice/twiml/conference#attributes-waiturl). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. Can be: `true` or `false` and defaults to `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_record: Whether to record the conference the participant is joining. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from the conference recording. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference state changes that should generate a call to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `modify`, `speaker`, and `announcement`. Separate multiple values with a space. Defaults to `start end`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param recording_status_callback_event: The recording state changes that should generate a call to `recording_status_callback`. Can be: `started`, `in-progress`, `paused`, `resumed`, `stopped`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'`. + :param conference_recording_status_callback_event: The conference recording state changes that generate a call to `conference_recording_status_callback`. Can be: `in-progress`, `completed`, `failed`, and `absent`. Separate multiple values with a space, ex: `'in-progress completed failed'` + :param coaching: Whether the participant is coaching another call. Can be: `true` or `false`. If not present, defaults to `false` unless `call_sid_to_coach` is defined. If `true`, `call_sid_to_coach` must be defined. + :param call_sid_to_coach: The SID of the participant who is being `coached`. The participant being coached is the only participant who can hear the participant who is `coaching`. + :param jitter_buffer_size: Jitter buffer size for the connecting participant. Twilio will use this setting to apply Jitter Buffer before participant's audio is mixed into the conference. Can be: `off`, `small`, `medium`, and `large`. Default to `large`. + :param byoc: The SID of a BYOC (Bring Your Own Carrier) trunk to route this call with. Note that `byoc` is only meaningful when `to` is a phone number; it will otherwise be ignored. (Beta) + :param caller_id: The phone number, Client identifier, or username portion of SIP address that made this call. Phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +16175551212). Client identifiers are formatted `client:name`. If using a phone number, it must be a Twilio number or a Verified [outgoing caller id](https://www.twilio.com/docs/voice/api/outgoing-caller-ids) for your account. If the `to` parameter is a phone number, `callerId` must also be a phone number. If `to` is sip address, this value of `callerId` should be a username portion to be used to populate the From header that is passed to the SIP endpoint. + :param call_reason: The Reason for the outgoing call. Use it to specify the purpose of the call that is presented on the called party's phone. (Branded Calls Beta) + :param recording_track: The audio track to record for the call. Can be: `inbound`, `outbound` or `both`. The default is `both`. `inbound` records the audio that is received by Twilio. `outbound` records the audio that is sent from Twilio. `both` records the audio that is received and sent by Twilio. + :param time_limit: The maximum duration of the call in seconds. Constraints depend on account and configuration. + :param machine_detection: Whether to detect if a human, answering machine, or fax has picked up the call. Can be: `Enable` or `DetectMessageEnd`. Use `Enable` if you would like us to return `AnsweredBy` as soon as the called party is identified. Use `DetectMessageEnd`, if you would like to leave a message on an answering machine. For more information, see [Answering Machine Detection](https://www.twilio.com/docs/voice/answering-machine-detection). + :param machine_detection_timeout: The number of seconds that we should attempt to detect an answering machine before timing out and sending a voice request with `AnsweredBy` of `unknown`. The default timeout is 30 seconds. + :param machine_detection_speech_threshold: The number of milliseconds that is used as the measuring stick for the length of the speech activity, where durations lower than this value will be interpreted as a human and longer than this value as a machine. Possible Values: 1000-6000. Default: 2400. + :param machine_detection_speech_end_threshold: The number of milliseconds of silence after speech activity at which point the speech activity is considered complete. Possible Values: 500-5000. Default: 1200. + :param machine_detection_silence_timeout: The number of milliseconds of initial silence after which an `unknown` AnsweredBy result will be returned. Possible Values: 2000-10000. Default: 5000. + :param amd_status_callback: The URL that we should call using the `amd_status_callback_method` to notify customer application whether the call was answered by human, machine or fax. + :param amd_status_callback_method: The HTTP method we should use when calling the `amd_status_callback` URL. Can be: `GET` or `POST` and the default is `POST`. + :param trim: Whether to trim any leading and trailing silence from the participant recording. Can be: `trim-silence` or `do-not-trim` and the default is `trim-silence`. + :param call_token: A token string needed to invoke a forwarded call. A call_token is generated when an incoming call is received on a Twilio number. Pass an incoming call's call_token value to a forwarded call via the call_token parameter when creating a new call. A forwarded call should bear the same CallerID of the original incoming call. + + :returns: The created ParticipantInstance + """ + + data = values.of( + { + "From": from_, + "To": to, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Label": label, + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), + "Beep": beep, + "StartConferenceOnEnter": serialize.boolean_to_string( + start_conference_on_enter + ), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "EarlyMedia": serialize.boolean_to_string(early_media), + "MaxParticipants": max_participants, + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "Region": region, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "RecordingStatusCallbackEvent": serialize.map( + recording_status_callback_event, lambda e: e + ), + "ConferenceRecordingStatusCallbackEvent": serialize.map( + conference_recording_status_callback_event, lambda e: e + ), + "Coaching": serialize.boolean_to_string(coaching), + "CallSidToCoach": call_sid_to_coach, + "JitterBufferSize": jitter_buffer_size, + "Byoc": byoc, + "CallerId": caller_id, + "CallReason": call_reason, + "RecordingTrack": recording_track, + "TimeLimit": time_limit, + "MachineDetection": machine_detection, + "MachineDetectionTimeout": machine_detection_timeout, + "MachineDetectionSpeechThreshold": machine_detection_speech_threshold, + "MachineDetectionSpeechEndThreshold": machine_detection_speech_end_threshold, + "MachineDetectionSilenceTimeout": machine_detection_silence_timeout, + "AmdStatusCallback": amd_status_callback, + "AmdStatusCallbackMethod": amd_status_callback_method, + "Trim": trim, + "CallToken": call_token, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + ) + + def stream( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantInstance]: + """ + Streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param bool hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param bool coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + muted=muted, hold=hold, coaching=coaching, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ParticipantInstance]: + """ + Asynchronously streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param bool hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param bool coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + muted=muted, hold=hold, coaching=coaching, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param bool hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param bool coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + muted=muted, + hold=hold, + coaching=coaching, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Asynchronously lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param bool hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param bool coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + muted=muted, + hold=hold, + coaching=coaching, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "Muted": serialize.boolean_to_string(muted), + "Hold": serialize.boolean_to_string(hold), + "Coaching": serialize.boolean_to_string(coaching), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + async def page_async( + self, + muted: Union[bool, object] = values.unset, + hold: Union[bool, object] = values.unset, + coaching: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Asynchronously retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param muted: Whether to return only participants that are muted. Can be: `true` or `false`. + :param hold: Whether to return only participants that are on hold. Can be: `true` or `false`. + :param coaching: Whether to return only participants who are coaching another call. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "Muted": serialize.boolean_to_string(muted), + "Hold": serialize.boolean_to_string(hold), + "Coaching": serialize.boolean_to_string(coaching), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ParticipantPage: + """ + Retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ParticipantPage: + """ + Asynchronously retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + def get(self, call_sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID or label of the participant to update. Non URL safe characters in a label must be percent encoded, for example, a space character is represented as %20. + """ + return ParticipantContext( + self._version, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=call_sid, + ) + + def __call__(self, call_sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID or label of the participant to update. Non URL safe characters in a label must be percent encoded, for example, a space character is represented as %20. + """ + return ParticipantContext( + self._version, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=call_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.ParticipantList>" diff --git a/twilio/rest/api/v2010/account/conference/recording.py b/twilio/rest/api/v2010/account/conference/recording.py new file mode 100644 index 0000000000..12008ed37f --- /dev/null +++ b/twilio/rest/api/v2010/account/conference/recording.py @@ -0,0 +1,718 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RecordingInstance(InstanceResource): + + class Source(object): + DIALVERB = "DialVerb" + CONFERENCE = "Conference" + OUTBOUNDAPI = "OutboundAPI" + TRUNKING = "Trunking" + RECORDVERB = "RecordVerb" + STARTCALLRECORDINGAPI = "StartCallRecordingAPI" + STARTCONFERENCERECORDINGAPI = "StartConferenceRecordingAPI" + + class Status(object): + IN_PROGRESS = "in-progress" + PAUSED = "paused" + STOPPED = "stopped" + PROCESSING = "processing" + COMPLETED = "completed" + ABSENT = "absent" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Conference Recording resource. + :ivar api_version: The API version used to create the recording. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Conference Recording resource is associated with. + :ivar conference_sid: The Conference SID that identifies the conference associated with the recording. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar start_time: The start time of the recording in GMT and in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar duration: The length of the recording in seconds. + :ivar sid: The unique string that that we created to identify the Conference Recording resource. + :ivar price: The one-time cost of creating the recording in the `price_unit` currency. + :ivar price_unit: The currency used in the `price` property. Example: `USD`. + :ivar status: + :ivar channels: The number of channels in the final recording file. Can be: `1`, or `2`. Separating a two leg call into two separate channels of the recording file is supported in [Dial](https://www.twilio.com/docs/voice/twiml/dial#attributes-record) and [Outbound Rest API](https://www.twilio.com/docs/voice/make-calls) record options. + :ivar source: + :ivar error_code: The error code that describes why the recording is `absent`. The error code is described in our [Error Dictionary](https://www.twilio.com/docs/api/errors). This value is null if the recording `status` is not `absent`. + :ivar encryption_details: How to decrypt the recording if it was encrypted using [Call Recording Encryption](https://www.twilio.com/docs/voice/tutorials/voice-recording-encryption) feature. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + conference_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.call_sid: Optional[str] = payload.get("call_sid") + self.conference_sid: Optional[str] = payload.get("conference_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.start_time: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("start_time") + ) + self.duration: Optional[str] = payload.get("duration") + self.sid: Optional[str] = payload.get("sid") + self.price: Optional[str] = payload.get("price") + self.price_unit: Optional[str] = payload.get("price_unit") + self.status: Optional["RecordingInstance.Status"] = payload.get("status") + self.channels: Optional[int] = deserialize.integer(payload.get("channels")) + self.source: Optional["RecordingInstance.Source"] = payload.get("source") + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.encryption_details: Optional[Dict[str, object]] = payload.get( + "encryption_details" + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "conference_sid": conference_sid, + "sid": sid or self.sid, + } + self._context: Optional[RecordingContext] = None + + @property + def _proxy(self) -> "RecordingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RecordingContext for this RecordingInstance + """ + if self._context is None: + self._context = RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RecordingInstance": + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RecordingInstance": + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> "RecordingInstance": + """ + Update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance + """ + return self._proxy.update( + status=status, + pause_behavior=pause_behavior, + ) + + async def update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> "RecordingInstance": + """ + Asynchronous coroutine to update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance + """ + return await self._proxy.update_async( + status=status, + pause_behavior=pause_behavior, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.RecordingInstance {}>".format(context) + + +class RecordingContext(InstanceContext): + + def __init__( + self, version: Version, account_sid: str, conference_sid: str, sid: str + ): + """ + Initialize the RecordingContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Conference Recording resource to update. + :param conference_sid: The Conference SID that identifies the conference associated with the recording to update. + :param sid: The Twilio-provided string that uniquely identifies the Conference Recording resource to update. Use `Twilio.CURRENT` to reference the current active recording. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "conference_sid": conference_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Conferences/{conference_sid}/Recordings/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RecordingInstance: + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> RecordingInstance: + """ + Update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance + """ + + data = values.of( + { + "Status": status, + "PauseBehavior": pause_behavior, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + status: "RecordingInstance.Status", + pause_behavior: Union[str, object] = values.unset, + ) -> RecordingInstance: + """ + Asynchronous coroutine to update the RecordingInstance + + :param status: + :param pause_behavior: Whether to record during a pause. Can be: `skip` or `silence` and the default is `silence`. `skip` does not record during the pause period, while `silence` will replace the actual audio of the call with silence during the pause period. This parameter only applies when setting `status` is set to `paused`. + + :returns: The updated RecordingInstance + """ + + data = values.of( + { + "Status": status, + "PauseBehavior": pause_behavior, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.RecordingContext {}>".format(context) + + +class RecordingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: + """ + Build an instance of RecordingInstance + + :param payload: Payload response from the API + """ + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.RecordingPage>" + + +class RecordingList(ListResource): + + def __init__(self, version: Version, account_sid: str, conference_sid: str): + """ + Initialize the RecordingList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Conference Recording resources to read. + :param conference_sid: The Conference SID that identifies the conference associated with the recording to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "conference_sid": conference_sid, + } + self._uri = "/Accounts/{account_sid}/Conferences/{conference_sid}/Recordings.json".format( + **self._solution + ) + + def stream( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RecordingInstance]: + """ + Streams RecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RecordingInstance]: + """ + Asynchronously streams RecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordingInstance]: + """ + Lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordingInstance]: + """ + Asynchronously lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordingPage: + """ + Retrieve a single page of RecordingInstance records from the API. + Request is executed immediately + + :param date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordingInstance + """ + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response, self._solution) + + async def page_async( + self, + date_created: Union[date, object] = values.unset, + date_created_before: Union[date, object] = values.unset, + date_created_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordingPage: + """ + Asynchronously retrieve a single page of RecordingInstance records from the API. + Request is executed immediately + + :param date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. You can also specify inequality: `DateCreated<=YYYY-MM-DD` will return recordings generated at or before midnight on a given date, and `DateCreated>=YYYY-MM-DD` returns recordings generated at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordingInstance + """ + data = values.of( + { + "DateCreated": serialize.iso8601_date(date_created), + "DateCreated<": serialize.iso8601_date(date_created_before), + "DateCreated>": serialize.iso8601_date(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RecordingPage: + """ + Retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RecordingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RecordingPage: + """ + Asynchronously retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RecordingPage(self._version, response, self._solution) + + def get(self, sid: str) -> RecordingContext: + """ + Constructs a RecordingContext + + :param sid: The Twilio-provided string that uniquely identifies the Conference Recording resource to update. Use `Twilio.CURRENT` to reference the current active recording. + """ + return RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> RecordingContext: + """ + Constructs a RecordingContext + + :param sid: The Twilio-provided string that uniquely identifies the Conference Recording resource to update. Use `Twilio.CURRENT` to reference the current active recording. + """ + return RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.RecordingList>" diff --git a/twilio/rest/api/v2010/account/connect_app.py b/twilio/rest/api/v2010/account/connect_app.py new file mode 100644 index 0000000000..689a2b184a --- /dev/null +++ b/twilio/rest/api/v2010/account/connect_app.py @@ -0,0 +1,690 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ConnectAppInstance(InstanceResource): + + class Permission(object): + GET_ALL = "get-all" + POST_ALL = "post-all" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ConnectApp resource. + :ivar authorize_redirect_url: The URL we redirect the user to after we authenticate the user and obtain authorization to access the Connect App. + :ivar company_name: The company name set for the Connect App. + :ivar deauthorize_callback_method: The HTTP method we use to call `deauthorize_callback_url`. + :ivar deauthorize_callback_url: The URL we call using the `deauthorize_callback_method` to de-authorize the Connect App. + :ivar description: The description of the Connect App. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar homepage_url: The public URL where users can obtain more information about this Connect App. + :ivar permissions: The set of permissions that your ConnectApp requests. + :ivar sid: The unique string that that we created to identify the ConnectApp resource. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.authorize_redirect_url: Optional[str] = payload.get( + "authorize_redirect_url" + ) + self.company_name: Optional[str] = payload.get("company_name") + self.deauthorize_callback_method: Optional[str] = payload.get( + "deauthorize_callback_method" + ) + self.deauthorize_callback_url: Optional[str] = payload.get( + "deauthorize_callback_url" + ) + self.description: Optional[str] = payload.get("description") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.homepage_url: Optional[str] = payload.get("homepage_url") + self.permissions: Optional[List["ConnectAppInstance.Permission"]] = payload.get( + "permissions" + ) + self.sid: Optional[str] = payload.get("sid") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[ConnectAppContext] = None + + @property + def _proxy(self) -> "ConnectAppContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConnectAppContext for this ConnectAppInstance + """ + if self._context is None: + self._context = ConnectAppContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ConnectAppInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConnectAppInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ConnectAppInstance": + """ + Fetch the ConnectAppInstance + + + :returns: The fetched ConnectAppInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConnectAppInstance": + """ + Asynchronous coroutine to fetch the ConnectAppInstance + + + :returns: The fetched ConnectAppInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + authorize_redirect_url: Union[str, object] = values.unset, + company_name: Union[str, object] = values.unset, + deauthorize_callback_method: Union[str, object] = values.unset, + deauthorize_callback_url: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + homepage_url: Union[str, object] = values.unset, + permissions: Union[ + List["ConnectAppInstance.Permission"], object + ] = values.unset, + ) -> "ConnectAppInstance": + """ + Update the ConnectAppInstance + + :param authorize_redirect_url: The URL to redirect the user to after we authenticate the user and obtain authorization to access the Connect App. + :param company_name: The company name to set for the Connect App. + :param deauthorize_callback_method: The HTTP method to use when calling `deauthorize_callback_url`. + :param deauthorize_callback_url: The URL to call using the `deauthorize_callback_method` to de-authorize the Connect App. + :param description: A description of the Connect App. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param homepage_url: A public URL where users can obtain more information about this Connect App. + :param permissions: A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. + + :returns: The updated ConnectAppInstance + """ + return self._proxy.update( + authorize_redirect_url=authorize_redirect_url, + company_name=company_name, + deauthorize_callback_method=deauthorize_callback_method, + deauthorize_callback_url=deauthorize_callback_url, + description=description, + friendly_name=friendly_name, + homepage_url=homepage_url, + permissions=permissions, + ) + + async def update_async( + self, + authorize_redirect_url: Union[str, object] = values.unset, + company_name: Union[str, object] = values.unset, + deauthorize_callback_method: Union[str, object] = values.unset, + deauthorize_callback_url: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + homepage_url: Union[str, object] = values.unset, + permissions: Union[ + List["ConnectAppInstance.Permission"], object + ] = values.unset, + ) -> "ConnectAppInstance": + """ + Asynchronous coroutine to update the ConnectAppInstance + + :param authorize_redirect_url: The URL to redirect the user to after we authenticate the user and obtain authorization to access the Connect App. + :param company_name: The company name to set for the Connect App. + :param deauthorize_callback_method: The HTTP method to use when calling `deauthorize_callback_url`. + :param deauthorize_callback_url: The URL to call using the `deauthorize_callback_method` to de-authorize the Connect App. + :param description: A description of the Connect App. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param homepage_url: A public URL where users can obtain more information about this Connect App. + :param permissions: A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. + + :returns: The updated ConnectAppInstance + """ + return await self._proxy.update_async( + authorize_redirect_url=authorize_redirect_url, + company_name=company_name, + deauthorize_callback_method=deauthorize_callback_method, + deauthorize_callback_url=deauthorize_callback_url, + description=description, + friendly_name=friendly_name, + homepage_url=homepage_url, + permissions=permissions, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.ConnectAppInstance {}>".format(context) + + +class ConnectAppContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the ConnectAppContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ConnectApp resources to update. + :param sid: The Twilio-provided string that uniquely identifies the ConnectApp resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/ConnectApps/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the ConnectAppInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConnectAppInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConnectAppInstance: + """ + Fetch the ConnectAppInstance + + + :returns: The fetched ConnectAppInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ConnectAppInstance: + """ + Asynchronous coroutine to fetch the ConnectAppInstance + + + :returns: The fetched ConnectAppInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + authorize_redirect_url: Union[str, object] = values.unset, + company_name: Union[str, object] = values.unset, + deauthorize_callback_method: Union[str, object] = values.unset, + deauthorize_callback_url: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + homepage_url: Union[str, object] = values.unset, + permissions: Union[ + List["ConnectAppInstance.Permission"], object + ] = values.unset, + ) -> ConnectAppInstance: + """ + Update the ConnectAppInstance + + :param authorize_redirect_url: The URL to redirect the user to after we authenticate the user and obtain authorization to access the Connect App. + :param company_name: The company name to set for the Connect App. + :param deauthorize_callback_method: The HTTP method to use when calling `deauthorize_callback_url`. + :param deauthorize_callback_url: The URL to call using the `deauthorize_callback_method` to de-authorize the Connect App. + :param description: A description of the Connect App. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param homepage_url: A public URL where users can obtain more information about this Connect App. + :param permissions: A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. + + :returns: The updated ConnectAppInstance + """ + + data = values.of( + { + "AuthorizeRedirectUrl": authorize_redirect_url, + "CompanyName": company_name, + "DeauthorizeCallbackMethod": deauthorize_callback_method, + "DeauthorizeCallbackUrl": deauthorize_callback_url, + "Description": description, + "FriendlyName": friendly_name, + "HomepageUrl": homepage_url, + "Permissions": serialize.map(permissions, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + authorize_redirect_url: Union[str, object] = values.unset, + company_name: Union[str, object] = values.unset, + deauthorize_callback_method: Union[str, object] = values.unset, + deauthorize_callback_url: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + homepage_url: Union[str, object] = values.unset, + permissions: Union[ + List["ConnectAppInstance.Permission"], object + ] = values.unset, + ) -> ConnectAppInstance: + """ + Asynchronous coroutine to update the ConnectAppInstance + + :param authorize_redirect_url: The URL to redirect the user to after we authenticate the user and obtain authorization to access the Connect App. + :param company_name: The company name to set for the Connect App. + :param deauthorize_callback_method: The HTTP method to use when calling `deauthorize_callback_url`. + :param deauthorize_callback_url: The URL to call using the `deauthorize_callback_method` to de-authorize the Connect App. + :param description: A description of the Connect App. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param homepage_url: A public URL where users can obtain more information about this Connect App. + :param permissions: A comma-separated list of the permissions you will request from the users of this ConnectApp. Can include: `get-all` and `post-all`. + + :returns: The updated ConnectAppInstance + """ + + data = values.of( + { + "AuthorizeRedirectUrl": authorize_redirect_url, + "CompanyName": company_name, + "DeauthorizeCallbackMethod": deauthorize_callback_method, + "DeauthorizeCallbackUrl": deauthorize_callback_url, + "Description": description, + "FriendlyName": friendly_name, + "HomepageUrl": homepage_url, + "Permissions": serialize.map(permissions, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.ConnectAppContext {}>".format(context) + + +class ConnectAppPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConnectAppInstance: + """ + Build an instance of ConnectAppInstance + + :param payload: Payload response from the API + """ + return ConnectAppInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.ConnectAppPage>" + + +class ConnectAppList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the ConnectAppList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ConnectApp resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/ConnectApps.json".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConnectAppInstance]: + """ + Streams ConnectAppInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConnectAppInstance]: + """ + Asynchronously streams ConnectAppInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConnectAppInstance]: + """ + Lists ConnectAppInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConnectAppInstance]: + """ + Asynchronously lists ConnectAppInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConnectAppPage: + """ + Retrieve a single page of ConnectAppInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConnectAppInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConnectAppPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConnectAppPage: + """ + Asynchronously retrieve a single page of ConnectAppInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConnectAppInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConnectAppPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ConnectAppPage: + """ + Retrieve a specific page of ConnectAppInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConnectAppInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConnectAppPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ConnectAppPage: + """ + Asynchronously retrieve a specific page of ConnectAppInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConnectAppInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConnectAppPage(self._version, response, self._solution) + + def get(self, sid: str) -> ConnectAppContext: + """ + Constructs a ConnectAppContext + + :param sid: The Twilio-provided string that uniquely identifies the ConnectApp resource to update. + """ + return ConnectAppContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ConnectAppContext: + """ + Constructs a ConnectAppContext + + :param sid: The Twilio-provided string that uniquely identifies the ConnectApp resource to update. + """ + return ConnectAppContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.ConnectAppList>" diff --git a/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py b/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py new file mode 100644 index 0000000000..c7c1eebcfd --- /dev/null +++ b/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py @@ -0,0 +1,1310 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on import ( + AssignedAddOnList, +) +from twilio.rest.api.v2010.account.incoming_phone_number.local import LocalList +from twilio.rest.api.v2010.account.incoming_phone_number.mobile import MobileList +from twilio.rest.api.v2010.account.incoming_phone_number.toll_free import TollFreeList + + +class IncomingPhoneNumberInstance(InstanceResource): + + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" + + class EmergencyAddressStatus(object): + REGISTERED = "registered" + UNREGISTERED = "unregistered" + PENDING_REGISTRATION = "pending-registration" + REGISTRATION_FAILURE = "registration-failure" + PENDING_UNREGISTRATION = "pending-unregistration" + UNREGISTRATION_FAILURE = "unregistration-failure" + + class EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" + + class VoiceReceiveMode(object): + VOICE = "voice" + FAX = "fax" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this IncomingPhoneNumber resource. + :ivar address_sid: The SID of the Address resource associated with the phone number. + :ivar address_requirements: + :ivar api_version: The API version used to start a new TwiML session. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar identity_sid: The SID of the Identity resource that we associate with the phone number. Some regions require an Identity to meet local regulations. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar origin: The phone number's origin. `twilio` identifies Twilio-owned phone numbers and `hosted` identifies hosted phone numbers. + :ivar sid: The unique string that that we created to identify this IncomingPhoneNumber resource. + :ivar sms_application_sid: The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :ivar sms_fallback_method: The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :ivar sms_fallback_url: The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :ivar sms_method: The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + :ivar sms_url: The URL we call when the phone number receives an incoming SMS message. + :ivar status_callback: The URL we call using the `status_callback_method` to send status information to your application. + :ivar status_callback_method: The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + :ivar trunk_sid: The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar voice_receive_mode: + :ivar voice_application_sid: The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :ivar voice_caller_id_lookup: Whether we look up the caller's caller-ID name from the CNAM database ($0.01 per look up). Can be: `true` or `false`. + :ivar voice_fallback_method: The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_url: The URL we call when the phone number receives a call. The `voice_url` will not be used if a `voice_application_sid` or a `trunk_sid` is set. + :ivar emergency_status: + :ivar emergency_address_sid: The SID of the emergency address configuration that we use for emergency calling from this phone number. + :ivar emergency_address_status: + :ivar bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + :ivar status: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.address_sid: Optional[str] = payload.get("address_sid") + self.address_requirements: Optional[ + "IncomingPhoneNumberInstance.AddressRequirement" + ] = payload.get("address_requirements") + self.api_version: Optional[str] = payload.get("api_version") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.identity_sid: Optional[str] = payload.get("identity_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.origin: Optional[str] = payload.get("origin") + self.sid: Optional[str] = payload.get("sid") + self.sms_application_sid: Optional[str] = payload.get("sms_application_sid") + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_url: Optional[str] = payload.get("sms_url") + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.uri: Optional[str] = payload.get("uri") + self.voice_receive_mode: Optional[ + "IncomingPhoneNumberInstance.VoiceReceiveMode" + ] = payload.get("voice_receive_mode") + self.voice_application_sid: Optional[str] = payload.get("voice_application_sid") + self.voice_caller_id_lookup: Optional[bool] = payload.get( + "voice_caller_id_lookup" + ) + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_url: Optional[str] = payload.get("voice_url") + self.emergency_status: Optional[ + "IncomingPhoneNumberInstance.EmergencyStatus" + ] = payload.get("emergency_status") + self.emergency_address_sid: Optional[str] = payload.get("emergency_address_sid") + self.emergency_address_status: Optional[ + "IncomingPhoneNumberInstance.EmergencyAddressStatus" + ] = payload.get("emergency_address_status") + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.status: Optional[str] = payload.get("status") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[IncomingPhoneNumberContext] = None + + @property + def _proxy(self) -> "IncomingPhoneNumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: IncomingPhoneNumberContext for this IncomingPhoneNumberInstance + """ + if self._context is None: + self._context = IncomingPhoneNumberContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the IncomingPhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IncomingPhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "IncomingPhoneNumberInstance": + """ + Fetch the IncomingPhoneNumberInstance + + + :returns: The fetched IncomingPhoneNumberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "IncomingPhoneNumberInstance": + """ + Asynchronous coroutine to fetch the IncomingPhoneNumberInstance + + + :returns: The fetched IncomingPhoneNumberInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + account_sid: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> "IncomingPhoneNumberInstance": + """ + Update the IncomingPhoneNumberInstance + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). + :param api_version: The API version to use for incoming calls made to the phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe this phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle phone calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from this phone number. + :param trunk_sid: The SID of the Trunk we should use to handle phone calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param identity_sid: The SID of the Identity resource that we should associate with the phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the phone number. Some regions require addresses to meet local regulations. + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The updated IncomingPhoneNumberInstance + """ + return self._proxy.update( + account_sid=account_sid, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + identity_sid=identity_sid, + address_sid=address_sid, + bundle_sid=bundle_sid, + ) + + async def update_async( + self, + account_sid: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> "IncomingPhoneNumberInstance": + """ + Asynchronous coroutine to update the IncomingPhoneNumberInstance + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). + :param api_version: The API version to use for incoming calls made to the phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe this phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle phone calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from this phone number. + :param trunk_sid: The SID of the Trunk we should use to handle phone calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param identity_sid: The SID of the Identity resource that we should associate with the phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the phone number. Some regions require addresses to meet local regulations. + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The updated IncomingPhoneNumberInstance + """ + return await self._proxy.update_async( + account_sid=account_sid, + api_version=api_version, + friendly_name=friendly_name, + sms_application_sid=sms_application_sid, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + status_callback=status_callback, + status_callback_method=status_callback_method, + voice_application_sid=voice_application_sid, + voice_caller_id_lookup=voice_caller_id_lookup, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + emergency_status=emergency_status, + emergency_address_sid=emergency_address_sid, + trunk_sid=trunk_sid, + voice_receive_mode=voice_receive_mode, + identity_sid=identity_sid, + address_sid=address_sid, + bundle_sid=bundle_sid, + ) + + @property + def assigned_add_ons(self) -> AssignedAddOnList: + """ + Access the assigned_add_ons + """ + return self._proxy.assigned_add_ons + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.IncomingPhoneNumberInstance {}>".format(context) + + +class IncomingPhoneNumberContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the IncomingPhoneNumberContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). + :param sid: The Twilio-provided string that uniquely identifies the IncomingPhoneNumber resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/{sid}.json".format( + **self._solution + ) + + self._assigned_add_ons: Optional[AssignedAddOnList] = None + + def delete(self) -> bool: + """ + Deletes the IncomingPhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IncomingPhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> IncomingPhoneNumberInstance: + """ + Fetch the IncomingPhoneNumberInstance + + + :returns: The fetched IncomingPhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> IncomingPhoneNumberInstance: + """ + Asynchronous coroutine to fetch the IncomingPhoneNumberInstance + + + :returns: The fetched IncomingPhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + account_sid: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> IncomingPhoneNumberInstance: + """ + Update the IncomingPhoneNumberInstance + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). + :param api_version: The API version to use for incoming calls made to the phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe this phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle phone calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from this phone number. + :param trunk_sid: The SID of the Trunk we should use to handle phone calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param identity_sid: The SID of the Identity resource that we should associate with the phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the phone number. Some regions require addresses to meet local regulations. + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The updated IncomingPhoneNumberInstance + """ + + data = values.of( + { + "AccountSid": account_sid, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "BundleSid": bundle_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + account_sid: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> IncomingPhoneNumberInstance: + """ + Asynchronous coroutine to update the IncomingPhoneNumberInstance + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). + :param api_version: The API version to use for incoming calls made to the phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe this phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle phone calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from this phone number. + :param trunk_sid: The SID of the Trunk we should use to handle phone calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param identity_sid: The SID of the Identity resource that we should associate with the phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the phone number. Some regions require addresses to meet local regulations. + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The updated IncomingPhoneNumberInstance + """ + + data = values.of( + { + "AccountSid": account_sid, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "BundleSid": bundle_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def assigned_add_ons(self) -> AssignedAddOnList: + """ + Access the assigned_add_ons + """ + if self._assigned_add_ons is None: + self._assigned_add_ons = AssignedAddOnList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._assigned_add_ons + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.IncomingPhoneNumberContext {}>".format(context) + + +class IncomingPhoneNumberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> IncomingPhoneNumberInstance: + """ + Build an instance of IncomingPhoneNumberInstance + + :param payload: Payload response from the API + """ + return IncomingPhoneNumberInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.IncomingPhoneNumberPage>" + + +class IncomingPhoneNumberList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the IncomingPhoneNumberList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IncomingPhoneNumber resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers.json".format( + **self._solution + ) + + self._local: Optional[LocalList] = None + self._mobile: Optional[MobileList] = None + self._toll_free: Optional[TollFreeList] = None + + def create( + self, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + area_code: Union[str, object] = values.unset, + ) -> IncomingPhoneNumberInstance: + """ + Create the IncomingPhoneNumberInstance + + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the new phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param area_code: The desired area code for your new incoming phone number. Can be any three-digit, US or Canada area code. We will provision an available phone number within this area code for you. **You must provide an `area_code` or a `phone_number`.** (US and Canada only). + + :returns: The created IncomingPhoneNumberInstance + """ + + data = values.of( + { + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + "PhoneNumber": phone_number, + "AreaCode": area_code, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IncomingPhoneNumberInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + emergency_status: Union[ + "IncomingPhoneNumberInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "IncomingPhoneNumberInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + area_code: Union[str, object] = values.unset, + ) -> IncomingPhoneNumberInstance: + """ + Asynchronously create the IncomingPhoneNumberInstance + + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the new phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param area_code: The desired area code for your new incoming phone number. Can be any three-digit, US or Canada area code. We will provision an available phone number within this area code for you. **You must provide an `area_code` or a `phone_number`.** (US and Canada only). + + :returns: The created IncomingPhoneNumberInstance + """ + + data = values.of( + { + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + "PhoneNumber": phone_number, + "AreaCode": area_code, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IncomingPhoneNumberInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[IncomingPhoneNumberInstance]: + """ + Streams IncomingPhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IncomingPhoneNumberInstance]: + """ + Asynchronously streams IncomingPhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IncomingPhoneNumberInstance]: + """ + Lists IncomingPhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IncomingPhoneNumberInstance]: + """ + Asynchronously lists IncomingPhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IncomingPhoneNumberPage: + """ + Retrieve a single page of IncomingPhoneNumberInstance records from the API. + Request is executed immediately + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IncomingPhoneNumberInstance + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IncomingPhoneNumberPage(self._version, response, self._solution) + + async def page_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IncomingPhoneNumberPage: + """ + Asynchronously retrieve a single page of IncomingPhoneNumberInstance records from the API. + Request is executed immediately + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the IncomingPhoneNumber resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IncomingPhoneNumberInstance + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IncomingPhoneNumberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> IncomingPhoneNumberPage: + """ + Retrieve a specific page of IncomingPhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IncomingPhoneNumberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return IncomingPhoneNumberPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> IncomingPhoneNumberPage: + """ + Asynchronously retrieve a specific page of IncomingPhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IncomingPhoneNumberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return IncomingPhoneNumberPage(self._version, response, self._solution) + + @property + def local(self) -> LocalList: + """ + Access the local + """ + if self._local is None: + self._local = LocalList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._local + + @property + def mobile(self) -> MobileList: + """ + Access the mobile + """ + if self._mobile is None: + self._mobile = MobileList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._mobile + + @property + def toll_free(self) -> TollFreeList: + """ + Access the toll_free + """ + if self._toll_free is None: + self._toll_free = TollFreeList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._toll_free + + def get(self, sid: str) -> IncomingPhoneNumberContext: + """ + Constructs a IncomingPhoneNumberContext + + :param sid: The Twilio-provided string that uniquely identifies the IncomingPhoneNumber resource to update. + """ + return IncomingPhoneNumberContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> IncomingPhoneNumberContext: + """ + Constructs a IncomingPhoneNumberContext + + :param sid: The Twilio-provided string that uniquely identifies the IncomingPhoneNumber resource to update. + """ + return IncomingPhoneNumberContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.IncomingPhoneNumberList>" diff --git a/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__init__.py b/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__init__.py new file mode 100644 index 0000000000..52fe2a52af --- /dev/null +++ b/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/__init__.py @@ -0,0 +1,602 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension import ( + AssignedAddOnExtensionList, +) + + +class AssignedAddOnInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource. + :ivar resource_sid: The SID of the Phone Number to which the Add-on is assigned. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar description: A short description of the functionality that the Add-on provides. + :ivar configuration: A JSON string that represents the current configuration of this Add-on installation. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar subresource_uris: A list of related resources identified by their relative URIs. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + resource_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.resource_sid: Optional[str] = payload.get("resource_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.unique_name: Optional[str] = payload.get("unique_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.uri: Optional[str] = payload.get("uri") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + + self._solution = { + "account_sid": account_sid, + "resource_sid": resource_sid, + "sid": sid or self.sid, + } + self._context: Optional[AssignedAddOnContext] = None + + @property + def _proxy(self) -> "AssignedAddOnContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AssignedAddOnContext for this AssignedAddOnInstance + """ + if self._context is None: + self._context = AssignedAddOnContext( + self._version, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AssignedAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssignedAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AssignedAddOnInstance": + """ + Fetch the AssignedAddOnInstance + + + :returns: The fetched AssignedAddOnInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AssignedAddOnInstance": + """ + Asynchronous coroutine to fetch the AssignedAddOnInstance + + + :returns: The fetched AssignedAddOnInstance + """ + return await self._proxy.fetch_async() + + @property + def extensions(self) -> AssignedAddOnExtensionList: + """ + Access the extensions + """ + return self._proxy.extensions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.AssignedAddOnInstance {}>".format(context) + + +class AssignedAddOnContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, resource_sid: str, sid: str): + """ + Initialize the AssignedAddOnContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource to fetch. + :param resource_sid: The SID of the Phone Number to which the Add-on is assigned. + :param sid: The Twilio-provided string that uniquely identifies the resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "resource_sid": resource_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/{resource_sid}/AssignedAddOns/{sid}.json".format( + **self._solution + ) + + self._extensions: Optional[AssignedAddOnExtensionList] = None + + def delete(self) -> bool: + """ + Deletes the AssignedAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssignedAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AssignedAddOnInstance: + """ + Fetch the AssignedAddOnInstance + + + :returns: The fetched AssignedAddOnInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AssignedAddOnInstance: + """ + Asynchronous coroutine to fetch the AssignedAddOnInstance + + + :returns: The fetched AssignedAddOnInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + sid=self._solution["sid"], + ) + + @property + def extensions(self) -> AssignedAddOnExtensionList: + """ + Access the extensions + """ + if self._extensions is None: + self._extensions = AssignedAddOnExtensionList( + self._version, + self._solution["account_sid"], + self._solution["resource_sid"], + self._solution["sid"], + ) + return self._extensions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.AssignedAddOnContext {}>".format(context) + + +class AssignedAddOnPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AssignedAddOnInstance: + """ + Build an instance of AssignedAddOnInstance + + :param payload: Payload response from the API + """ + return AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AssignedAddOnPage>" + + +class AssignedAddOnList(ListResource): + + def __init__(self, version: Version, account_sid: str, resource_sid: str): + """ + Initialize the AssignedAddOnList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resources to read. + :param resource_sid: The SID of the Phone Number to which the Add-on is assigned. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "resource_sid": resource_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/{resource_sid}/AssignedAddOns.json".format( + **self._solution + ) + + def create(self, installed_add_on_sid: str) -> AssignedAddOnInstance: + """ + Create the AssignedAddOnInstance + + :param installed_add_on_sid: The SID that identifies the Add-on installation. + + :returns: The created AssignedAddOnInstance + """ + + data = values.of( + { + "InstalledAddOnSid": installed_add_on_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + ) + + async def create_async(self, installed_add_on_sid: str) -> AssignedAddOnInstance: + """ + Asynchronously create the AssignedAddOnInstance + + :param installed_add_on_sid: The SID that identifies the Add-on installation. + + :returns: The created AssignedAddOnInstance + """ + + data = values.of( + { + "InstalledAddOnSid": installed_add_on_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssignedAddOnInstance]: + """ + Streams AssignedAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AssignedAddOnInstance]: + """ + Asynchronously streams AssignedAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssignedAddOnInstance]: + """ + Lists AssignedAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssignedAddOnInstance]: + """ + Asynchronously lists AssignedAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssignedAddOnPage: + """ + Retrieve a single page of AssignedAddOnInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssignedAddOnInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssignedAddOnPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssignedAddOnPage: + """ + Asynchronously retrieve a single page of AssignedAddOnInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssignedAddOnInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssignedAddOnPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AssignedAddOnPage: + """ + Retrieve a specific page of AssignedAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssignedAddOnInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AssignedAddOnPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AssignedAddOnPage: + """ + Asynchronously retrieve a specific page of AssignedAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssignedAddOnInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssignedAddOnPage(self._version, response, self._solution) + + def get(self, sid: str) -> AssignedAddOnContext: + """ + Constructs a AssignedAddOnContext + + :param sid: The Twilio-provided string that uniquely identifies the resource to fetch. + """ + return AssignedAddOnContext( + self._version, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AssignedAddOnContext: + """ + Constructs a AssignedAddOnContext + + :param sid: The Twilio-provided string that uniquely identifies the resource to fetch. + """ + return AssignedAddOnContext( + self._version, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AssignedAddOnList>" diff --git a/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/assigned_add_on_extension.py b/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/assigned_add_on_extension.py new file mode 100644 index 0000000000..1a7d9cdc34 --- /dev/null +++ b/twilio/rest/api/v2010/account/incoming_phone_number/assigned_add_on/assigned_add_on_extension.py @@ -0,0 +1,484 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AssignedAddOnExtensionInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource. + :ivar resource_sid: The SID of the Phone Number to which the Add-on is assigned. + :ivar assigned_add_on_sid: The SID that uniquely identifies the assigned Add-on installation. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar product_name: A string that you assigned to describe the Product this Extension is used within. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar enabled: Whether the Extension will be invoked. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + resource_sid: str, + assigned_add_on_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.resource_sid: Optional[str] = payload.get("resource_sid") + self.assigned_add_on_sid: Optional[str] = payload.get("assigned_add_on_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.product_name: Optional[str] = payload.get("product_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.uri: Optional[str] = payload.get("uri") + self.enabled: Optional[bool] = payload.get("enabled") + + self._solution = { + "account_sid": account_sid, + "resource_sid": resource_sid, + "assigned_add_on_sid": assigned_add_on_sid, + "sid": sid or self.sid, + } + self._context: Optional[AssignedAddOnExtensionContext] = None + + @property + def _proxy(self) -> "AssignedAddOnExtensionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AssignedAddOnExtensionContext for this AssignedAddOnExtensionInstance + """ + if self._context is None: + self._context = AssignedAddOnExtensionContext( + self._version, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + assigned_add_on_sid=self._solution["assigned_add_on_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AssignedAddOnExtensionInstance": + """ + Fetch the AssignedAddOnExtensionInstance + + + :returns: The fetched AssignedAddOnExtensionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AssignedAddOnExtensionInstance": + """ + Asynchronous coroutine to fetch the AssignedAddOnExtensionInstance + + + :returns: The fetched AssignedAddOnExtensionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.AssignedAddOnExtensionInstance {}>".format(context) + + +class AssignedAddOnExtensionContext(InstanceContext): + + def __init__( + self, + version: Version, + account_sid: str, + resource_sid: str, + assigned_add_on_sid: str, + sid: str, + ): + """ + Initialize the AssignedAddOnExtensionContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource to fetch. + :param resource_sid: The SID of the Phone Number to which the Add-on is assigned. + :param assigned_add_on_sid: The SID that uniquely identifies the assigned Add-on installation. + :param sid: The Twilio-provided string that uniquely identifies the resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "resource_sid": resource_sid, + "assigned_add_on_sid": assigned_add_on_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/{resource_sid}/AssignedAddOns/{assigned_add_on_sid}/Extensions/{sid}.json".format( + **self._solution + ) + + def fetch(self) -> AssignedAddOnExtensionInstance: + """ + Fetch the AssignedAddOnExtensionInstance + + + :returns: The fetched AssignedAddOnExtensionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AssignedAddOnExtensionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + assigned_add_on_sid=self._solution["assigned_add_on_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AssignedAddOnExtensionInstance: + """ + Asynchronous coroutine to fetch the AssignedAddOnExtensionInstance + + + :returns: The fetched AssignedAddOnExtensionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AssignedAddOnExtensionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + assigned_add_on_sid=self._solution["assigned_add_on_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.AssignedAddOnExtensionContext {}>".format(context) + + +class AssignedAddOnExtensionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AssignedAddOnExtensionInstance: + """ + Build an instance of AssignedAddOnExtensionInstance + + :param payload: Payload response from the API + """ + return AssignedAddOnExtensionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + assigned_add_on_sid=self._solution["assigned_add_on_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AssignedAddOnExtensionPage>" + + +class AssignedAddOnExtensionList(ListResource): + + def __init__( + self, + version: Version, + account_sid: str, + resource_sid: str, + assigned_add_on_sid: str, + ): + """ + Initialize the AssignedAddOnExtensionList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resources to read. + :param resource_sid: The SID of the Phone Number to which the Add-on is assigned. + :param assigned_add_on_sid: The SID that uniquely identifies the assigned Add-on installation. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "resource_sid": resource_sid, + "assigned_add_on_sid": assigned_add_on_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/{resource_sid}/AssignedAddOns/{assigned_add_on_sid}/Extensions.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssignedAddOnExtensionInstance]: + """ + Streams AssignedAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AssignedAddOnExtensionInstance]: + """ + Asynchronously streams AssignedAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssignedAddOnExtensionInstance]: + """ + Lists AssignedAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssignedAddOnExtensionInstance]: + """ + Asynchronously lists AssignedAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssignedAddOnExtensionPage: + """ + Retrieve a single page of AssignedAddOnExtensionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssignedAddOnExtensionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssignedAddOnExtensionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssignedAddOnExtensionPage: + """ + Asynchronously retrieve a single page of AssignedAddOnExtensionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssignedAddOnExtensionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssignedAddOnExtensionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AssignedAddOnExtensionPage: + """ + Retrieve a specific page of AssignedAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssignedAddOnExtensionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AssignedAddOnExtensionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AssignedAddOnExtensionPage: + """ + Asynchronously retrieve a specific page of AssignedAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssignedAddOnExtensionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssignedAddOnExtensionPage(self._version, response, self._solution) + + def get(self, sid: str) -> AssignedAddOnExtensionContext: + """ + Constructs a AssignedAddOnExtensionContext + + :param sid: The Twilio-provided string that uniquely identifies the resource to fetch. + """ + return AssignedAddOnExtensionContext( + self._version, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + assigned_add_on_sid=self._solution["assigned_add_on_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AssignedAddOnExtensionContext: + """ + Constructs a AssignedAddOnExtensionContext + + :param sid: The Twilio-provided string that uniquely identifies the resource to fetch. + """ + return AssignedAddOnExtensionContext( + self._version, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + assigned_add_on_sid=self._solution["assigned_add_on_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AssignedAddOnExtensionList>" diff --git a/twilio/rest/api/v2010/account/incoming_phone_number/local.py b/twilio/rest/api/v2010/account/incoming_phone_number/local.py new file mode 100644 index 0000000000..af67fb0a2d --- /dev/null +++ b/twilio/rest/api/v2010/account/incoming_phone_number/local.py @@ -0,0 +1,672 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class LocalInstance(InstanceResource): + + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" + + class EmergencyAddressStatus(object): + REGISTERED = "registered" + UNREGISTERED = "unregistered" + PENDING_REGISTRATION = "pending-registration" + REGISTRATION_FAILURE = "registration-failure" + PENDING_UNREGISTRATION = "pending-unregistration" + UNREGISTRATION_FAILURE = "unregistration-failure" + + class EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" + + class VoiceReceiveMode(object): + VOICE = "voice" + FAX = "fax" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource. + :ivar address_sid: The SID of the Address resource associated with the phone number. + :ivar address_requirements: + :ivar api_version: The API version used to start a new TwiML session. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar identity_sid: The SID of the Identity resource that we associate with the phone number. Some regions require an Identity to meet local regulations. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar origin: The phone number's origin. `twilio` identifies Twilio-owned phone numbers and `hosted` identifies hosted phone numbers. + :ivar sid: The unique string that that we created to identify the resource. + :ivar sms_application_sid: The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :ivar sms_fallback_method: The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :ivar sms_fallback_url: The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :ivar sms_method: The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + :ivar sms_url: The URL we call when the phone number receives an incoming SMS message. + :ivar status_callback: The URL we call using the `status_callback_method` to send status information to your application. + :ivar status_callback_method: The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + :ivar trunk_sid: The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar voice_receive_mode: + :ivar voice_application_sid: The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :ivar voice_caller_id_lookup: Whether we look up the caller's caller-ID name from the CNAM database ($0.01 per look up). Can be: `true` or `false`. + :ivar voice_fallback_method: The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_url: The URL we call when this phone number receives a call. The `voice_url` will not be used if a `voice_application_sid` or a `trunk_sid` is set. + :ivar emergency_status: + :ivar emergency_address_sid: The SID of the emergency address configuration that we use for emergency calling from this phone number. + :ivar emergency_address_status: + :ivar bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + :ivar status: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.address_sid: Optional[str] = payload.get("address_sid") + self.address_requirements: Optional["LocalInstance.AddressRequirement"] = ( + payload.get("address_requirements") + ) + self.api_version: Optional[str] = payload.get("api_version") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.identity_sid: Optional[str] = payload.get("identity_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.origin: Optional[str] = payload.get("origin") + self.sid: Optional[str] = payload.get("sid") + self.sms_application_sid: Optional[str] = payload.get("sms_application_sid") + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_url: Optional[str] = payload.get("sms_url") + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.uri: Optional[str] = payload.get("uri") + self.voice_receive_mode: Optional["LocalInstance.VoiceReceiveMode"] = ( + payload.get("voice_receive_mode") + ) + self.voice_application_sid: Optional[str] = payload.get("voice_application_sid") + self.voice_caller_id_lookup: Optional[bool] = payload.get( + "voice_caller_id_lookup" + ) + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_url: Optional[str] = payload.get("voice_url") + self.emergency_status: Optional["LocalInstance.EmergencyStatus"] = payload.get( + "emergency_status" + ) + self.emergency_address_sid: Optional[str] = payload.get("emergency_address_sid") + self.emergency_address_status: Optional[ + "LocalInstance.EmergencyAddressStatus" + ] = payload.get("emergency_address_status") + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.status: Optional[str] = payload.get("status") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.LocalInstance {}>".format(context) + + +class LocalPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> LocalInstance: + """ + Build an instance of LocalInstance + + :param payload: Payload response from the API + """ + return LocalInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.LocalPage>" + + +class LocalList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the LocalList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/Local.json".format( + **self._solution + ) + + def create( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union["LocalInstance.EmergencyStatus", object] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "LocalInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> LocalInstance: + """ + Create the LocalInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created LocalInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return LocalInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union["LocalInstance.EmergencyStatus", object] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "LocalInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> LocalInstance: + """ + Asynchronously create the LocalInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those set on the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created LocalInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return LocalInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[LocalInstance]: + """ + Streams LocalInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[LocalInstance]: + """ + Asynchronously streams LocalInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LocalInstance]: + """ + Lists LocalInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LocalInstance]: + """ + Asynchronously lists LocalInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LocalPage: + """ + Retrieve a single page of LocalInstance records from the API. + Request is executed immediately + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LocalInstance + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LocalPage(self._version, response, self._solution) + + async def page_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LocalPage: + """ + Asynchronously retrieve a single page of LocalInstance records from the API. + Request is executed immediately + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LocalInstance + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LocalPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> LocalPage: + """ + Retrieve a specific page of LocalInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of LocalInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return LocalPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> LocalPage: + """ + Asynchronously retrieve a specific page of LocalInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of LocalInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return LocalPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.LocalList>" diff --git a/twilio/rest/api/v2010/account/incoming_phone_number/mobile.py b/twilio/rest/api/v2010/account/incoming_phone_number/mobile.py new file mode 100644 index 0000000000..27fc8a0e9f --- /dev/null +++ b/twilio/rest/api/v2010/account/incoming_phone_number/mobile.py @@ -0,0 +1,676 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MobileInstance(InstanceResource): + + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" + + class EmergencyAddressStatus(object): + REGISTERED = "registered" + UNREGISTERED = "unregistered" + PENDING_REGISTRATION = "pending-registration" + REGISTRATION_FAILURE = "registration-failure" + PENDING_UNREGISTRATION = "pending-unregistration" + UNREGISTRATION_FAILURE = "unregistration-failure" + + class EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" + + class VoiceReceiveMode(object): + VOICE = "voice" + FAX = "fax" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource. + :ivar address_sid: The SID of the Address resource associated with the phone number. + :ivar address_requirements: + :ivar api_version: The API version used to start a new TwiML session. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar identity_sid: The SID of the Identity resource that we associate with the phone number. Some regions require an Identity to meet local regulations. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar origin: The phone number's origin. `twilio` identifies Twilio-owned phone numbers and `hosted` identifies hosted phone numbers. + :ivar sid: The unique string that that we created to identify the resource. + :ivar sms_application_sid: The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :ivar sms_fallback_method: The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :ivar sms_fallback_url: The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :ivar sms_method: The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + :ivar sms_url: The URL we call when the phone number receives an incoming SMS message. + :ivar status_callback: The URL we call using the `status_callback_method` to send status information to your application. + :ivar status_callback_method: The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + :ivar trunk_sid: The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar voice_receive_mode: + :ivar voice_application_sid: The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :ivar voice_caller_id_lookup: Whether we look up the caller's caller-ID name from the CNAM database ($0.01 per look up). Can be: `true` or `false`. + :ivar voice_fallback_method: The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_url: The URL we call when the phone number receives a call. The `voice_url` will not be used if a `voice_application_sid` or a `trunk_sid` is set. + :ivar emergency_status: + :ivar emergency_address_sid: The SID of the emergency address configuration that we use for emergency calling from this phone number. + :ivar emergency_address_status: + :ivar bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + :ivar status: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.address_sid: Optional[str] = payload.get("address_sid") + self.address_requirements: Optional["MobileInstance.AddressRequirement"] = ( + payload.get("address_requirements") + ) + self.api_version: Optional[str] = payload.get("api_version") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.identity_sid: Optional[str] = payload.get("identity_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.origin: Optional[str] = payload.get("origin") + self.sid: Optional[str] = payload.get("sid") + self.sms_application_sid: Optional[str] = payload.get("sms_application_sid") + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_url: Optional[str] = payload.get("sms_url") + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.uri: Optional[str] = payload.get("uri") + self.voice_receive_mode: Optional["MobileInstance.VoiceReceiveMode"] = ( + payload.get("voice_receive_mode") + ) + self.voice_application_sid: Optional[str] = payload.get("voice_application_sid") + self.voice_caller_id_lookup: Optional[bool] = payload.get( + "voice_caller_id_lookup" + ) + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_url: Optional[str] = payload.get("voice_url") + self.emergency_status: Optional["MobileInstance.EmergencyStatus"] = payload.get( + "emergency_status" + ) + self.emergency_address_sid: Optional[str] = payload.get("emergency_address_sid") + self.emergency_address_status: Optional[ + "MobileInstance.EmergencyAddressStatus" + ] = payload.get("emergency_address_status") + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.status: Optional[str] = payload.get("status") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.MobileInstance {}>".format(context) + + +class MobilePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MobileInstance: + """ + Build an instance of MobileInstance + + :param payload: Payload response from the API + """ + return MobileInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.MobilePage>" + + +class MobileList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the MobileList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/Mobile.json".format( + **self._solution + ) + + def create( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "MobileInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "MobileInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> MobileInstance: + """ + Create the MobileInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, the is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created MobileInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MobileInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "MobileInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "MobileInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> MobileInstance: + """ + Asynchronously create the MobileInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, the is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all of the `sms_*_url` urls and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use only those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created MobileInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MobileInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MobileInstance]: + """ + Streams MobileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MobileInstance]: + """ + Asynchronously streams MobileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MobileInstance]: + """ + Lists MobileInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MobileInstance]: + """ + Asynchronously lists MobileInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MobilePage: + """ + Retrieve a single page of MobileInstance records from the API. + Request is executed immediately + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MobileInstance + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MobilePage(self._version, response, self._solution) + + async def page_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MobilePage: + """ + Asynchronously retrieve a single page of MobileInstance records from the API. + Request is executed immediately + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MobileInstance + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MobilePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MobilePage: + """ + Retrieve a specific page of MobileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MobileInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MobilePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MobilePage: + """ + Asynchronously retrieve a specific page of MobileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MobileInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MobilePage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.MobileList>" diff --git a/twilio/rest/api/v2010/account/incoming_phone_number/toll_free.py b/twilio/rest/api/v2010/account/incoming_phone_number/toll_free.py new file mode 100644 index 0000000000..86290ff9b2 --- /dev/null +++ b/twilio/rest/api/v2010/account/incoming_phone_number/toll_free.py @@ -0,0 +1,676 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TollFreeInstance(InstanceResource): + + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" + + class EmergencyAddressStatus(object): + REGISTERED = "registered" + UNREGISTERED = "unregistered" + PENDING_REGISTRATION = "pending-registration" + REGISTRATION_FAILURE = "registration-failure" + PENDING_UNREGISTRATION = "pending-unregistration" + UNREGISTRATION_FAILURE = "unregistration-failure" + + class EmergencyStatus(object): + ACTIVE = "Active" + INACTIVE = "Inactive" + + class VoiceReceiveMode(object): + VOICE = "voice" + FAX = "fax" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource. + :ivar address_sid: The SID of the Address resource associated with the phone number. + :ivar address_requirements: + :ivar api_version: The API version used to start a new TwiML session. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar identity_sid: The SID of the Identity resource that we associate with the phone number. Some regions require an Identity to meet local regulations. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar origin: The phone number's origin. `twilio` identifies Twilio-owned phone numbers and `hosted` identifies hosted phone numbers. + :ivar sid: The unique string that that we created to identify the resource. + :ivar sms_application_sid: The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :ivar sms_fallback_method: The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :ivar sms_fallback_url: The URL that we call when an error occurs while retrieving or executing the TwiML from `sms_url`. + :ivar sms_method: The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + :ivar sms_url: The URL we call when the phone number receives an incoming SMS message. + :ivar status_callback: The URL we call using the `status_callback_method` to send status information to your application. + :ivar status_callback_method: The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + :ivar trunk_sid: The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar voice_receive_mode: + :ivar voice_application_sid: The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :ivar voice_caller_id_lookup: Whether we look up the caller's caller-ID name from the CNAM database ($0.01 per look up). Can be: `true` or `false`. + :ivar voice_fallback_method: The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call when an error occurs retrieving or executing the TwiML requested by `url`. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_url: The URL we call when the phone number receives a call. The `voice_url` will not be used if a `voice_application_sid` or a `trunk_sid` is set. + :ivar emergency_status: + :ivar emergency_address_sid: The SID of the emergency address configuration that we use for emergency calling from this phone number. + :ivar emergency_address_status: + :ivar bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + :ivar status: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.address_sid: Optional[str] = payload.get("address_sid") + self.address_requirements: Optional["TollFreeInstance.AddressRequirement"] = ( + payload.get("address_requirements") + ) + self.api_version: Optional[str] = payload.get("api_version") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[str] = payload.get("capabilities") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.identity_sid: Optional[str] = payload.get("identity_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.origin: Optional[str] = payload.get("origin") + self.sid: Optional[str] = payload.get("sid") + self.sms_application_sid: Optional[str] = payload.get("sms_application_sid") + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_url: Optional[str] = payload.get("sms_url") + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.uri: Optional[str] = payload.get("uri") + self.voice_receive_mode: Optional["TollFreeInstance.VoiceReceiveMode"] = ( + payload.get("voice_receive_mode") + ) + self.voice_application_sid: Optional[str] = payload.get("voice_application_sid") + self.voice_caller_id_lookup: Optional[bool] = payload.get( + "voice_caller_id_lookup" + ) + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_url: Optional[str] = payload.get("voice_url") + self.emergency_status: Optional["TollFreeInstance.EmergencyStatus"] = ( + payload.get("emergency_status") + ) + self.emergency_address_sid: Optional[str] = payload.get("emergency_address_sid") + self.emergency_address_status: Optional[ + "TollFreeInstance.EmergencyAddressStatus" + ] = payload.get("emergency_address_status") + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.status: Optional[str] = payload.get("status") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.TollFreeInstance {}>".format(context) + + +class TollFreePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TollFreeInstance: + """ + Build an instance of TollFreeInstance + + :param payload: Payload response from the API + """ + return TollFreeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.TollFreePage>" + + +class TollFreeList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the TollFreeList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/TollFree.json".format( + **self._solution + ) + + def create( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "TollFreeInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "TollFreeInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> TollFreeInstance: + """ + Create the TollFreeInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an Identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created TollFreeInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TollFreeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + phone_number: str, + api_version: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + voice_application_sid: Union[str, object] = values.unset, + voice_caller_id_lookup: Union[bool, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + identity_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + emergency_status: Union[ + "TollFreeInstance.EmergencyStatus", object + ] = values.unset, + emergency_address_sid: Union[str, object] = values.unset, + trunk_sid: Union[str, object] = values.unset, + voice_receive_mode: Union[ + "TollFreeInstance.VoiceReceiveMode", object + ] = values.unset, + bundle_sid: Union[str, object] = values.unset, + ) -> TollFreeInstance: + """ + Asynchronously create the TollFreeInstance + + :param phone_number: The phone number to purchase specified in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param api_version: The API version to use for incoming calls made to the new phone number. The default is `2010-04-01`. + :param friendly_name: A descriptive string that you created to describe the new phone number. It can be up to 64 characters long. By default, this is a formatted version of the phone number. + :param sms_application_sid: The SID of the application that should handle SMS messages sent to the new phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :param sms_fallback_method: The HTTP method that we should use to call `sms_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_fallback_url: The URL that we should call when an error occurs while requesting or executing the TwiML defined by `sms_url`. + :param sms_method: The HTTP method that we should use to call `sms_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param sms_url: The URL we should call when the new phone number receives an incoming SMS message. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_application_sid: The SID of the application we should use to handle calls to the new phone number. If a `voice_application_sid` is present, we ignore all of the voice urls and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :param voice_caller_id_lookup: Whether to lookup the caller's name from the CNAM database and post it to your app. Can be: `true` or `false` and defaults to `false`. + :param voice_fallback_method: The HTTP method that we should use to call `voice_fallback_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs retrieving or executing the TwiML requested by `url`. + :param voice_method: The HTTP method that we should use to call `voice_url`. Can be: `GET` or `POST` and defaults to `POST`. + :param voice_url: The URL that we should call to answer a call to the new phone number. The `voice_url` will not be called if a `voice_application_sid` or a `trunk_sid` is set. + :param identity_sid: The SID of the Identity resource that we should associate with the new phone number. Some regions require an Identity to meet local regulations. + :param address_sid: The SID of the Address resource we should associate with the new phone number. Some regions require addresses to meet local regulations. + :param emergency_status: + :param emergency_address_sid: The SID of the emergency address configuration to use for emergency calling from the new phone number. + :param trunk_sid: The SID of the Trunk we should use to handle calls to the new phone number. If a `trunk_sid` is present, we ignore all of the voice urls and voice applications and use only those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :param voice_receive_mode: + :param bundle_sid: The SID of the Bundle resource that you associate with the phone number. Some regions require a Bundle to meet local Regulations. + + :returns: The created TollFreeInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "ApiVersion": api_version, + "FriendlyName": friendly_name, + "SmsApplicationSid": sms_application_sid, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "VoiceApplicationSid": voice_application_sid, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TollFreeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TollFreeInstance]: + """ + Streams TollFreeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TollFreeInstance]: + """ + Asynchronously streams TollFreeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TollFreeInstance]: + """ + Lists TollFreeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TollFreeInstance]: + """ + Asynchronously lists TollFreeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param str friendly_name: A string that identifies the resources to read. + :param str phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param str origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + beta=beta, + friendly_name=friendly_name, + phone_number=phone_number, + origin=origin, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TollFreePage: + """ + Retrieve a single page of TollFreeInstance records from the API. + Request is executed immediately + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TollFreeInstance + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TollFreePage(self._version, response, self._solution) + + async def page_async( + self, + beta: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + origin: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TollFreePage: + """ + Asynchronously retrieve a single page of TollFreeInstance records from the API. + Request is executed immediately + + :param beta: Whether to include phone numbers new to the Twilio platform. Can be: `true` or `false` and the default is `true`. + :param friendly_name: A string that identifies the resources to read. + :param phone_number: The phone numbers of the IncomingPhoneNumber resources to read. You can specify partial numbers and use '*' as a wildcard for any digit. + :param origin: Whether to include phone numbers based on their origin. Can be: `twilio` or `hosted`. By default, phone numbers of all origin are included. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TollFreeInstance + """ + data = values.of( + { + "Beta": serialize.boolean_to_string(beta), + "FriendlyName": friendly_name, + "PhoneNumber": phone_number, + "Origin": origin, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TollFreePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TollFreePage: + """ + Retrieve a specific page of TollFreeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TollFreeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TollFreePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TollFreePage: + """ + Asynchronously retrieve a specific page of TollFreeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TollFreeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TollFreePage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.TollFreeList>" diff --git a/twilio/rest/api/v2010/account/key.py b/twilio/rest/api/v2010/account/key.py new file mode 100644 index 0000000000..8b18dbd4ba --- /dev/null +++ b/twilio/rest/api/v2010/account/key.py @@ -0,0 +1,566 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class KeyInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the Key resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[KeyContext] = None + + @property + def _proxy(self) -> "KeyContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: KeyContext for this KeyInstance + """ + if self._context is None: + self._context = KeyContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the KeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the KeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "KeyInstance": + """ + Fetch the KeyInstance + + + :returns: The fetched KeyInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "KeyInstance": + """ + Asynchronous coroutine to fetch the KeyInstance + + + :returns: The fetched KeyInstance + """ + return await self._proxy.fetch_async() + + def update(self, friendly_name: Union[str, object] = values.unset) -> "KeyInstance": + """ + Update the KeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated KeyInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "KeyInstance": + """ + Asynchronous coroutine to update the KeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated KeyInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.KeyInstance {}>".format(context) + + +class KeyContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the KeyContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Key resources to update. + :param sid: The Twilio-provided string that uniquely identifies the Key resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Keys/{sid}.json".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the KeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the KeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> KeyInstance: + """ + Fetch the KeyInstance + + + :returns: The fetched KeyInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> KeyInstance: + """ + Asynchronous coroutine to fetch the KeyInstance + + + :returns: The fetched KeyInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update(self, friendly_name: Union[str, object] = values.unset) -> KeyInstance: + """ + Update the KeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated KeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> KeyInstance: + """ + Asynchronous coroutine to update the KeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated KeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.KeyContext {}>".format(context) + + +class KeyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> KeyInstance: + """ + Build an instance of KeyInstance + + :param payload: Payload response from the API + """ + return KeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.KeyPage>" + + +class KeyList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the KeyList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Key resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Keys.json".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[KeyInstance]: + """ + Streams KeyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[KeyInstance]: + """ + Asynchronously streams KeyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[KeyInstance]: + """ + Lists KeyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[KeyInstance]: + """ + Asynchronously lists KeyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> KeyPage: + """ + Retrieve a single page of KeyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of KeyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return KeyPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> KeyPage: + """ + Asynchronously retrieve a single page of KeyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of KeyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return KeyPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> KeyPage: + """ + Retrieve a specific page of KeyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of KeyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return KeyPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> KeyPage: + """ + Asynchronously retrieve a specific page of KeyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of KeyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return KeyPage(self._version, response, self._solution) + + def get(self, sid: str) -> KeyContext: + """ + Constructs a KeyContext + + :param sid: The Twilio-provided string that uniquely identifies the Key resource to update. + """ + return KeyContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> KeyContext: + """ + Constructs a KeyContext + + :param sid: The Twilio-provided string that uniquely identifies the Key resource to update. + """ + return KeyContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.KeyList>" diff --git a/twilio/rest/api/v2010/account/message/__init__.py b/twilio/rest/api/v2010/account/message/__init__.py new file mode 100644 index 0000000000..d5369d11ce --- /dev/null +++ b/twilio/rest/api/v2010/account/message/__init__.py @@ -0,0 +1,1014 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.message.feedback import FeedbackList +from twilio.rest.api.v2010.account.message.media import MediaList + + +class MessageInstance(InstanceResource): + + class AddressRetention(object): + RETAIN = "retain" + OBFUSCATE = "obfuscate" + + class ContentRetention(object): + RETAIN = "retain" + DISCARD = "discard" + + class Direction(object): + INBOUND = "inbound" + OUTBOUND_API = "outbound-api" + OUTBOUND_CALL = "outbound-call" + OUTBOUND_REPLY = "outbound-reply" + + class RiskCheck(object): + ENABLE = "enable" + DISABLE = "disable" + + class ScheduleType(object): + FIXED = "fixed" + + class Status(object): + QUEUED = "queued" + SENDING = "sending" + SENT = "sent" + FAILED = "failed" + DELIVERED = "delivered" + UNDELIVERED = "undelivered" + RECEIVING = "receiving" + RECEIVED = "received" + ACCEPTED = "accepted" + SCHEDULED = "scheduled" + READ = "read" + PARTIALLY_DELIVERED = "partially_delivered" + CANCELED = "canceled" + + class TrafficType(object): + FREE = "free" + + class UpdateStatus(object): + CANCELED = "canceled" + + """ + :ivar body: The text content of the message + :ivar num_segments: The number of segments that make up the complete message. SMS message bodies that exceed the [character limit](https://www.twilio.com/docs/glossary/what-sms-character-limit) are segmented and charged as multiple messages. Note: For messages sent via a Messaging Service, `num_segments` is initially `0`, since a sender hasn't yet been assigned. + :ivar direction: + :ivar from_: The sender's phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). For incoming messages, this is the number or channel address of the sender. For outgoing messages, this value is a Twilio phone number, alphanumeric sender ID, short code, or channel address from which the message is sent. + :ivar to: The recipient's phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format) or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g. `whatsapp:+15552229999`) + :ivar date_updated: The [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822#section-3.3) timestamp (in GMT) of when the Message resource was last updated + :ivar price: The amount billed for the message in the currency specified by `price_unit`. The `price` is populated after the message has been sent/received, and may not be immediately availalble. View the [Pricing page](https://www.twilio.com/en-us/pricing) for more details. + :ivar error_message: The description of the `error_code` if the Message `status` is `failed` or `undelivered`. If no error was encountered, the value is `null`. The value returned in this field for a specific error cause is subject to change as Twilio improves errors. Users should not use the `error_code` and `error_message` fields programmatically. + :ivar uri: The URI of the Message resource, relative to `https://api.twilio.com`. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with the Message resource + :ivar num_media: The number of media files associated with the Message resource. + :ivar status: + :ivar messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) associated with the Message resource. A unique default value is assigned if a Messaging Service is not used. + :ivar sid: The unique, Twilio-provided string that identifies the Message resource. + :ivar date_sent: The [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822#section-3.3) timestamp (in GMT) of when the Message was sent. For an outgoing message, this is when Twilio sent the message. For an incoming message, this is when Twilio sent the HTTP request to your incoming message webhook URL. + :ivar date_created: The [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822#section-3.3) timestamp (in GMT) of when the Message resource was created + :ivar error_code: The [error code](https://www.twilio.com/docs/api/errors) returned if the Message `status` is `failed` or `undelivered`. If no error was encountered, the value is `null`. The value returned in this field for a specific error cause is subject to change as Twilio improves errors. Users should not use the `error_code` and `error_message` fields programmatically. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar api_version: The API version used to process the Message + :ivar subresource_uris: A list of related resources identified by their URIs relative to `https://api.twilio.com` + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.body: Optional[str] = payload.get("body") + self.num_segments: Optional[str] = payload.get("num_segments") + self.direction: Optional["MessageInstance.Direction"] = payload.get("direction") + self.from_: Optional[str] = payload.get("from") + self.to: Optional[str] = payload.get("to") + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.price: Optional[str] = payload.get("price") + self.error_message: Optional[str] = payload.get("error_message") + self.uri: Optional[str] = payload.get("uri") + self.account_sid: Optional[str] = payload.get("account_sid") + self.num_media: Optional[str] = payload.get("num_media") + self.status: Optional["MessageInstance.Status"] = payload.get("status") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.sid: Optional[str] = payload.get("sid") + self.date_sent: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_sent") + ) + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.api_version: Optional[str] = payload.get("api_version") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[MessageContext] = None + + @property + def _proxy(self) -> "MessageContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> "MessageInstance": + """ + Update the MessageInstance + + :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string + :param status: + + :returns: The updated MessageInstance + """ + return self._proxy.update( + body=body, + status=status, + ) + + async def update_async( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> "MessageInstance": + """ + Asynchronous coroutine to update the MessageInstance + + :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string + :param status: + + :returns: The updated MessageInstance + """ + return await self._proxy.update_async( + body=body, + status=status, + ) + + @property + def feedback(self) -> FeedbackList: + """ + Access the feedback + """ + return self._proxy.feedback + + @property + def media(self) -> MediaList: + """ + Access the media + """ + return self._proxy.media + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.MessageInstance {}>".format(context) + + +class MessageContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the MessageContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Message resources to update. + :param sid: The SID of the Message resource to be updated + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Messages/{sid}.json".format( + **self._solution + ) + + self._feedback: Optional[FeedbackList] = None + self._media: Optional[MediaList] = None + + def delete(self) -> bool: + """ + Deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> MessageInstance: + """ + Update the MessageInstance + + :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string + :param status: + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Body": body, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + body: Union[str, object] = values.unset, + status: Union["MessageInstance.UpdateStatus", object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param body: The new `body` of the Message resource. To redact the text content of a Message, this parameter's value must be an empty string + :param status: + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Body": body, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def feedback(self) -> FeedbackList: + """ + Access the feedback + """ + if self._feedback is None: + self._feedback = FeedbackList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._feedback + + @property + def media(self) -> MediaList: + """ + Access the media + """ + if self._media is None: + self._media = MediaList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._media + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.MessageContext {}>".format(context) + + +class MessagePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance + + :param payload: Payload response from the API + """ + return MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.MessagePage>" + + +class MessageList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with the Message resources. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Messages.json".format(**self._solution) + + def create( + self, + to: str, + status_callback: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + max_price: Union[float, object] = values.unset, + provide_feedback: Union[bool, object] = values.unset, + attempt: Union[int, object] = values.unset, + validity_period: Union[int, object] = values.unset, + force_delivery: Union[bool, object] = values.unset, + content_retention: Union[ + "MessageInstance.ContentRetention", object + ] = values.unset, + address_retention: Union[ + "MessageInstance.AddressRetention", object + ] = values.unset, + smart_encoded: Union[bool, object] = values.unset, + persistent_action: Union[List[str], object] = values.unset, + traffic_type: Union["MessageInstance.TrafficType", object] = values.unset, + shorten_urls: Union[bool, object] = values.unset, + schedule_type: Union["MessageInstance.ScheduleType", object] = values.unset, + send_at: Union[datetime, object] = values.unset, + send_as_mms: Union[bool, object] = values.unset, + content_variables: Union[str, object] = values.unset, + risk_check: Union["MessageInstance.RiskCheck", object] = values.unset, + from_: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + content_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param to: The recipient's phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (for SMS/MMS) or [channel address](https://www.twilio.com/docs/messaging/channels), e.g. `whatsapp:+15552229999`. + :param status_callback: The URL of the endpoint to which Twilio sends [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url). URL must contain a valid hostname and underscores are not allowed. If you include this parameter with the `messaging_service_sid`, Twilio uses this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource). + :param application_sid: The SID of the associated [TwiML Application](https://www.twilio.com/docs/usage/api/applications). [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url) are sent to the TwiML App's `message_status_callback` URL. Note that the `status_callback` parameter of a request takes priority over the `application_sid` parameter; if both are included `application_sid` is ignored. + :param max_price: [OBSOLETE] This parameter will no longer have any effect as of 2024-06-03. + :param provide_feedback: Boolean indicating whether or not you intend to provide delivery confirmation feedback to Twilio (used in conjunction with the [Message Feedback subresource](https://www.twilio.com/docs/sms/api/message-feedback-resource)). Default value is `false`. + :param attempt: Total number of attempts made (including this request) to send the message regardless of the provider used + :param validity_period: The maximum length in seconds that the Message can remain in Twilio's outgoing message queue. If a queued Message exceeds the `validity_period`, the Message is not sent. Accepted values are integers from `1` to `36000`. Default value is `36000`. A `validity_period` greater than `5` is recommended. [Learn more about the validity period](https://www.twilio.com/blog/take-more-control-of-outbound-messages-using-validity-period-html) + :param force_delivery: Reserved + :param content_retention: + :param address_retention: + :param smart_encoded: Whether to detect Unicode characters that have a similar GSM-7 character and replace them. Can be: `true` or `false`. + :param persistent_action: Rich actions for non-SMS/MMS channels. Used for [sending location in WhatsApp messages](https://www.twilio.com/docs/whatsapp/message-features#location-messages-with-whatsapp). + :param traffic_type: + :param shorten_urls: For Messaging Services with [Link Shortening configured](https://www.twilio.com/docs/messaging/features/link-shortening) only: A Boolean indicating whether or not Twilio should shorten links in the `body` of the Message. Default value is `false`. If `true`, the `messaging_service_sid` parameter must also be provided. + :param schedule_type: + :param send_at: The time that Twilio will send the message. Must be in ISO 8601 format. + :param send_as_mms: If set to `true`, Twilio delivers the message as a single MMS message, regardless of the presence of media. + :param content_variables: For [Content Editor/API](https://www.twilio.com/docs/content) only: Key-value pairs of [Template variables](https://www.twilio.com/docs/content/using-variables-with-content-api) and their substitution values. `content_sid` parameter must also be provided. If values are not defined in the `content_variables` parameter, the [Template's default placeholder values](https://www.twilio.com/docs/content/content-api-resources#create-templates) are used. + :param risk_check: + :param from_: The sender's Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). The value of the `from` parameter must be a sender that is hosted within Twilio and belongs to the Account creating the Message. If you are using `messaging_service_sid`, this parameter can be empty (Twilio assigns a `from` value from the Messaging Service's Sender Pool) or you can provide a specific sender from your Sender Pool. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service's Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. + :param body: The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages). + :param media_url: The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. + :param content_sid: For [Content Editor/API](https://www.twilio.com/docs/content) only: The SID of the Content Template to be used with the Message, e.g., `HXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`. If this parameter is not provided, a Content Template is not used. Find the SID in the Console on the Content Editor page. For Content API users, the SID is found in Twilio's response when [creating the Template](https://www.twilio.com/docs/content/content-api-resources#create-templates) or by [fetching your Templates](https://www.twilio.com/docs/content/content-api-resources#fetch-all-content-resources). + + :returns: The created MessageInstance + """ + + data = values.of( + { + "To": to, + "StatusCallback": status_callback, + "ApplicationSid": application_sid, + "MaxPrice": max_price, + "ProvideFeedback": serialize.boolean_to_string(provide_feedback), + "Attempt": attempt, + "ValidityPeriod": validity_period, + "ForceDelivery": serialize.boolean_to_string(force_delivery), + "ContentRetention": content_retention, + "AddressRetention": address_retention, + "SmartEncoded": serialize.boolean_to_string(smart_encoded), + "PersistentAction": serialize.map(persistent_action, lambda e: e), + "TrafficType": traffic_type, + "ShortenUrls": serialize.boolean_to_string(shorten_urls), + "ScheduleType": schedule_type, + "SendAt": serialize.iso8601_datetime(send_at), + "SendAsMms": serialize.boolean_to_string(send_as_mms), + "ContentVariables": content_variables, + "RiskCheck": risk_check, + "From": from_, + "MessagingServiceSid": messaging_service_sid, + "Body": body, + "MediaUrl": serialize.map(media_url, lambda e: e), + "ContentSid": content_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + to: str, + status_callback: Union[str, object] = values.unset, + application_sid: Union[str, object] = values.unset, + max_price: Union[float, object] = values.unset, + provide_feedback: Union[bool, object] = values.unset, + attempt: Union[int, object] = values.unset, + validity_period: Union[int, object] = values.unset, + force_delivery: Union[bool, object] = values.unset, + content_retention: Union[ + "MessageInstance.ContentRetention", object + ] = values.unset, + address_retention: Union[ + "MessageInstance.AddressRetention", object + ] = values.unset, + smart_encoded: Union[bool, object] = values.unset, + persistent_action: Union[List[str], object] = values.unset, + traffic_type: Union["MessageInstance.TrafficType", object] = values.unset, + shorten_urls: Union[bool, object] = values.unset, + schedule_type: Union["MessageInstance.ScheduleType", object] = values.unset, + send_at: Union[datetime, object] = values.unset, + send_as_mms: Union[bool, object] = values.unset, + content_variables: Union[str, object] = values.unset, + risk_check: Union["MessageInstance.RiskCheck", object] = values.unset, + from_: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + content_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param to: The recipient's phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (for SMS/MMS) or [channel address](https://www.twilio.com/docs/messaging/channels), e.g. `whatsapp:+15552229999`. + :param status_callback: The URL of the endpoint to which Twilio sends [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url). URL must contain a valid hostname and underscores are not allowed. If you include this parameter with the `messaging_service_sid`, Twilio uses this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource). + :param application_sid: The SID of the associated [TwiML Application](https://www.twilio.com/docs/usage/api/applications). [Message status callback requests](https://www.twilio.com/docs/sms/api/message-resource#twilios-request-to-the-statuscallback-url) are sent to the TwiML App's `message_status_callback` URL. Note that the `status_callback` parameter of a request takes priority over the `application_sid` parameter; if both are included `application_sid` is ignored. + :param max_price: [OBSOLETE] This parameter will no longer have any effect as of 2024-06-03. + :param provide_feedback: Boolean indicating whether or not you intend to provide delivery confirmation feedback to Twilio (used in conjunction with the [Message Feedback subresource](https://www.twilio.com/docs/sms/api/message-feedback-resource)). Default value is `false`. + :param attempt: Total number of attempts made (including this request) to send the message regardless of the provider used + :param validity_period: The maximum length in seconds that the Message can remain in Twilio's outgoing message queue. If a queued Message exceeds the `validity_period`, the Message is not sent. Accepted values are integers from `1` to `36000`. Default value is `36000`. A `validity_period` greater than `5` is recommended. [Learn more about the validity period](https://www.twilio.com/blog/take-more-control-of-outbound-messages-using-validity-period-html) + :param force_delivery: Reserved + :param content_retention: + :param address_retention: + :param smart_encoded: Whether to detect Unicode characters that have a similar GSM-7 character and replace them. Can be: `true` or `false`. + :param persistent_action: Rich actions for non-SMS/MMS channels. Used for [sending location in WhatsApp messages](https://www.twilio.com/docs/whatsapp/message-features#location-messages-with-whatsapp). + :param traffic_type: + :param shorten_urls: For Messaging Services with [Link Shortening configured](https://www.twilio.com/docs/messaging/features/link-shortening) only: A Boolean indicating whether or not Twilio should shorten links in the `body` of the Message. Default value is `false`. If `true`, the `messaging_service_sid` parameter must also be provided. + :param schedule_type: + :param send_at: The time that Twilio will send the message. Must be in ISO 8601 format. + :param send_as_mms: If set to `true`, Twilio delivers the message as a single MMS message, regardless of the presence of media. + :param content_variables: For [Content Editor/API](https://www.twilio.com/docs/content) only: Key-value pairs of [Template variables](https://www.twilio.com/docs/content/using-variables-with-content-api) and their substitution values. `content_sid` parameter must also be provided. If values are not defined in the `content_variables` parameter, the [Template's default placeholder values](https://www.twilio.com/docs/content/content-api-resources#create-templates) are used. + :param risk_check: + :param from_: The sender's Twilio phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/quickstart), [Wireless SIM](https://www.twilio.com/docs/iot/wireless/programmable-wireless-send-machine-machine-sms-commands), [short code](https://www.twilio.com/en-us/messaging/channels/sms/short-codes), or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g., `whatsapp:+15554449999`). The value of the `from` parameter must be a sender that is hosted within Twilio and belongs to the Account creating the Message. If you are using `messaging_service_sid`, this parameter can be empty (Twilio assigns a `from` value from the Messaging Service's Sender Pool) or you can provide a specific sender from your Sender Pool. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) you want to associate with the Message. When this parameter is provided and the `from` parameter is omitted, Twilio selects the optimal sender from the Messaging Service's Sender Pool. You may also provide a `from` parameter if you want to use a specific Sender from the Sender Pool. + :param body: The text content of the outgoing message. Can be up to 1,600 characters in length. SMS only: If the `body` contains more than 160 [GSM-7](https://www.twilio.com/docs/glossary/what-is-gsm-7-character-encoding) characters (or 70 [UCS-2](https://www.twilio.com/docs/glossary/what-is-ucs-2-character-encoding) characters), the message is segmented and charged accordingly. For long `body` text, consider using the [send_as_mms parameter](https://www.twilio.com/blog/mms-for-long-text-messages). + :param media_url: The URL of media to include in the Message content. `jpeg`, `jpg`, `gif`, and `png` file types are fully supported by Twilio and content is formatted for delivery on destination devices. The media size limit is 5 MB for supported file types (`jpeg`, `jpg`, `png`, `gif`) and 500 KB for [other types](https://www.twilio.com/docs/messaging/guides/accepted-mime-types) of accepted media. To send more than one image in the message, provide multiple `media_url` parameters in the POST request. You can include up to ten `media_url` parameters per message. [International](https://support.twilio.com/hc/en-us/articles/223179808-Sending-and-receiving-MMS-messages) and [carrier](https://support.twilio.com/hc/en-us/articles/223133707-Is-MMS-supported-for-all-carriers-in-US-and-Canada-) limits apply. + :param content_sid: For [Content Editor/API](https://www.twilio.com/docs/content) only: The SID of the Content Template to be used with the Message, e.g., `HXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`. If this parameter is not provided, a Content Template is not used. Find the SID in the Console on the Content Editor page. For Content API users, the SID is found in Twilio's response when [creating the Template](https://www.twilio.com/docs/content/content-api-resources#create-templates) or by [fetching your Templates](https://www.twilio.com/docs/content/content-api-resources#fetch-all-content-resources). + + :returns: The created MessageInstance + """ + + data = values.of( + { + "To": to, + "StatusCallback": status_callback, + "ApplicationSid": application_sid, + "MaxPrice": max_price, + "ProvideFeedback": serialize.boolean_to_string(provide_feedback), + "Attempt": attempt, + "ValidityPeriod": validity_period, + "ForceDelivery": serialize.boolean_to_string(force_delivery), + "ContentRetention": content_retention, + "AddressRetention": address_retention, + "SmartEncoded": serialize.boolean_to_string(smart_encoded), + "PersistentAction": serialize.map(persistent_action, lambda e: e), + "TrafficType": traffic_type, + "ShortenUrls": serialize.boolean_to_string(shorten_urls), + "ScheduleType": schedule_type, + "SendAt": serialize.iso8601_datetime(send_at), + "SendAsMms": serialize.boolean_to_string(send_as_mms), + "ContentVariables": content_variables, + "RiskCheck": risk_check, + "From": from_, + "MessagingServiceSid": messaging_service_sid, + "Body": body, + "MediaUrl": serialize.map(media_url, lambda e: e), + "ContentSid": content_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: + """ + Streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` + :param str from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + to=to, + from_=from_, + date_sent=date_sent, + date_sent_before=date_sent_before, + date_sent_after=date_sent_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInstance]: + """ + Asynchronously streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` + :param str from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + to=to, + from_=from_, + date_sent=date_sent, + date_sent_before=date_sent_before, + date_sent_after=date_sent_after, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` + :param str from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + to=to, + from_=from_, + date_sent=date_sent, + date_sent_before=date_sent_before, + date_sent_after=date_sent_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Asynchronously lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` + :param str from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param datetime date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param datetime date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + to=to, + from_=from_, + date_sent=date_sent, + date_sent_before=date_sent_before, + date_sent_after=date_sent_after, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` + :param from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "To": to, + "From": from_, + "DateSent": serialize.iso8601_datetime(date_sent), + "DateSent<": serialize.iso8601_datetime(date_sent_before), + "DateSent>": serialize.iso8601_datetime(date_sent_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + async def page_async( + self, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + date_sent: Union[datetime, object] = values.unset, + date_sent_before: Union[datetime, object] = values.unset, + date_sent_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param to: Filter by recipient. For example: Set this `to` parameter to `+15558881111` to retrieve a list of Message resources with `to` properties of `+15558881111` + :param from_: Filter by sender. For example: Set this `from` parameter to `+15552229999` to retrieve a list of Message resources with `from` properties of `+15552229999` + :param date_sent: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param date_sent_before: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param date_sent_after: Filter by Message `sent_date`. Accepts GMT dates in the following formats: `YYYY-MM-DD` (to find Messages with a specific `sent_date`), `<=YYYY-MM-DD` (to find Messages with `sent_date`s on and before a specific date), and `>=YYYY-MM-DD` (to find Messages with `sent_dates` on and after a specific date). + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "To": to, + "From": from_, + "DateSent": serialize.iso8601_datetime(date_sent), + "DateSent<": serialize.iso8601_datetime(date_sent_before), + "DateSent>": serialize.iso8601_datetime(date_sent_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MessagePage: + """ + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MessagePage: + """ + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) + + def get(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: The SID of the Message resource to be updated + """ + return MessageContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: The SID of the Message resource to be updated + """ + return MessageContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.MessageList>" diff --git a/twilio/rest/api/v2010/account/message/feedback.py b/twilio/rest/api/v2010/account/message/feedback.py new file mode 100644 index 0000000000..cda2de2ff6 --- /dev/null +++ b/twilio/rest/api/v2010/account/message/feedback.py @@ -0,0 +1,170 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class FeedbackInstance(InstanceResource): + + class Outcome(object): + CONFIRMED = "confirmed" + UNCONFIRMED = "unconfirmed" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with this MessageFeedback resource. + :ivar message_sid: The SID of the Message resource associated with this MessageFeedback resource. + :ivar outcome: + :ivar date_created: The date and time in GMT when this MessageFeedback resource was created, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when this MessageFeedback resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + message_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.message_sid: Optional[str] = payload.get("message_sid") + self.outcome: Optional["FeedbackInstance.Outcome"] = payload.get("outcome") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "message_sid": message_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.FeedbackInstance {}>".format(context) + + +class FeedbackList(ListResource): + + def __init__(self, version: Version, account_sid: str, message_sid: str): + """ + Initialize the FeedbackList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with the Message resource for which to create MessageFeedback. + :param message_sid: The SID of the Message resource for which to create MessageFeedback. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "message_sid": message_sid, + } + self._uri = ( + "/Accounts/{account_sid}/Messages/{message_sid}/Feedback.json".format( + **self._solution + ) + ) + + def create( + self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset + ) -> FeedbackInstance: + """ + Create the FeedbackInstance + + :param outcome: + + :returns: The created FeedbackInstance + """ + + data = values.of( + { + "Outcome": outcome, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FeedbackInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + ) + + async def create_async( + self, outcome: Union["FeedbackInstance.Outcome", object] = values.unset + ) -> FeedbackInstance: + """ + Asynchronously create the FeedbackInstance + + :param outcome: + + :returns: The created FeedbackInstance + """ + + data = values.of( + { + "Outcome": outcome, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FeedbackInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.FeedbackList>" diff --git a/twilio/rest/api/v2010/account/message/media.py b/twilio/rest/api/v2010/account/message/media.py new file mode 100644 index 0000000000..b5d2926d12 --- /dev/null +++ b/twilio/rest/api/v2010/account/message/media.py @@ -0,0 +1,564 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MediaInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with this Media resource. + :ivar content_type: The default [MIME type](https://en.wikipedia.org/wiki/Internet_media_type) of the media, for example `image/jpeg`, `image/png`, or `image/gif`. + :ivar date_created: The date and time in GMT when this Media resource was created, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when this Media resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar parent_sid: The SID of the Message resource that is associated with this Media resource. + :ivar sid: The unique string that identifies this Media resource. + :ivar uri: The URI of this Media resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + message_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.content_type: Optional[str] = payload.get("content_type") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.parent_sid: Optional[str] = payload.get("parent_sid") + self.sid: Optional[str] = payload.get("sid") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "message_sid": message_sid, + "sid": sid or self.sid, + } + self._context: Optional[MediaContext] = None + + @property + def _proxy(self) -> "MediaContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MediaContext for this MediaInstance + """ + if self._context is None: + self._context = MediaContext( + self._version, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the MediaInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MediaInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "MediaInstance": + """ + Fetch the MediaInstance + + + :returns: The fetched MediaInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MediaInstance": + """ + Asynchronous coroutine to fetch the MediaInstance + + + :returns: The fetched MediaInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.MediaInstance {}>".format(context) + + +class MediaContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, message_sid: str, sid: str): + """ + Initialize the MediaContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with the Media resource. + :param message_sid: The SID of the Message resource that is associated with the Media resource. + :param sid: The Twilio-provided string that uniquely identifies the Media resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "message_sid": message_sid, + "sid": sid, + } + self._uri = ( + "/Accounts/{account_sid}/Messages/{message_sid}/Media/{sid}.json".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the MediaInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MediaInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MediaInstance: + """ + Fetch the MediaInstance + + + :returns: The fetched MediaInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MediaInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MediaInstance: + """ + Asynchronous coroutine to fetch the MediaInstance + + + :returns: The fetched MediaInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MediaInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.MediaContext {}>".format(context) + + +class MediaPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MediaInstance: + """ + Build an instance of MediaInstance + + :param payload: Payload response from the API + """ + return MediaInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.MediaPage>" + + +class MediaList(ListResource): + + def __init__(self, version: Version, account_sid: str, message_sid: str): + """ + Initialize the MediaList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that is associated with the Media resources. + :param message_sid: The SID of the Message resource that is associated with the Media resources. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "message_sid": message_sid, + } + self._uri = "/Accounts/{account_sid}/Messages/{message_sid}/Media.json".format( + **self._solution + ) + + def stream( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MediaInstance]: + """ + Streams MediaInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MediaInstance]: + """ + Asynchronously streams MediaInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MediaInstance]: + """ + Lists MediaInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MediaInstance]: + """ + Asynchronously lists MediaInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param datetime date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MediaPage: + """ + Retrieve a single page of MediaInstance records from the API. + Request is executed immediately + + :param date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MediaInstance + """ + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateCreated<": serialize.iso8601_datetime(date_created_before), + "DateCreated>": serialize.iso8601_datetime(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MediaPage(self._version, response, self._solution) + + async def page_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MediaPage: + """ + Asynchronously retrieve a single page of MediaInstance records from the API. + Request is executed immediately + + :param date_created: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param date_created_before: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param date_created_after: Only include Media resources that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read Media that were created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read Media that were created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read Media that were created on or after midnight of this date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MediaInstance + """ + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateCreated<": serialize.iso8601_datetime(date_created_before), + "DateCreated>": serialize.iso8601_datetime(date_created_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MediaPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MediaPage: + """ + Retrieve a specific page of MediaInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MediaInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MediaPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MediaPage: + """ + Asynchronously retrieve a specific page of MediaInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MediaInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MediaPage(self._version, response, self._solution) + + def get(self, sid: str) -> MediaContext: + """ + Constructs a MediaContext + + :param sid: The Twilio-provided string that uniquely identifies the Media resource to fetch. + """ + return MediaContext( + self._version, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MediaContext: + """ + Constructs a MediaContext + + :param sid: The Twilio-provided string that uniquely identifies the Media resource to fetch. + """ + return MediaContext( + self._version, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.MediaList>" diff --git a/twilio/rest/api/v2010/account/new_key.py b/twilio/rest/api/v2010/account/new_key.py new file mode 100644 index 0000000000..ba811ec14f --- /dev/null +++ b/twilio/rest/api/v2010/account/new_key.py @@ -0,0 +1,144 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NewKeyInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the NewKey resource. You will use this as the basic-auth `user` when authenticating to the API. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT that the API Key was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the new API Key was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar secret: The secret your application uses to sign Access Tokens and to authenticate to the REST API (you will use this as the basic-auth `password`). **Note that for security reasons, this field is ONLY returned when the API Key is first created.** + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.secret: Optional[str] = payload.get("secret") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.NewKeyInstance {}>".format(context) + + +class NewKeyList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the NewKeyList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that will be responsible for the new Key resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Keys.json".format(**self._solution) + + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> NewKeyInstance: + """ + Create the NewKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created NewKeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NewKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> NewKeyInstance: + """ + Asynchronously create the NewKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created NewKeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NewKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.NewKeyList>" diff --git a/twilio/rest/api/v2010/account/new_signing_key.py b/twilio/rest/api/v2010/account/new_signing_key.py new file mode 100644 index 0000000000..95341d31cb --- /dev/null +++ b/twilio/rest/api/v2010/account/new_signing_key.py @@ -0,0 +1,144 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NewSigningKeyInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the NewSigningKey resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar secret: The secret your application uses to sign Access Tokens and to authenticate to the REST API (you will use this as the basic-auth `password`). **Note that for security reasons, this field is ONLY returned when the API Key is first created.** + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.secret: Optional[str] = payload.get("secret") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.NewSigningKeyInstance {}>".format(context) + + +class NewSigningKeyList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the NewSigningKeyList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that will be responsible for the new Key resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/SigningKeys.json".format(**self._solution) + + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> NewSigningKeyInstance: + """ + Create the NewSigningKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created NewSigningKeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NewSigningKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> NewSigningKeyInstance: + """ + Asynchronously create the NewSigningKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created NewSigningKeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NewSigningKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.NewSigningKeyList>" diff --git a/twilio/rest/api/v2010/account/notification.py b/twilio/rest/api/v2010/account/notification.py new file mode 100644 index 0000000000..cd35efeabf --- /dev/null +++ b/twilio/rest/api/v2010/account/notification.py @@ -0,0 +1,540 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class NotificationInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Notification resource. + :ivar api_version: The API version used to generate the notification. Can be empty for events that don't have a specific API version, such as incoming phone calls. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Notification resource is associated with. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar error_code: A unique error code for the error condition that is described in our [Error Dictionary](https://www.twilio.com/docs/api/errors). + :ivar log: An integer log level that corresponds to the type of notification: `0` is ERROR, `1` is WARNING. + :ivar message_date: The date the notification was actually generated in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. Message buffering can cause this value to differ from `date_created`. + :ivar message_text: The text of the notification. + :ivar more_info: The URL for more information about the error condition. This value is a page in our [Error Dictionary](https://www.twilio.com/docs/api/errors). + :ivar request_method: The HTTP method used to generate the notification. If the notification was generated during a phone call, this is the HTTP Method used to request the resource on your server. If the notification was generated by your use of our REST API, this is the HTTP method used to call the resource on our servers. + :ivar request_url: The URL of the resource that generated the notification. If the notification was generated during a phone call, this is the URL of the resource on your server that caused the notification. If the notification was generated by your use of our REST API, this is the URL of the resource you called. + :ivar request_variables: The HTTP GET or POST variables we sent to your server. However, if the notification was generated by our REST API, this contains the HTTP POST or PUT variables you sent to our API. + :ivar response_body: The HTTP body returned by your server. + :ivar response_headers: The HTTP headers returned by your server. + :ivar sid: The unique string that that we created to identify the Notification resource. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.call_sid: Optional[str] = payload.get("call_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.error_code: Optional[str] = payload.get("error_code") + self.log: Optional[str] = payload.get("log") + self.message_date: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("message_date") + ) + self.message_text: Optional[str] = payload.get("message_text") + self.more_info: Optional[str] = payload.get("more_info") + self.request_method: Optional[str] = payload.get("request_method") + self.request_url: Optional[str] = payload.get("request_url") + self.request_variables: Optional[str] = payload.get("request_variables") + self.response_body: Optional[str] = payload.get("response_body") + self.response_headers: Optional[str] = payload.get("response_headers") + self.sid: Optional[str] = payload.get("sid") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[NotificationContext] = None + + @property + def _proxy(self) -> "NotificationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NotificationContext for this NotificationInstance + """ + if self._context is None: + self._context = NotificationContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "NotificationInstance": + """ + Fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "NotificationInstance": + """ + Asynchronous coroutine to fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.NotificationInstance {}>".format(context) + + +class NotificationContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the NotificationContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Notification resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Notification resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Notifications/{sid}.json".format( + **self._solution + ) + + def fetch(self) -> NotificationInstance: + """ + Fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> NotificationInstance: + """ + Asynchronous coroutine to fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.NotificationContext {}>".format(context) + + +class NotificationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> NotificationInstance: + """ + Build an instance of NotificationInstance + + :param payload: Payload response from the API + """ + return NotificationInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.NotificationPage>" + + +class NotificationList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the NotificationList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Notification resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Notifications.json".format( + **self._solution + ) + + def stream( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[NotificationInstance]: + """ + Streams NotificationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[NotificationInstance]: + """ + Asynchronously streams NotificationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NotificationInstance]: + """ + Lists NotificationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NotificationInstance]: + """ + Asynchronously lists NotificationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param date message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param date message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + log=log, + message_date=message_date, + message_date_before=message_date_before, + message_date_after=message_date_after, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NotificationPage: + """ + Retrieve a single page of NotificationInstance records from the API. + Request is executed immediately + + :param log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NotificationInstance + """ + data = values.of( + { + "Log": log, + "MessageDate": serialize.iso8601_date(message_date), + "MessageDate<": serialize.iso8601_date(message_date_before), + "MessageDate>": serialize.iso8601_date(message_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NotificationPage(self._version, response, self._solution) + + async def page_async( + self, + log: Union[int, object] = values.unset, + message_date: Union[date, object] = values.unset, + message_date_before: Union[date, object] = values.unset, + message_date_after: Union[date, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NotificationPage: + """ + Asynchronously retrieve a single page of NotificationInstance records from the API. + Request is executed immediately + + :param log: Only read notifications of the specified log level. Can be: `0` to read only ERROR notifications or `1` to read only WARNING notifications. By default, all notifications are read. + :param message_date: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_before: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param message_date_after: Only show notifications for the specified date, formatted as `YYYY-MM-DD`. You can also specify an inequality, such as `<=YYYY-MM-DD` for messages logged at or before midnight on a date, or `>=YYYY-MM-DD` for messages logged at or after midnight on a date. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NotificationInstance + """ + data = values.of( + { + "Log": log, + "MessageDate": serialize.iso8601_date(message_date), + "MessageDate<": serialize.iso8601_date(message_date_before), + "MessageDate>": serialize.iso8601_date(message_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NotificationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> NotificationPage: + """ + Retrieve a specific page of NotificationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NotificationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return NotificationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> NotificationPage: + """ + Asynchronously retrieve a specific page of NotificationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NotificationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return NotificationPage(self._version, response, self._solution) + + def get(self, sid: str) -> NotificationContext: + """ + Constructs a NotificationContext + + :param sid: The Twilio-provided string that uniquely identifies the Notification resource to fetch. + """ + return NotificationContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> NotificationContext: + """ + Constructs a NotificationContext + + :param sid: The Twilio-provided string that uniquely identifies the Notification resource to fetch. + """ + return NotificationContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.NotificationList>" diff --git a/twilio/rest/api/v2010/account/outgoing_caller_id.py b/twilio/rest/api/v2010/account/outgoing_caller_id.py new file mode 100644 index 0000000000..eeb9954c75 --- /dev/null +++ b/twilio/rest/api/v2010/account/outgoing_caller_id.py @@ -0,0 +1,620 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class OutgoingCallerIdInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the OutgoingCallerId resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the OutgoingCallerId resource. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[OutgoingCallerIdContext] = None + + @property + def _proxy(self) -> "OutgoingCallerIdContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OutgoingCallerIdContext for this OutgoingCallerIdInstance + """ + if self._context is None: + self._context = OutgoingCallerIdContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the OutgoingCallerIdInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OutgoingCallerIdInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "OutgoingCallerIdInstance": + """ + Fetch the OutgoingCallerIdInstance + + + :returns: The fetched OutgoingCallerIdInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OutgoingCallerIdInstance": + """ + Asynchronous coroutine to fetch the OutgoingCallerIdInstance + + + :returns: The fetched OutgoingCallerIdInstance + """ + return await self._proxy.fetch_async() + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "OutgoingCallerIdInstance": + """ + Update the OutgoingCallerIdInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated OutgoingCallerIdInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "OutgoingCallerIdInstance": + """ + Asynchronous coroutine to update the OutgoingCallerIdInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated OutgoingCallerIdInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.OutgoingCallerIdInstance {}>".format(context) + + +class OutgoingCallerIdContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the OutgoingCallerIdContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the OutgoingCallerId resources to update. + :param sid: The Twilio-provided string that uniquely identifies the OutgoingCallerId resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/OutgoingCallerIds/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the OutgoingCallerIdInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OutgoingCallerIdInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> OutgoingCallerIdInstance: + """ + Fetch the OutgoingCallerIdInstance + + + :returns: The fetched OutgoingCallerIdInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return OutgoingCallerIdInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> OutgoingCallerIdInstance: + """ + Asynchronous coroutine to fetch the OutgoingCallerIdInstance + + + :returns: The fetched OutgoingCallerIdInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return OutgoingCallerIdInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> OutgoingCallerIdInstance: + """ + Update the OutgoingCallerIdInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated OutgoingCallerIdInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return OutgoingCallerIdInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> OutgoingCallerIdInstance: + """ + Asynchronous coroutine to update the OutgoingCallerIdInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated OutgoingCallerIdInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return OutgoingCallerIdInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.OutgoingCallerIdContext {}>".format(context) + + +class OutgoingCallerIdPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> OutgoingCallerIdInstance: + """ + Build an instance of OutgoingCallerIdInstance + + :param payload: Payload response from the API + """ + return OutgoingCallerIdInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.OutgoingCallerIdPage>" + + +class OutgoingCallerIdList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the OutgoingCallerIdList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the OutgoingCallerId resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/OutgoingCallerIds.json".format( + **self._solution + ) + + def stream( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[OutgoingCallerIdInstance]: + """ + Streams OutgoingCallerIdInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str phone_number: The phone number of the OutgoingCallerId resources to read. + :param str friendly_name: The string that identifies the OutgoingCallerId resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + phone_number=phone_number, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[OutgoingCallerIdInstance]: + """ + Asynchronously streams OutgoingCallerIdInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str phone_number: The phone number of the OutgoingCallerId resources to read. + :param str friendly_name: The string that identifies the OutgoingCallerId resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + phone_number=phone_number, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OutgoingCallerIdInstance]: + """ + Lists OutgoingCallerIdInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str phone_number: The phone number of the OutgoingCallerId resources to read. + :param str friendly_name: The string that identifies the OutgoingCallerId resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + phone_number=phone_number, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OutgoingCallerIdInstance]: + """ + Asynchronously lists OutgoingCallerIdInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str phone_number: The phone number of the OutgoingCallerId resources to read. + :param str friendly_name: The string that identifies the OutgoingCallerId resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + phone_number=phone_number, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OutgoingCallerIdPage: + """ + Retrieve a single page of OutgoingCallerIdInstance records from the API. + Request is executed immediately + + :param phone_number: The phone number of the OutgoingCallerId resources to read. + :param friendly_name: The string that identifies the OutgoingCallerId resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OutgoingCallerIdInstance + """ + data = values.of( + { + "PhoneNumber": phone_number, + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OutgoingCallerIdPage(self._version, response, self._solution) + + async def page_async( + self, + phone_number: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OutgoingCallerIdPage: + """ + Asynchronously retrieve a single page of OutgoingCallerIdInstance records from the API. + Request is executed immediately + + :param phone_number: The phone number of the OutgoingCallerId resources to read. + :param friendly_name: The string that identifies the OutgoingCallerId resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OutgoingCallerIdInstance + """ + data = values.of( + { + "PhoneNumber": phone_number, + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OutgoingCallerIdPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> OutgoingCallerIdPage: + """ + Retrieve a specific page of OutgoingCallerIdInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OutgoingCallerIdInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return OutgoingCallerIdPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> OutgoingCallerIdPage: + """ + Asynchronously retrieve a specific page of OutgoingCallerIdInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OutgoingCallerIdInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return OutgoingCallerIdPage(self._version, response, self._solution) + + def get(self, sid: str) -> OutgoingCallerIdContext: + """ + Constructs a OutgoingCallerIdContext + + :param sid: The Twilio-provided string that uniquely identifies the OutgoingCallerId resource to update. + """ + return OutgoingCallerIdContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> OutgoingCallerIdContext: + """ + Constructs a OutgoingCallerIdContext + + :param sid: The Twilio-provided string that uniquely identifies the OutgoingCallerId resource to update. + """ + return OutgoingCallerIdContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.OutgoingCallerIdList>" diff --git a/twilio/rest/api/v2010/account/queue/__init__.py b/twilio/rest/api/v2010/account/queue/__init__.py new file mode 100644 index 0000000000..e76fda1259 --- /dev/null +++ b/twilio/rest/api/v2010/account/queue/__init__.py @@ -0,0 +1,687 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.queue.member import MemberList + + +class QueueInstance(InstanceResource): + """ + :ivar date_updated: The date and time in GMT that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar current_size: The number of calls currently in the queue. + :ivar friendly_name: A string that you assigned to describe this resource. + :ivar uri: The URI of this resource, relative to `https://api.twilio.com`. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Queue resource. + :ivar average_wait_time: The average wait time in seconds of the members in this queue. This is calculated at the time of the request. + :ivar sid: The unique string that that we created to identify this Queue resource. + :ivar date_created: The date and time in GMT that this resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar max_size: The maximum number of calls that can be in the queue. The default is 1000 and the maximum is 5000. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.current_size: Optional[int] = deserialize.integer( + payload.get("current_size") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.uri: Optional[str] = payload.get("uri") + self.account_sid: Optional[str] = payload.get("account_sid") + self.average_wait_time: Optional[int] = deserialize.integer( + payload.get("average_wait_time") + ) + self.sid: Optional[str] = payload.get("sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.max_size: Optional[int] = deserialize.integer(payload.get("max_size")) + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[QueueContext] = None + + @property + def _proxy(self) -> "QueueContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: QueueContext for this QueueInstance + """ + if self._context is None: + self._context = QueueContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the QueueInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the QueueInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "QueueInstance": + """ + Fetch the QueueInstance + + + :returns: The fetched QueueInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "QueueInstance": + """ + Asynchronous coroutine to fetch the QueueInstance + + + :returns: The fetched QueueInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> "QueueInstance": + """ + Update the QueueInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: The updated QueueInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + max_size=max_size, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> "QueueInstance": + """ + Asynchronous coroutine to update the QueueInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: The updated QueueInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + max_size=max_size, + ) + + @property + def members(self) -> MemberList: + """ + Access the members + """ + return self._proxy.members + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.QueueInstance {}>".format(context) + + +class QueueContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the QueueContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Queue resource to update. + :param sid: The Twilio-provided string that uniquely identifies the Queue resource to update + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Queues/{sid}.json".format(**self._solution) + + self._members: Optional[MemberList] = None + + def delete(self) -> bool: + """ + Deletes the QueueInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the QueueInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> QueueInstance: + """ + Fetch the QueueInstance + + + :returns: The fetched QueueInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> QueueInstance: + """ + Asynchronous coroutine to fetch the QueueInstance + + + :returns: The fetched QueueInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> QueueInstance: + """ + Update the QueueInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: The updated QueueInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "MaxSize": max_size, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + max_size: Union[int, object] = values.unset, + ) -> QueueInstance: + """ + Asynchronous coroutine to update the QueueInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: The updated QueueInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "MaxSize": max_size, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def members(self) -> MemberList: + """ + Access the members + """ + if self._members is None: + self._members = MemberList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._members + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.QueueContext {}>".format(context) + + +class QueuePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> QueueInstance: + """ + Build an instance of QueueInstance + + :param payload: Payload response from the API + """ + return QueueInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.QueuePage>" + + +class QueueList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the QueueList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Queue resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Queues.json".format(**self._solution) + + def create( + self, friendly_name: str, max_size: Union[int, object] = values.unset + ) -> QueueInstance: + """ + Create the QueueInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: The created QueueInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "MaxSize": max_size, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return QueueInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, friendly_name: str, max_size: Union[int, object] = values.unset + ) -> QueueInstance: + """ + Asynchronously create the QueueInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. + :param max_size: The maximum number of calls allowed to be in the queue. The default is 1000. The maximum is 5000. + + :returns: The created QueueInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "MaxSize": max_size, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return QueueInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[QueueInstance]: + """ + Streams QueueInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[QueueInstance]: + """ + Asynchronously streams QueueInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[QueueInstance]: + """ + Lists QueueInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[QueueInstance]: + """ + Asynchronously lists QueueInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> QueuePage: + """ + Retrieve a single page of QueueInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of QueueInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return QueuePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> QueuePage: + """ + Asynchronously retrieve a single page of QueueInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of QueueInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return QueuePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> QueuePage: + """ + Retrieve a specific page of QueueInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of QueueInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return QueuePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> QueuePage: + """ + Asynchronously retrieve a specific page of QueueInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of QueueInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return QueuePage(self._version, response, self._solution) + + def get(self, sid: str) -> QueueContext: + """ + Constructs a QueueContext + + :param sid: The Twilio-provided string that uniquely identifies the Queue resource to update + """ + return QueueContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> QueueContext: + """ + Constructs a QueueContext + + :param sid: The Twilio-provided string that uniquely identifies the Queue resource to update + """ + return QueueContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.QueueList>" diff --git a/twilio/rest/api/v2010/account/queue/member.py b/twilio/rest/api/v2010/account/queue/member.py new file mode 100644 index 0000000000..30ff4abbc7 --- /dev/null +++ b/twilio/rest/api/v2010/account/queue/member.py @@ -0,0 +1,564 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MemberInstance(InstanceResource): + """ + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Member resource is associated with. + :ivar date_enqueued: The date that the member was enqueued, given in RFC 2822 format. + :ivar position: This member's current position in the queue. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar wait_time: The number of seconds the member has been in the queue. + :ivar queue_sid: The SID of the Queue the member is in. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + queue_sid: str, + call_sid: Optional[str] = None, + ): + super().__init__(version) + + self.call_sid: Optional[str] = payload.get("call_sid") + self.date_enqueued: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_enqueued") + ) + self.position: Optional[int] = deserialize.integer(payload.get("position")) + self.uri: Optional[str] = payload.get("uri") + self.wait_time: Optional[int] = deserialize.integer(payload.get("wait_time")) + self.queue_sid: Optional[str] = payload.get("queue_sid") + + self._solution = { + "account_sid": account_sid, + "queue_sid": queue_sid, + "call_sid": call_sid or self.call_sid, + } + self._context: Optional[MemberContext] = None + + @property + def _proxy(self) -> "MemberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MemberContext for this MemberInstance + """ + if self._context is None: + self._context = MemberContext( + self._version, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + return self._context + + def fetch(self) -> "MemberInstance": + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MemberInstance": + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + return await self._proxy.fetch_async() + + def update( + self, url: str, method: Union[str, object] = values.unset + ) -> "MemberInstance": + """ + Update the MemberInstance + + :param url: The absolute URL of the Queue resource. + :param method: How to pass the update request data. Can be `GET` or `POST` and the default is `POST`. `POST` sends the data as encoded form data and `GET` sends the data as query parameters. + + :returns: The updated MemberInstance + """ + return self._proxy.update( + url=url, + method=method, + ) + + async def update_async( + self, url: str, method: Union[str, object] = values.unset + ) -> "MemberInstance": + """ + Asynchronous coroutine to update the MemberInstance + + :param url: The absolute URL of the Queue resource. + :param method: How to pass the update request data. Can be `GET` or `POST` and the default is `POST`. `POST` sends the data as encoded form data and `GET` sends the data as query parameters. + + :returns: The updated MemberInstance + """ + return await self._proxy.update_async( + url=url, + method=method, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.MemberInstance {}>".format(context) + + +class MemberContext(InstanceContext): + + def __init__( + self, version: Version, account_sid: str, queue_sid: str, call_sid: str + ): + """ + Initialize the MemberContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Member resource(s) to update. + :param queue_sid: The SID of the Queue in which to find the members to update. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resource(s) to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "queue_sid": queue_sid, + "call_sid": call_sid, + } + self._uri = ( + "/Accounts/{account_sid}/Queues/{queue_sid}/Members/{call_sid}.json".format( + **self._solution + ) + ) + + def fetch(self) -> MemberInstance: + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + + async def fetch_async(self) -> MemberInstance: + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + + def update( + self, url: str, method: Union[str, object] = values.unset + ) -> MemberInstance: + """ + Update the MemberInstance + + :param url: The absolute URL of the Queue resource. + :param method: How to pass the update request data. Can be `GET` or `POST` and the default is `POST`. `POST` sends the data as encoded form data and `GET` sends the data as query parameters. + + :returns: The updated MemberInstance + """ + + data = values.of( + { + "Url": url, + "Method": method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + + async def update_async( + self, url: str, method: Union[str, object] = values.unset + ) -> MemberInstance: + """ + Asynchronous coroutine to update the MemberInstance + + :param url: The absolute URL of the Queue resource. + :param method: How to pass the update request data. Can be `GET` or `POST` and the default is `POST`. `POST` sends the data as encoded form data and `GET` sends the data as query parameters. + + :returns: The updated MemberInstance + """ + + data = values.of( + { + "Url": url, + "Method": method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.MemberContext {}>".format(context) + + +class MemberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: + """ + Build an instance of MemberInstance + + :param payload: Payload response from the API + """ + return MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.MemberPage>" + + +class MemberList(ListResource): + + def __init__(self, version: Version, account_sid: str, queue_sid: str): + """ + Initialize the MemberList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Member resource(s) to read. + :param queue_sid: The SID of the Queue in which to find the members + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "queue_sid": queue_sid, + } + self._uri = "/Accounts/{account_sid}/Queues/{queue_sid}/Members.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MemberInstance]: + """ + Streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MemberInstance]: + """ + Asynchronously streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Asynchronously lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Asynchronously retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MemberPage: + """ + Retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MemberPage: + """ + Asynchronously retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MemberPage(self._version, response, self._solution) + + def get(self, call_sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resource(s) to update. + """ + return MemberContext( + self._version, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=call_sid, + ) + + def __call__(self, call_sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resource(s) to update. + """ + return MemberContext( + self._version, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=call_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.MemberList>" diff --git a/twilio/rest/api/v2010/account/recording/__init__.py b/twilio/rest/api/v2010/account/recording/__init__.py new file mode 100644 index 0000000000..807fb3ca6e --- /dev/null +++ b/twilio/rest/api/v2010/account/recording/__init__.py @@ -0,0 +1,720 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.recording.add_on_result import AddOnResultList +from twilio.rest.api.v2010.account.recording.transcription import TranscriptionList + + +class RecordingInstance(InstanceResource): + + class Source(object): + DIALVERB = "DialVerb" + CONFERENCE = "Conference" + OUTBOUNDAPI = "OutboundAPI" + TRUNKING = "Trunking" + RECORDVERB = "RecordVerb" + STARTCALLRECORDINGAPI = "StartCallRecordingAPI" + STARTCONFERENCERECORDINGAPI = "StartConferenceRecordingAPI" + + class Status(object): + IN_PROGRESS = "in-progress" + PAUSED = "paused" + STOPPED = "stopped" + PROCESSING = "processing" + COMPLETED = "completed" + ABSENT = "absent" + DELETED = "deleted" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resource. + :ivar api_version: The API version used during the recording. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Recording resource is associated with. This will always refer to the parent leg of a two-leg call. + :ivar conference_sid: The Conference SID that identifies the conference associated with the recording, if a conference recording. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar start_time: The start time of the recording in GMT and in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar duration: The length of the recording in seconds. + :ivar sid: The unique string that that we created to identify the Recording resource. + :ivar price: The one-time cost of creating the recording in the `price_unit` currency. + :ivar price_unit: The currency used in the `price` property. Example: `USD`. + :ivar status: + :ivar channels: The number of channels in the final recording file. Can be: `1` or `2`. Default: `1`. + :ivar source: + :ivar error_code: The error code that describes why the recording is `absent`. The error code is described in our [Error Dictionary](https://www.twilio.com/docs/api/errors). This value is null if the recording `status` is not `absent`. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar encryption_details: How to decrypt the recording if it was encrypted using [Call Recording Encryption](https://www.twilio.com/docs/voice/tutorials/voice-recording-encryption) feature. + :ivar subresource_uris: A list of related resources identified by their relative URIs. + :ivar media_url: The URL of the media file associated with this recording resource. When stored externally, this is the full URL location of the media file. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.call_sid: Optional[str] = payload.get("call_sid") + self.conference_sid: Optional[str] = payload.get("conference_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.start_time: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("start_time") + ) + self.duration: Optional[str] = payload.get("duration") + self.sid: Optional[str] = payload.get("sid") + self.price: Optional[str] = payload.get("price") + self.price_unit: Optional[str] = payload.get("price_unit") + self.status: Optional["RecordingInstance.Status"] = payload.get("status") + self.channels: Optional[int] = deserialize.integer(payload.get("channels")) + self.source: Optional["RecordingInstance.Source"] = payload.get("source") + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.uri: Optional[str] = payload.get("uri") + self.encryption_details: Optional[Dict[str, object]] = payload.get( + "encryption_details" + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.media_url: Optional[str] = payload.get("media_url") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[RecordingContext] = None + + @property + def _proxy(self) -> "RecordingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RecordingContext for this RecordingInstance + """ + if self._context is None: + self._context = RecordingContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> "RecordingInstance": + """ + Fetch the RecordingInstance + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + + :returns: The fetched RecordingInstance + """ + return self._proxy.fetch( + include_soft_deleted=include_soft_deleted, + ) + + async def fetch_async( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> "RecordingInstance": + """ + Asynchronous coroutine to fetch the RecordingInstance + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + + :returns: The fetched RecordingInstance + """ + return await self._proxy.fetch_async( + include_soft_deleted=include_soft_deleted, + ) + + @property + def add_on_results(self) -> AddOnResultList: + """ + Access the add_on_results + """ + return self._proxy.add_on_results + + @property + def transcriptions(self) -> TranscriptionList: + """ + Access the transcriptions + """ + return self._proxy.transcriptions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.RecordingInstance {}>".format(context) + + +class RecordingContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the RecordingContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Recording resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Recordings/{sid}.json".format( + **self._solution + ) + + self._add_on_results: Optional[AddOnResultList] = None + self._transcriptions: Optional[TranscriptionList] = None + + def delete(self) -> bool: + """ + Deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> RecordingInstance: + """ + Fetch the RecordingInstance + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + + :returns: The fetched RecordingInstance + """ + + data = values.of( + { + "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance + + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + + :returns: The fetched RecordingInstance + """ + + data = values.of( + { + "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def add_on_results(self) -> AddOnResultList: + """ + Access the add_on_results + """ + if self._add_on_results is None: + self._add_on_results = AddOnResultList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._add_on_results + + @property + def transcriptions(self) -> TranscriptionList: + """ + Access the transcriptions + """ + if self._transcriptions is None: + self._transcriptions = TranscriptionList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._transcriptions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.RecordingContext {}>".format(context) + + +class RecordingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: + """ + Build an instance of RecordingInstance + + :param payload: Payload response from the API + """ + return RecordingInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.RecordingPage>" + + +class RecordingList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the RecordingList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Recordings.json".format(**self._solution) + + def stream( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RecordingInstance]: + """ + Streams RecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param str call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param str conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param bool include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + call_sid=call_sid, + conference_sid=conference_sid, + include_soft_deleted=include_soft_deleted, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RecordingInstance]: + """ + Asynchronously streams RecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param str call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param str conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param bool include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + call_sid=call_sid, + conference_sid=conference_sid, + include_soft_deleted=include_soft_deleted, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordingInstance]: + """ + Lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param str call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param str conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param bool include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + call_sid=call_sid, + conference_sid=conference_sid, + include_soft_deleted=include_soft_deleted, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordingInstance]: + """ + Asynchronously lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param datetime date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param str call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param str conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param bool include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + date_created=date_created, + date_created_before=date_created_before, + date_created_after=date_created_after, + call_sid=call_sid, + conference_sid=conference_sid, + include_soft_deleted=include_soft_deleted, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordingPage: + """ + Retrieve a single page of RecordingInstance records from the API. + Request is executed immediately + + :param date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordingInstance + """ + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateCreated<": serialize.iso8601_datetime(date_created_before), + "DateCreated>": serialize.iso8601_datetime(date_created_after), + "CallSid": call_sid, + "ConferenceSid": conference_sid, + "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response, self._solution) + + async def page_async( + self, + date_created: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + call_sid: Union[str, object] = values.unset, + conference_sid: Union[str, object] = values.unset, + include_soft_deleted: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordingPage: + """ + Asynchronously retrieve a single page of RecordingInstance records from the API. + Request is executed immediately + + :param date_created: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param date_created_before: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param date_created_after: Only include recordings that were created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read recordings that were created on this date. You can also specify an inequality, such as `DateCreated<=YYYY-MM-DD`, to read recordings that were created on or before midnight of this date, and `DateCreated>=YYYY-MM-DD` to read recordings that were created on or after midnight of this date. + :param call_sid: The [Call](https://www.twilio.com/docs/voice/api/call-resource) SID of the resources to read. + :param conference_sid: The Conference SID that identifies the conference associated with the recording to read. + :param include_soft_deleted: A boolean parameter indicating whether to retrieve soft deleted recordings or not. Recordings metadata are kept after deletion for a retention period of 40 days. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordingInstance + """ + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateCreated<": serialize.iso8601_datetime(date_created_before), + "DateCreated>": serialize.iso8601_datetime(date_created_after), + "CallSid": call_sid, + "ConferenceSid": conference_sid, + "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RecordingPage: + """ + Retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RecordingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RecordingPage: + """ + Asynchronously retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RecordingPage(self._version, response, self._solution) + + def get(self, sid: str) -> RecordingContext: + """ + Constructs a RecordingContext + + :param sid: The Twilio-provided string that uniquely identifies the Recording resource to fetch. + """ + return RecordingContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RecordingContext: + """ + Constructs a RecordingContext + + :param sid: The Twilio-provided string that uniquely identifies the Recording resource to fetch. + """ + return RecordingContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.RecordingList>" diff --git a/twilio/rest/api/v2010/account/recording/add_on_result/__init__.py b/twilio/rest/api/v2010/account/recording/add_on_result/__init__.py new file mode 100644 index 0000000000..95296f3cc4 --- /dev/null +++ b/twilio/rest/api/v2010/account/recording/add_on_result/__init__.py @@ -0,0 +1,553 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.recording.add_on_result.payload import PayloadList + + +class AddOnResultInstance(InstanceResource): + + class Status(object): + CANCELED = "canceled" + COMPLETED = "completed" + DELETED = "deleted" + FAILED = "failed" + IN_PROGRESS = "in-progress" + INIT = "init" + PROCESSING = "processing" + QUEUED = "queued" + + """ + :ivar sid: The unique string that that we created to identify the Recording AddOnResult resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult resource. + :ivar status: + :ivar add_on_sid: The SID of the Add-on to which the result belongs. + :ivar add_on_configuration_sid: The SID of the Add-on configuration. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_completed: The date and time in GMT that the result was completed specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar reference_sid: The SID of the recording to which the AddOnResult resource belongs. + :ivar subresource_uris: A list of related resources identified by their relative URIs. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + reference_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.status: Optional["AddOnResultInstance.Status"] = payload.get("status") + self.add_on_sid: Optional[str] = payload.get("add_on_sid") + self.add_on_configuration_sid: Optional[str] = payload.get( + "add_on_configuration_sid" + ) + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.date_completed: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_completed") + ) + self.reference_sid: Optional[str] = payload.get("reference_sid") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "sid": sid or self.sid, + } + self._context: Optional[AddOnResultContext] = None + + @property + def _proxy(self) -> "AddOnResultContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AddOnResultContext for this AddOnResultInstance + """ + if self._context is None: + self._context = AddOnResultContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AddOnResultInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AddOnResultInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AddOnResultInstance": + """ + Fetch the AddOnResultInstance + + + :returns: The fetched AddOnResultInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AddOnResultInstance": + """ + Asynchronous coroutine to fetch the AddOnResultInstance + + + :returns: The fetched AddOnResultInstance + """ + return await self._proxy.fetch_async() + + @property + def payloads(self) -> PayloadList: + """ + Access the payloads + """ + return self._proxy.payloads + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.AddOnResultInstance {}>".format(context) + + +class AddOnResultContext(InstanceContext): + + def __init__( + self, version: Version, account_sid: str, reference_sid: str, sid: str + ): + """ + Initialize the AddOnResultContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult resource to fetch. + :param reference_sid: The SID of the recording to which the result to fetch belongs. + :param sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Recordings/{reference_sid}/AddOnResults/{sid}.json".format( + **self._solution + ) + + self._payloads: Optional[PayloadList] = None + + def delete(self) -> bool: + """ + Deletes the AddOnResultInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AddOnResultInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AddOnResultInstance: + """ + Fetch the AddOnResultInstance + + + :returns: The fetched AddOnResultInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AddOnResultInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AddOnResultInstance: + """ + Asynchronous coroutine to fetch the AddOnResultInstance + + + :returns: The fetched AddOnResultInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AddOnResultInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=self._solution["sid"], + ) + + @property + def payloads(self) -> PayloadList: + """ + Access the payloads + """ + if self._payloads is None: + self._payloads = PayloadList( + self._version, + self._solution["account_sid"], + self._solution["reference_sid"], + self._solution["sid"], + ) + return self._payloads + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.AddOnResultContext {}>".format(context) + + +class AddOnResultPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AddOnResultInstance: + """ + Build an instance of AddOnResultInstance + + :param payload: Payload response from the API + """ + return AddOnResultInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AddOnResultPage>" + + +class AddOnResultList(ListResource): + + def __init__(self, version: Version, account_sid: str, reference_sid: str): + """ + Initialize the AddOnResultList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult resources to read. + :param reference_sid: The SID of the recording to which the result to read belongs. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + } + self._uri = "/Accounts/{account_sid}/Recordings/{reference_sid}/AddOnResults.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AddOnResultInstance]: + """ + Streams AddOnResultInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AddOnResultInstance]: + """ + Asynchronously streams AddOnResultInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AddOnResultInstance]: + """ + Lists AddOnResultInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AddOnResultInstance]: + """ + Asynchronously lists AddOnResultInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AddOnResultPage: + """ + Retrieve a single page of AddOnResultInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AddOnResultInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AddOnResultPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AddOnResultPage: + """ + Asynchronously retrieve a single page of AddOnResultInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AddOnResultInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AddOnResultPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AddOnResultPage: + """ + Retrieve a specific page of AddOnResultInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AddOnResultInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AddOnResultPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AddOnResultPage: + """ + Asynchronously retrieve a specific page of AddOnResultInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AddOnResultInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AddOnResultPage(self._version, response, self._solution) + + def get(self, sid: str) -> AddOnResultContext: + """ + Constructs a AddOnResultContext + + :param sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult resource to fetch. + """ + return AddOnResultContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AddOnResultContext: + """ + Constructs a AddOnResultContext + + :param sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult resource to fetch. + """ + return AddOnResultContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AddOnResultList>" diff --git a/twilio/rest/api/v2010/account/recording/add_on_result/payload/__init__.py b/twilio/rest/api/v2010/account/recording/add_on_result/payload/__init__.py new file mode 100644 index 0000000000..08e6ea2109 --- /dev/null +++ b/twilio/rest/api/v2010/account/recording/add_on_result/payload/__init__.py @@ -0,0 +1,566 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.recording.add_on_result.payload.data import DataList + + +class PayloadInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the Recording AddOnResult Payload resource. + :ivar add_on_result_sid: The SID of the AddOnResult to which the payload belongs. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult Payload resource. + :ivar label: The string provided by the vendor that describes the payload. + :ivar add_on_sid: The SID of the Add-on to which the result belongs. + :ivar add_on_configuration_sid: The SID of the Add-on configuration. + :ivar content_type: The MIME type of the payload. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar reference_sid: The SID of the recording to which the AddOnResult resource that contains the payload belongs. + :ivar subresource_uris: A list of related resources identified by their relative URIs. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + reference_sid: str, + add_on_result_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.add_on_result_sid: Optional[str] = payload.get("add_on_result_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.label: Optional[str] = payload.get("label") + self.add_on_sid: Optional[str] = payload.get("add_on_sid") + self.add_on_configuration_sid: Optional[str] = payload.get( + "add_on_configuration_sid" + ) + self.content_type: Optional[str] = payload.get("content_type") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.reference_sid: Optional[str] = payload.get("reference_sid") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "add_on_result_sid": add_on_result_sid, + "sid": sid or self.sid, + } + self._context: Optional[PayloadContext] = None + + @property + def _proxy(self) -> "PayloadContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PayloadContext for this PayloadInstance + """ + if self._context is None: + self._context = PayloadContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the PayloadInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PayloadInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "PayloadInstance": + """ + Fetch the PayloadInstance + + + :returns: The fetched PayloadInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PayloadInstance": + """ + Asynchronous coroutine to fetch the PayloadInstance + + + :returns: The fetched PayloadInstance + """ + return await self._proxy.fetch_async() + + @property + def data(self) -> DataList: + """ + Access the data + """ + return self._proxy.data + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.PayloadInstance {}>".format(context) + + +class PayloadContext(InstanceContext): + + def __init__( + self, + version: Version, + account_sid: str, + reference_sid: str, + add_on_result_sid: str, + sid: str, + ): + """ + Initialize the PayloadContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult Payload resource to fetch. + :param reference_sid: The SID of the recording to which the AddOnResult resource that contains the payload to fetch belongs. + :param add_on_result_sid: The SID of the AddOnResult to which the payload to fetch belongs. + :param sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult Payload resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "add_on_result_sid": add_on_result_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Recordings/{reference_sid}/AddOnResults/{add_on_result_sid}/Payloads/{sid}.json".format( + **self._solution + ) + + self._data: Optional[DataList] = None + + def delete(self) -> bool: + """ + Deletes the PayloadInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PayloadInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> PayloadInstance: + """ + Fetch the PayloadInstance + + + :returns: The fetched PayloadInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PayloadInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> PayloadInstance: + """ + Asynchronous coroutine to fetch the PayloadInstance + + + :returns: The fetched PayloadInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PayloadInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + sid=self._solution["sid"], + ) + + @property + def data(self) -> DataList: + """ + Access the data + """ + if self._data is None: + self._data = DataList( + self._version, + self._solution["account_sid"], + self._solution["reference_sid"], + self._solution["add_on_result_sid"], + self._solution["sid"], + ) + return self._data + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.PayloadContext {}>".format(context) + + +class PayloadPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PayloadInstance: + """ + Build an instance of PayloadInstance + + :param payload: Payload response from the API + """ + return PayloadInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.PayloadPage>" + + +class PayloadList(ListResource): + + def __init__( + self, + version: Version, + account_sid: str, + reference_sid: str, + add_on_result_sid: str, + ): + """ + Initialize the PayloadList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult Payload resources to read. + :param reference_sid: The SID of the recording to which the AddOnResult resource that contains the payloads to read belongs. + :param add_on_result_sid: The SID of the AddOnResult to which the payloads to read belongs. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "add_on_result_sid": add_on_result_sid, + } + self._uri = "/Accounts/{account_sid}/Recordings/{reference_sid}/AddOnResults/{add_on_result_sid}/Payloads.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PayloadInstance]: + """ + Streams PayloadInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PayloadInstance]: + """ + Asynchronously streams PayloadInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PayloadInstance]: + """ + Lists PayloadInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PayloadInstance]: + """ + Asynchronously lists PayloadInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PayloadPage: + """ + Retrieve a single page of PayloadInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PayloadInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PayloadPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PayloadPage: + """ + Asynchronously retrieve a single page of PayloadInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PayloadInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PayloadPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> PayloadPage: + """ + Retrieve a specific page of PayloadInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PayloadInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PayloadPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> PayloadPage: + """ + Asynchronously retrieve a specific page of PayloadInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PayloadInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PayloadPage(self._version, response, self._solution) + + def get(self, sid: str) -> PayloadContext: + """ + Constructs a PayloadContext + + :param sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult Payload resource to fetch. + """ + return PayloadContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> PayloadContext: + """ + Constructs a PayloadContext + + :param sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult Payload resource to fetch. + """ + return PayloadContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.PayloadList>" diff --git a/twilio/rest/api/v2010/account/recording/add_on_result/payload/data.py b/twilio/rest/api/v2010/account/recording/add_on_result/payload/data.py new file mode 100644 index 0000000000..48567badca --- /dev/null +++ b/twilio/rest/api/v2010/account/recording/add_on_result/payload/data.py @@ -0,0 +1,247 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class DataInstance(InstanceResource): + """ + :ivar redirect_to: The URL to redirect to to get the data returned by the AddOn that was previously stored. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + reference_sid: str, + add_on_result_sid: str, + payload_sid: str, + ): + super().__init__(version) + + self.redirect_to: Optional[str] = payload.get("redirect_to") + + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "add_on_result_sid": add_on_result_sid, + "payload_sid": payload_sid, + } + self._context: Optional[DataContext] = None + + @property + def _proxy(self) -> "DataContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DataContext for this DataInstance + """ + if self._context is None: + self._context = DataContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + payload_sid=self._solution["payload_sid"], + ) + return self._context + + def fetch(self) -> "DataInstance": + """ + Fetch the DataInstance + + + :returns: The fetched DataInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DataInstance": + """ + Asynchronous coroutine to fetch the DataInstance + + + :returns: The fetched DataInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.DataInstance {}>".format(context) + + +class DataContext(InstanceContext): + + def __init__( + self, + version: Version, + account_sid: str, + reference_sid: str, + add_on_result_sid: str, + payload_sid: str, + ): + """ + Initialize the DataContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult Payload resource to fetch. + :param reference_sid: The SID of the recording to which the AddOnResult resource that contains the payload to fetch belongs. + :param add_on_result_sid: The SID of the AddOnResult to which the payload to fetch belongs. + :param payload_sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult Payload resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "add_on_result_sid": add_on_result_sid, + "payload_sid": payload_sid, + } + self._uri = "/Accounts/{account_sid}/Recordings/{reference_sid}/AddOnResults/{add_on_result_sid}/Payloads/{payload_sid}/Data.json".format( + **self._solution + ) + + def fetch(self) -> DataInstance: + """ + Fetch the DataInstance + + + :returns: The fetched DataInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DataInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + payload_sid=self._solution["payload_sid"], + ) + + async def fetch_async(self) -> DataInstance: + """ + Asynchronous coroutine to fetch the DataInstance + + + :returns: The fetched DataInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DataInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + payload_sid=self._solution["payload_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.DataContext {}>".format(context) + + +class DataList(ListResource): + + def __init__( + self, + version: Version, + account_sid: str, + reference_sid: str, + add_on_result_sid: str, + payload_sid: str, + ): + """ + Initialize the DataList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording AddOnResult Payload resource to fetch. + :param reference_sid: The SID of the recording to which the AddOnResult resource that contains the payload to fetch belongs. + :param add_on_result_sid: The SID of the AddOnResult to which the payload to fetch belongs. + :param payload_sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult Payload resource to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "add_on_result_sid": add_on_result_sid, + "payload_sid": payload_sid, + } + + def get(self) -> DataContext: + """ + Constructs a DataContext + + """ + return DataContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + payload_sid=self._solution["payload_sid"], + ) + + def __call__(self) -> DataContext: + """ + Constructs a DataContext + + """ + return DataContext( + self._version, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + add_on_result_sid=self._solution["add_on_result_sid"], + payload_sid=self._solution["payload_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.DataList>" diff --git a/twilio/rest/api/v2010/account/recording/transcription.py b/twilio/rest/api/v2010/account/recording/transcription.py new file mode 100644 index 0000000000..472f5b2bff --- /dev/null +++ b/twilio/rest/api/v2010/account/recording/transcription.py @@ -0,0 +1,524 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TranscriptionInstance(InstanceResource): + + class Status(object): + IN_PROGRESS = "in-progress" + COMPLETED = "completed" + FAILED = "failed" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Transcription resource. + :ivar api_version: The API version used to create the transcription. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar duration: The duration of the transcribed audio in seconds. + :ivar price: The charge for the transcript in the currency associated with the account. This value is populated after the transcript is complete so it may not be available immediately. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar recording_sid: The SID of the [Recording](https://www.twilio.com/docs/voice/api/recording) from which the transcription was created. + :ivar sid: The unique string that that we created to identify the Transcription resource. + :ivar status: + :ivar transcription_text: The text content of the transcription. + :ivar type: The transcription type. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + recording_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.duration: Optional[str] = payload.get("duration") + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.recording_sid: Optional[str] = payload.get("recording_sid") + self.sid: Optional[str] = payload.get("sid") + self.status: Optional["TranscriptionInstance.Status"] = payload.get("status") + self.transcription_text: Optional[str] = payload.get("transcription_text") + self.type: Optional[str] = payload.get("type") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "recording_sid": recording_sid, + "sid": sid or self.sid, + } + self._context: Optional[TranscriptionContext] = None + + @property + def _proxy(self) -> "TranscriptionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TranscriptionContext for this TranscriptionInstance + """ + if self._context is None: + self._context = TranscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TranscriptionInstance": + """ + Fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TranscriptionInstance": + """ + Asynchronous coroutine to fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.TranscriptionInstance {}>".format(context) + + +class TranscriptionContext(InstanceContext): + + def __init__( + self, version: Version, account_sid: str, recording_sid: str, sid: str + ): + """ + Initialize the TranscriptionContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Transcription resource to fetch. + :param recording_sid: The SID of the [Recording](https://www.twilio.com/docs/voice/api/recording) that created the transcription to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Transcription resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "recording_sid": recording_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Recordings/{recording_sid}/Transcriptions/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TranscriptionInstance: + """ + Fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TranscriptionInstance: + """ + Asynchronous coroutine to fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.TranscriptionContext {}>".format(context) + + +class TranscriptionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TranscriptionInstance: + """ + Build an instance of TranscriptionInstance + + :param payload: Payload response from the API + """ + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.TranscriptionPage>" + + +class TranscriptionList(ListResource): + + def __init__(self, version: Version, account_sid: str, recording_sid: str): + """ + Initialize the TranscriptionList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Transcription resources to read. + :param recording_sid: The SID of the [Recording](https://www.twilio.com/docs/voice/api/recording) that created the transcriptions to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "recording_sid": recording_sid, + } + self._uri = "/Accounts/{account_sid}/Recordings/{recording_sid}/Transcriptions.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TranscriptionInstance]: + """ + Streams TranscriptionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TranscriptionInstance]: + """ + Asynchronously streams TranscriptionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptionInstance]: + """ + Lists TranscriptionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptionInstance]: + """ + Asynchronously lists TranscriptionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TranscriptionPage: + """ + Retrieve a single page of TranscriptionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TranscriptionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TranscriptionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TranscriptionPage: + """ + Asynchronously retrieve a single page of TranscriptionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TranscriptionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TranscriptionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TranscriptionPage: + """ + Retrieve a specific page of TranscriptionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TranscriptionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TranscriptionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TranscriptionPage: + """ + Asynchronously retrieve a specific page of TranscriptionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TranscriptionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TranscriptionPage(self._version, response, self._solution) + + def get(self, sid: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param sid: The Twilio-provided string that uniquely identifies the Transcription resource to fetch. + """ + return TranscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param sid: The Twilio-provided string that uniquely identifies the Transcription resource to fetch. + """ + return TranscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.TranscriptionList>" diff --git a/twilio/rest/api/v2010/account/short_code.py b/twilio/rest/api/v2010/account/short_code.py new file mode 100644 index 0000000000..eae35c4aa5 --- /dev/null +++ b/twilio/rest/api/v2010/account/short_code.py @@ -0,0 +1,650 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ShortCodeInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this ShortCode resource. + :ivar api_version: The API version used to start a new TwiML session when an SMS message is sent to this short code. + :ivar date_created: The date and time in GMT that this resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: A string that you assigned to describe this resource. By default, the `FriendlyName` is the short code. + :ivar short_code: The short code. e.g., 894546. + :ivar sid: The unique string that that we created to identify this ShortCode resource. + :ivar sms_fallback_method: The HTTP method we use to call the `sms_fallback_url`. Can be: `GET` or `POST`. + :ivar sms_fallback_url: The URL that we call if an error occurs while retrieving or executing the TwiML from `sms_url`. + :ivar sms_method: The HTTP method we use to call the `sms_url`. Can be: `GET` or `POST`. + :ivar sms_url: The URL we call when receiving an incoming SMS message to this short code. + :ivar uri: The URI of this resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.short_code: Optional[str] = payload.get("short_code") + self.sid: Optional[str] = payload.get("sid") + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_url: Optional[str] = payload.get("sms_url") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[ShortCodeContext] = None + + @property + def _proxy(self) -> "ShortCodeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ShortCodeContext for this ShortCodeInstance + """ + if self._context is None: + self._context = ShortCodeContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ShortCodeInstance": + """ + Fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ShortCodeInstance": + """ + Asynchronous coroutine to fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + ) -> "ShortCodeInstance": + """ + Update the ShortCodeInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. By default, the `FriendlyName` is the short code. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. + :param sms_url: The URL we should call when receiving an incoming SMS message to this short code. + :param sms_method: The HTTP method we should use when calling the `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call if an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method that we should use to call the `sms_fallback_url`. Can be: `GET` or `POST`. + + :returns: The updated ShortCodeInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + api_version=api_version, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + ) -> "ShortCodeInstance": + """ + Asynchronous coroutine to update the ShortCodeInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. By default, the `FriendlyName` is the short code. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. + :param sms_url: The URL we should call when receiving an incoming SMS message to this short code. + :param sms_method: The HTTP method we should use when calling the `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call if an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method that we should use to call the `sms_fallback_url`. Can be: `GET` or `POST`. + + :returns: The updated ShortCodeInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + api_version=api_version, + sms_url=sms_url, + sms_method=sms_method, + sms_fallback_url=sms_fallback_url, + sms_fallback_method=sms_fallback_method, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.ShortCodeInstance {}>".format(context) + + +class ShortCodeContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the ShortCodeContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ShortCode resource(s) to update. + :param sid: The Twilio-provided string that uniquely identifies the ShortCode resource to update + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SMS/ShortCodes/{sid}.json".format( + **self._solution + ) + + def fetch(self) -> ShortCodeInstance: + """ + Fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ShortCodeInstance: + """ + Asynchronous coroutine to fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + ) -> ShortCodeInstance: + """ + Update the ShortCodeInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. By default, the `FriendlyName` is the short code. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. + :param sms_url: The URL we should call when receiving an incoming SMS message to this short code. + :param sms_method: The HTTP method we should use when calling the `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call if an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method that we should use to call the `sms_fallback_url`. Can be: `GET` or `POST`. + + :returns: The updated ShortCodeInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApiVersion": api_version, + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + api_version: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + ) -> ShortCodeInstance: + """ + Asynchronous coroutine to update the ShortCodeInstance + + :param friendly_name: A descriptive string that you created to describe this resource. It can be up to 64 characters long. By default, the `FriendlyName` is the short code. + :param api_version: The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. + :param sms_url: The URL we should call when receiving an incoming SMS message to this short code. + :param sms_method: The HTTP method we should use when calling the `sms_url`. Can be: `GET` or `POST`. + :param sms_fallback_url: The URL that we should call if an error occurs while retrieving or executing the TwiML from `sms_url`. + :param sms_fallback_method: The HTTP method that we should use to call the `sms_fallback_url`. Can be: `GET` or `POST`. + + :returns: The updated ShortCodeInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApiVersion": api_version, + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.ShortCodeContext {}>".format(context) + + +class ShortCodePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ShortCodeInstance: + """ + Build an instance of ShortCodeInstance + + :param payload: Payload response from the API + """ + return ShortCodeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.ShortCodePage>" + + +class ShortCodeList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the ShortCodeList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ShortCode resource(s) to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/SMS/ShortCodes.json".format( + **self._solution + ) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ShortCodeInstance]: + """ + Streams ShortCodeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The string that identifies the ShortCode resources to read. + :param str short_code: Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + friendly_name=friendly_name, + short_code=short_code, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ShortCodeInstance]: + """ + Asynchronously streams ShortCodeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The string that identifies the ShortCode resources to read. + :param str short_code: Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, + short_code=short_code, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ShortCodeInstance]: + """ + Lists ShortCodeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The string that identifies the ShortCode resources to read. + :param str short_code: Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + short_code=short_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ShortCodeInstance]: + """ + Asynchronously lists ShortCodeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The string that identifies the ShortCode resources to read. + :param str short_code: Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + short_code=short_code, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ShortCodePage: + """ + Retrieve a single page of ShortCodeInstance records from the API. + Request is executed immediately + + :param friendly_name: The string that identifies the ShortCode resources to read. + :param short_code: Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ShortCodeInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "ShortCode": short_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ShortCodePage(self._version, response, self._solution) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + short_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ShortCodePage: + """ + Asynchronously retrieve a single page of ShortCodeInstance records from the API. + Request is executed immediately + + :param friendly_name: The string that identifies the ShortCode resources to read. + :param short_code: Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ShortCodeInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "ShortCode": short_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ShortCodePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ShortCodePage: + """ + Retrieve a specific page of ShortCodeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ShortCodeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ShortCodePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ShortCodePage: + """ + Asynchronously retrieve a specific page of ShortCodeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ShortCodeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ShortCodePage(self._version, response, self._solution) + + def get(self, sid: str) -> ShortCodeContext: + """ + Constructs a ShortCodeContext + + :param sid: The Twilio-provided string that uniquely identifies the ShortCode resource to update + """ + return ShortCodeContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ShortCodeContext: + """ + Constructs a ShortCodeContext + + :param sid: The Twilio-provided string that uniquely identifies the ShortCode resource to update + """ + return ShortCodeContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.ShortCodeList>" diff --git a/twilio/rest/api/v2010/account/signing_key.py b/twilio/rest/api/v2010/account/signing_key.py new file mode 100644 index 0000000000..8e33f218f5 --- /dev/null +++ b/twilio/rest/api/v2010/account/signing_key.py @@ -0,0 +1,572 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SigningKeyInstance(InstanceResource): + """ + :ivar sid: + :ivar friendly_name: + :ivar date_created: + :ivar date_updated: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[SigningKeyContext] = None + + @property + def _proxy(self) -> "SigningKeyContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SigningKeyContext for this SigningKeyInstance + """ + if self._context is None: + self._context = SigningKeyContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SigningKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SigningKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SigningKeyInstance": + """ + Fetch the SigningKeyInstance + + + :returns: The fetched SigningKeyInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SigningKeyInstance": + """ + Asynchronous coroutine to fetch the SigningKeyInstance + + + :returns: The fetched SigningKeyInstance + """ + return await self._proxy.fetch_async() + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "SigningKeyInstance": + """ + Update the SigningKeyInstance + + :param friendly_name: + + :returns: The updated SigningKeyInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "SigningKeyInstance": + """ + Asynchronous coroutine to update the SigningKeyInstance + + :param friendly_name: + + :returns: The updated SigningKeyInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.SigningKeyInstance {}>".format(context) + + +class SigningKeyContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the SigningKeyContext + + :param version: Version that contains the resource + :param account_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SigningKeys/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the SigningKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SigningKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SigningKeyInstance: + """ + Fetch the SigningKeyInstance + + + :returns: The fetched SigningKeyInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SigningKeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SigningKeyInstance: + """ + Asynchronous coroutine to fetch the SigningKeyInstance + + + :returns: The fetched SigningKeyInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SigningKeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> SigningKeyInstance: + """ + Update the SigningKeyInstance + + :param friendly_name: + + :returns: The updated SigningKeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SigningKeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> SigningKeyInstance: + """ + Asynchronous coroutine to update the SigningKeyInstance + + :param friendly_name: + + :returns: The updated SigningKeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SigningKeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.SigningKeyContext {}>".format(context) + + +class SigningKeyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SigningKeyInstance: + """ + Build an instance of SigningKeyInstance + + :param payload: Payload response from the API + """ + return SigningKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.SigningKeyPage>" + + +class SigningKeyList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the SigningKeyList + + :param version: Version that contains the resource + :param account_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/SigningKeys.json".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SigningKeyInstance]: + """ + Streams SigningKeyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SigningKeyInstance]: + """ + Asynchronously streams SigningKeyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SigningKeyInstance]: + """ + Lists SigningKeyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SigningKeyInstance]: + """ + Asynchronously lists SigningKeyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SigningKeyPage: + """ + Retrieve a single page of SigningKeyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SigningKeyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SigningKeyPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SigningKeyPage: + """ + Asynchronously retrieve a single page of SigningKeyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SigningKeyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SigningKeyPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SigningKeyPage: + """ + Retrieve a specific page of SigningKeyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SigningKeyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SigningKeyPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SigningKeyPage: + """ + Asynchronously retrieve a specific page of SigningKeyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SigningKeyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SigningKeyPage(self._version, response, self._solution) + + def get(self, sid: str) -> SigningKeyContext: + """ + Constructs a SigningKeyContext + + :param sid: + """ + return SigningKeyContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> SigningKeyContext: + """ + Constructs a SigningKeyContext + + :param sid: + """ + return SigningKeyContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.SigningKeyList>" diff --git a/twilio/rest/api/v2010/account/sip/__init__.py b/twilio/rest/api/v2010/account/sip/__init__.py new file mode 100644 index 0000000000..12c695ff72 --- /dev/null +++ b/twilio/rest/api/v2010/account/sip/__init__.py @@ -0,0 +1,89 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.api.v2010.account.sip.credential_list import CredentialListList +from twilio.rest.api.v2010.account.sip.domain import DomainList +from twilio.rest.api.v2010.account.sip.ip_access_control_list import ( + IpAccessControlListList, +) + + +class SipList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the SipList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the SipDomain resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/SIP.json".format(**self._solution) + + self._credential_lists: Optional[CredentialListList] = None + self._domains: Optional[DomainList] = None + self._ip_access_control_lists: Optional[IpAccessControlListList] = None + + @property + def credential_lists(self) -> CredentialListList: + """ + Access the credential_lists + """ + if self._credential_lists is None: + self._credential_lists = CredentialListList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._credential_lists + + @property + def domains(self) -> DomainList: + """ + Access the domains + """ + if self._domains is None: + self._domains = DomainList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._domains + + @property + def ip_access_control_lists(self) -> IpAccessControlListList: + """ + Access the ip_access_control_lists + """ + if self._ip_access_control_lists is None: + self._ip_access_control_lists = IpAccessControlListList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._ip_access_control_lists + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.SipList>" diff --git a/twilio/rest/api/v2010/account/sip/credential_list/__init__.py b/twilio/rest/api/v2010/account/sip/credential_list/__init__.py new file mode 100644 index 0000000000..d1be747b6d --- /dev/null +++ b/twilio/rest/api/v2010/account/sip/credential_list/__init__.py @@ -0,0 +1,653 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.sip.credential_list.credential import CredentialList + + +class CredentialListInstance(InstanceResource): + """ + :ivar account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) that owns this resource. + :ivar date_created: The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar date_updated: The date that this resource was last updated, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar friendly_name: A human readable descriptive text that describes the CredentialList, up to 64 characters long. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar subresource_uris: A list of credentials associated with this credential list. + :ivar uri: The URI for this resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[CredentialListContext] = None + + @property + def _proxy(self) -> "CredentialListContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CredentialListContext for this CredentialListInstance + """ + if self._context is None: + self._context = CredentialListContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialListInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialListInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CredentialListInstance": + """ + Fetch the CredentialListInstance + + + :returns: The fetched CredentialListInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialListInstance": + """ + Asynchronous coroutine to fetch the CredentialListInstance + + + :returns: The fetched CredentialListInstance + """ + return await self._proxy.fetch_async() + + def update(self, friendly_name: str) -> "CredentialListInstance": + """ + Update the CredentialListInstance + + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. + + :returns: The updated CredentialListInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async(self, friendly_name: str) -> "CredentialListInstance": + """ + Asynchronous coroutine to update the CredentialListInstance + + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. + + :returns: The updated CredentialListInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + @property + def credentials(self) -> CredentialList: + """ + Access the credentials + """ + return self._proxy.credentials + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.CredentialListInstance {}>".format(context) + + +class CredentialListContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the CredentialListContext + + :param version: Version that contains the resource + :param account_sid: The unique id of the Account that is responsible for this resource. + :param sid: The credential list Sid that uniquely identifies this resource + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/CredentialLists/{sid}.json".format( + **self._solution + ) + + self._credentials: Optional[CredentialList] = None + + def delete(self) -> bool: + """ + Deletes the CredentialListInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialListInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialListInstance: + """ + Fetch the CredentialListInstance + + + :returns: The fetched CredentialListInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialListInstance: + """ + Asynchronous coroutine to fetch the CredentialListInstance + + + :returns: The fetched CredentialListInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update(self, friendly_name: str) -> CredentialListInstance: + """ + Update the CredentialListInstance + + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. + + :returns: The updated CredentialListInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, friendly_name: str) -> CredentialListInstance: + """ + Asynchronous coroutine to update the CredentialListInstance + + :param friendly_name: A human readable descriptive text for a CredentialList, up to 64 characters long. + + :returns: The updated CredentialListInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def credentials(self) -> CredentialList: + """ + Access the credentials + """ + if self._credentials is None: + self._credentials = CredentialList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._credentials + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.CredentialListContext {}>".format(context) + + +class CredentialListPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialListInstance: + """ + Build an instance of CredentialListInstance + + :param payload: Payload response from the API + """ + return CredentialListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.CredentialListPage>" + + +class CredentialListList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the CredentialListList + + :param version: Version that contains the resource + :param account_sid: The unique id of the Account that is responsible for this resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/CredentialLists.json".format( + **self._solution + ) + + def create(self, friendly_name: str) -> CredentialListInstance: + """ + Create the CredentialListInstance + + :param friendly_name: A human readable descriptive text that describes the CredentialList, up to 64 characters long. + + :returns: The created CredentialListInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async(self, friendly_name: str) -> CredentialListInstance: + """ + Asynchronously create the CredentialListInstance + + :param friendly_name: A human readable descriptive text that describes the CredentialList, up to 64 characters long. + + :returns: The created CredentialListInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialListInstance]: + """ + Streams CredentialListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialListInstance]: + """ + Asynchronously streams CredentialListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListInstance]: + """ + Lists CredentialListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListInstance]: + """ + Asynchronously lists CredentialListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialListPage: + """ + Retrieve a single page of CredentialListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialListInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialListPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialListPage: + """ + Asynchronously retrieve a single page of CredentialListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialListInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialListPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> CredentialListPage: + """ + Retrieve a specific page of CredentialListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialListInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialListPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> CredentialListPage: + """ + Asynchronously retrieve a specific page of CredentialListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialListInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialListPage(self._version, response, self._solution) + + def get(self, sid: str) -> CredentialListContext: + """ + Constructs a CredentialListContext + + :param sid: The credential list Sid that uniquely identifies this resource + """ + return CredentialListContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> CredentialListContext: + """ + Constructs a CredentialListContext + + :param sid: The credential list Sid that uniquely identifies this resource + """ + return CredentialListContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.CredentialListList>" diff --git a/twilio/rest/api/v2010/account/sip/credential_list/credential.py b/twilio/rest/api/v2010/account/sip/credential_list/credential.py new file mode 100644 index 0000000000..9c52a110e0 --- /dev/null +++ b/twilio/rest/api/v2010/account/sip/credential_list/credential.py @@ -0,0 +1,666 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CredentialInstance(InstanceResource): + """ + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar account_sid: The unique id of the Account that is responsible for this resource. + :ivar credential_list_sid: The unique id that identifies the credential list that includes this credential. + :ivar username: The username for this credential. + :ivar date_created: The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar date_updated: The date that this resource was last updated, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar uri: The URI for this resource, relative to `https://api.twilio.com` + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + credential_list_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.credential_list_sid: Optional[str] = payload.get("credential_list_sid") + self.username: Optional[str] = payload.get("username") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "credential_list_sid": credential_list_sid, + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None + + @property + def _proxy(self) -> "CredentialContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CredentialInstance": + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialInstance": + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return await self._proxy.fetch_async() + + def update( + self, password: Union[str, object] = values.unset + ) -> "CredentialInstance": + """ + Update the CredentialInstance + + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: The updated CredentialInstance + """ + return self._proxy.update( + password=password, + ) + + async def update_async( + self, password: Union[str, object] = values.unset + ) -> "CredentialInstance": + """ + Asynchronous coroutine to update the CredentialInstance + + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: The updated CredentialInstance + """ + return await self._proxy.update_async( + password=password, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.CredentialInstance {}>".format(context) + + +class CredentialContext(InstanceContext): + + def __init__( + self, version: Version, account_sid: str, credential_list_sid: str, sid: str + ): + """ + Initialize the CredentialContext + + :param version: Version that contains the resource + :param account_sid: The unique id of the Account that is responsible for this resource. + :param credential_list_sid: The unique id that identifies the credential list that includes this credential. + :param sid: The unique id that identifies the resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "credential_list_sid": credential_list_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/CredentialLists/{credential_list_sid}/Credentials/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], + ) + + def update(self, password: Union[str, object] = values.unset) -> CredentialInstance: + """ + Update the CredentialInstance + + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "Password": password, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, password: Union[str, object] = values.unset + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "Password": password, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.CredentialContext {}>".format(context) + + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance + + :param payload: Payload response from the API + """ + return CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.CredentialPage>" + + +class CredentialList(ListResource): + + def __init__(self, version: Version, account_sid: str, credential_list_sid: str): + """ + Initialize the CredentialList + + :param version: Version that contains the resource + :param account_sid: The unique id of the Account that is responsible for this resource. + :param credential_list_sid: The unique id that identifies the credential list that contains the desired credentials. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "credential_list_sid": credential_list_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/CredentialLists/{credential_list_sid}/Credentials.json".format( + **self._solution + ) + + def create(self, username: str, password: str) -> CredentialInstance: + """ + Create the CredentialInstance + + :param username: The username that will be passed when authenticating SIP requests. The username should be sent in response to Twilio's challenge of the initial INVITE. It can be up to 32 characters long. + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Username": username, + "Password": password, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + ) + + async def create_async(self, username: str, password: str) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param username: The username that will be passed when authenticating SIP requests. The username should be sent in response to Twilio's challenge of the initial INVITE. It can be up to 32 characters long. + :param password: The password that the username will use when authenticating SIP requests. The password must be a minimum of 12 characters, contain at least 1 digit, and have mixed case. (eg `IWasAtSignal2018`) + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Username": username, + "Password": password, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialInstance]: + """ + Streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: + """ + Asynchronously streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Asynchronously lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Asynchronously retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> CredentialPage: + """ + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> CredentialPage: + """ + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response, self._solution) + + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The unique id that identifies the resource to update. + """ + return CredentialContext( + self._version, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The unique id that identifies the resource to update. + """ + return CredentialContext( + self._version, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.CredentialList>" diff --git a/twilio/rest/api/v2010/account/sip/domain/__init__.py b/twilio/rest/api/v2010/account/sip/domain/__init__.py new file mode 100644 index 0000000000..0a45e68273 --- /dev/null +++ b/twilio/rest/api/v2010/account/sip/domain/__init__.py @@ -0,0 +1,977 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.sip.domain.auth_types import AuthTypesList +from twilio.rest.api.v2010.account.sip.domain.credential_list_mapping import ( + CredentialListMappingList, +) +from twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping import ( + IpAccessControlListMappingList, +) + + +class DomainInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the SipDomain resource. + :ivar api_version: The API version used to process the call. + :ivar auth_type: The types of authentication you have mapped to your domain. Can be: `IP_ACL` and `CREDENTIAL_LIST`. If you have both defined for your domain, both will be returned in a comma delimited string. If `auth_type` is not defined, the domain will not be able to receive any traffic. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \"-\" and must end with `sip.twilio.com`. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar sid: The unique string that that we created to identify the SipDomain resource. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar voice_fallback_method: The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call when an error occurs while retrieving or executing the TwiML requested from `voice_url`. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_status_callback_method: The HTTP method we use to call `voice_status_callback_url`. Either `GET` or `POST`. + :ivar voice_status_callback_url: The URL that we call to pass status parameters (such as call ended) to your application. + :ivar voice_url: The URL we call using the `voice_method` when the domain receives a call. + :ivar subresource_uris: A list of mapping resources associated with the SIP Domain resource identified by their relative URIs. + :ivar sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. + :ivar emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :ivar secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :ivar byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :ivar emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.auth_type: Optional[str] = payload.get("auth_type") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.domain_name: Optional[str] = payload.get("domain_name") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + self.uri: Optional[str] = payload.get("uri") + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_status_callback_method: Optional[str] = payload.get( + "voice_status_callback_method" + ) + self.voice_status_callback_url: Optional[str] = payload.get( + "voice_status_callback_url" + ) + self.voice_url: Optional[str] = payload.get("voice_url") + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.sip_registration: Optional[bool] = payload.get("sip_registration") + self.emergency_calling_enabled: Optional[bool] = payload.get( + "emergency_calling_enabled" + ) + self.secure: Optional[bool] = payload.get("secure") + self.byoc_trunk_sid: Optional[str] = payload.get("byoc_trunk_sid") + self.emergency_caller_sid: Optional[str] = payload.get("emergency_caller_sid") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[DomainContext] = None + + @property + def _proxy(self) -> "DomainContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DomainContext for this DomainInstance + """ + if self._context is None: + self._context = DomainContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the DomainInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DomainInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "DomainInstance": + """ + Fetch the DomainInstance + + + :returns: The fetched DomainInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DomainInstance": + """ + Asynchronous coroutine to fetch the DomainInstance + + + :returns: The fetched DomainInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + domain_name: Union[str, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> "DomainInstance": + """ + Update the DomainInstance + + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_url: The URL we should call when the domain receives a call. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: The updated DomainInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_status_callback_method=voice_status_callback_method, + voice_status_callback_url=voice_status_callback_url, + voice_url=voice_url, + sip_registration=sip_registration, + domain_name=domain_name, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + domain_name: Union[str, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> "DomainInstance": + """ + Asynchronous coroutine to update the DomainInstance + + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_url: The URL we should call when the domain receives a call. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: The updated DomainInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_status_callback_method=voice_status_callback_method, + voice_status_callback_url=voice_status_callback_url, + voice_url=voice_url, + sip_registration=sip_registration, + domain_name=domain_name, + emergency_calling_enabled=emergency_calling_enabled, + secure=secure, + byoc_trunk_sid=byoc_trunk_sid, + emergency_caller_sid=emergency_caller_sid, + ) + + @property + def auth(self) -> AuthTypesList: + """ + Access the auth + """ + return self._proxy.auth + + @property + def credential_list_mappings(self) -> CredentialListMappingList: + """ + Access the credential_list_mappings + """ + return self._proxy.credential_list_mappings + + @property + def ip_access_control_list_mappings(self) -> IpAccessControlListMappingList: + """ + Access the ip_access_control_list_mappings + """ + return self._proxy.ip_access_control_list_mappings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.DomainInstance {}>".format(context) + + +class DomainContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the DomainContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the SipDomain resource to update. + :param sid: The Twilio-provided string that uniquely identifies the SipDomain resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{sid}.json".format( + **self._solution + ) + + self._auth: Optional[AuthTypesList] = None + self._credential_list_mappings: Optional[CredentialListMappingList] = None + self._ip_access_control_list_mappings: Optional[ + IpAccessControlListMappingList + ] = None + + def delete(self) -> bool: + """ + Deletes the DomainInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DomainInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> DomainInstance: + """ + Fetch the DomainInstance + + + :returns: The fetched DomainInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> DomainInstance: + """ + Asynchronous coroutine to fetch the DomainInstance + + + :returns: The fetched DomainInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + domain_name: Union[str, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> DomainInstance: + """ + Update the DomainInstance + + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_url: The URL we should call when the domain receives a call. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: The updated DomainInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceStatusCallbackMethod": voice_status_callback_method, + "VoiceStatusCallbackUrl": voice_status_callback_url, + "VoiceUrl": voice_url, + "SipRegistration": serialize.boolean_to_string(sip_registration), + "DomainName": domain_name, + "EmergencyCallingEnabled": serialize.boolean_to_string( + emergency_calling_enabled + ), + "Secure": serialize.boolean_to_string(secure), + "ByocTrunkSid": byoc_trunk_sid, + "EmergencyCallerSid": emergency_caller_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + domain_name: Union[str, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> DomainInstance: + """ + Asynchronous coroutine to update the DomainInstance + + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_url: The URL we should call when the domain receives a call. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: The updated DomainInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceStatusCallbackMethod": voice_status_callback_method, + "VoiceStatusCallbackUrl": voice_status_callback_url, + "VoiceUrl": voice_url, + "SipRegistration": serialize.boolean_to_string(sip_registration), + "DomainName": domain_name, + "EmergencyCallingEnabled": serialize.boolean_to_string( + emergency_calling_enabled + ), + "Secure": serialize.boolean_to_string(secure), + "ByocTrunkSid": byoc_trunk_sid, + "EmergencyCallerSid": emergency_caller_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def auth(self) -> AuthTypesList: + """ + Access the auth + """ + if self._auth is None: + self._auth = AuthTypesList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._auth + + @property + def credential_list_mappings(self) -> CredentialListMappingList: + """ + Access the credential_list_mappings + """ + if self._credential_list_mappings is None: + self._credential_list_mappings = CredentialListMappingList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._credential_list_mappings + + @property + def ip_access_control_list_mappings(self) -> IpAccessControlListMappingList: + """ + Access the ip_access_control_list_mappings + """ + if self._ip_access_control_list_mappings is None: + self._ip_access_control_list_mappings = IpAccessControlListMappingList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._ip_access_control_list_mappings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.DomainContext {}>".format(context) + + +class DomainPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DomainInstance: + """ + Build an instance of DomainInstance + + :param payload: Payload response from the API + """ + return DomainInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.DomainPage>" + + +class DomainList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the DomainList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the SipDomain resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains.json".format(**self._solution) + + def create( + self, + domain_name: str, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> DomainInstance: + """ + Create the DomainInstance + + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_url: The URL we should when the domain receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: The created DomainInstance + """ + + data = values.of( + { + "DomainName": domain_name, + "FriendlyName": friendly_name, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceStatusCallbackUrl": voice_status_callback_url, + "VoiceStatusCallbackMethod": voice_status_callback_method, + "SipRegistration": serialize.boolean_to_string(sip_registration), + "EmergencyCallingEnabled": serialize.boolean_to_string( + emergency_calling_enabled + ), + "Secure": serialize.boolean_to_string(secure), + "ByocTrunkSid": byoc_trunk_sid, + "EmergencyCallerSid": emergency_caller_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DomainInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + domain_name: str, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_status_callback_url: Union[str, object] = values.unset, + voice_status_callback_method: Union[str, object] = values.unset, + sip_registration: Union[bool, object] = values.unset, + emergency_calling_enabled: Union[bool, object] = values.unset, + secure: Union[bool, object] = values.unset, + byoc_trunk_sid: Union[str, object] = values.unset, + emergency_caller_sid: Union[str, object] = values.unset, + ) -> DomainInstance: + """ + Asynchronously create the DomainInstance + + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and \\\"-\\\" and must end with `sip.twilio.com`. + :param friendly_name: A descriptive string that you created to describe the resource. It can be up to 64 characters long. + :param voice_url: The URL we should when the domain receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param voice_status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param voice_status_callback_method: The HTTP method we should use to call `voice_status_callback_url`. Can be: `GET` or `POST`. + :param sip_registration: Whether to allow SIP Endpoints to register with the domain to receive calls. Can be `true` or `false`. `true` allows SIP Endpoints to register with the domain to receive calls, `false` does not. + :param emergency_calling_enabled: Whether emergency calling is enabled for the domain. If enabled, allows emergency calls on the domain from phone numbers with validated addresses. + :param secure: Whether secure SIP is enabled for the domain. If enabled, TLS will be enforced and SRTP will be negotiated on all incoming calls to this sip domain. + :param byoc_trunk_sid: The SID of the BYOC Trunk(Bring Your Own Carrier) resource that the Sip Domain will be associated with. + :param emergency_caller_sid: Whether an emergency caller sid is configured for the domain. If present, this phone number will be used as the callback for the emergency call. + + :returns: The created DomainInstance + """ + + data = values.of( + { + "DomainName": domain_name, + "FriendlyName": friendly_name, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceStatusCallbackUrl": voice_status_callback_url, + "VoiceStatusCallbackMethod": voice_status_callback_method, + "SipRegistration": serialize.boolean_to_string(sip_registration), + "EmergencyCallingEnabled": serialize.boolean_to_string( + emergency_calling_enabled + ), + "Secure": serialize.boolean_to_string(secure), + "ByocTrunkSid": byoc_trunk_sid, + "EmergencyCallerSid": emergency_caller_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DomainInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DomainInstance]: + """ + Streams DomainInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DomainInstance]: + """ + Asynchronously streams DomainInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DomainInstance]: + """ + Lists DomainInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DomainInstance]: + """ + Asynchronously lists DomainInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DomainPage: + """ + Retrieve a single page of DomainInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DomainInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DomainPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DomainPage: + """ + Asynchronously retrieve a single page of DomainInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DomainInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DomainPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DomainPage: + """ + Retrieve a specific page of DomainInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DomainInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DomainPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DomainPage: + """ + Asynchronously retrieve a specific page of DomainInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DomainInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DomainPage(self._version, response, self._solution) + + def get(self, sid: str) -> DomainContext: + """ + Constructs a DomainContext + + :param sid: The Twilio-provided string that uniquely identifies the SipDomain resource to update. + """ + return DomainContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> DomainContext: + """ + Constructs a DomainContext + + :param sid: The Twilio-provided string that uniquely identifies the SipDomain resource to update. + """ + return DomainContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.DomainList>" diff --git a/twilio/rest/api/v2010/account/sip/domain/auth_types/__init__.py b/twilio/rest/api/v2010/account/sip/domain/auth_types/__init__.py new file mode 100644 index 0000000000..73a81ac90d --- /dev/null +++ b/twilio/rest/api/v2010/account/sip/domain/auth_types/__init__.py @@ -0,0 +1,86 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.api.v2010.account.sip.domain.auth_types.auth_type_calls import ( + AuthTypeCallsList, +) +from twilio.rest.api.v2010.account.sip.domain.auth_types.auth_type_registrations import ( + AuthTypeRegistrationsList, +) + + +class AuthTypesList(ListResource): + + def __init__(self, version: Version, account_sid: str, domain_sid: str): + """ + Initialize the AuthTypesList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resource to fetch. + :param domain_sid: The SID of the SIP domain that contains the resource to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/Auth.json".format( + **self._solution + ) + + self._calls: Optional[AuthTypeCallsList] = None + self._registrations: Optional[AuthTypeRegistrationsList] = None + + @property + def calls(self) -> AuthTypeCallsList: + """ + Access the calls + """ + if self._calls is None: + self._calls = AuthTypeCallsList( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return self._calls + + @property + def registrations(self) -> AuthTypeRegistrationsList: + """ + Access the registrations + """ + if self._registrations is None: + self._registrations = AuthTypeRegistrationsList( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return self._registrations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AuthTypesList>" diff --git a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__init__.py b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__init__.py new file mode 100644 index 0000000000..79a42fa01d --- /dev/null +++ b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__init__.py @@ -0,0 +1,96 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.api.v2010.account.sip.domain.auth_types.auth_type_calls.auth_calls_credential_list_mapping import ( + AuthCallsCredentialListMappingList, +) +from twilio.rest.api.v2010.account.sip.domain.auth_types.auth_type_calls.auth_calls_ip_access_control_list_mapping import ( + AuthCallsIpAccessControlListMappingList, +) + + +class AuthTypeCallsList(ListResource): + + def __init__(self, version: Version, account_sid: str, domain_sid: str): + """ + Initialize the AuthTypeCallsList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resource to fetch. + :param domain_sid: The SID of the SIP domain that contains the resource to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + } + self._uri = ( + "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/Auth/Calls.json".format( + **self._solution + ) + ) + + self._credential_list_mappings: Optional[AuthCallsCredentialListMappingList] = ( + None + ) + self._ip_access_control_list_mappings: Optional[ + AuthCallsIpAccessControlListMappingList + ] = None + + @property + def credential_list_mappings(self) -> AuthCallsCredentialListMappingList: + """ + Access the credential_list_mappings + """ + if self._credential_list_mappings is None: + self._credential_list_mappings = AuthCallsCredentialListMappingList( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return self._credential_list_mappings + + @property + def ip_access_control_list_mappings( + self, + ) -> AuthCallsIpAccessControlListMappingList: + """ + Access the ip_access_control_list_mappings + """ + if self._ip_access_control_list_mappings is None: + self._ip_access_control_list_mappings = ( + AuthCallsIpAccessControlListMappingList( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + ) + return self._ip_access_control_list_mappings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AuthTypeCallsList>" diff --git a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_credential_list_mapping.py b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_credential_list_mapping.py new file mode 100644 index 0000000000..4839f17d48 --- /dev/null +++ b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_credential_list_mapping.py @@ -0,0 +1,582 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AuthCallsCredentialListMappingInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar sid: The unique string that that we created to identify the CredentialListMapping resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + domain_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid or self.sid, + } + self._context: Optional[AuthCallsCredentialListMappingContext] = None + + @property + def _proxy(self) -> "AuthCallsCredentialListMappingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AuthCallsCredentialListMappingContext for this AuthCallsCredentialListMappingInstance + """ + if self._context is None: + self._context = AuthCallsCredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AuthCallsCredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AuthCallsCredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AuthCallsCredentialListMappingInstance": + """ + Fetch the AuthCallsCredentialListMappingInstance + + + :returns: The fetched AuthCallsCredentialListMappingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AuthCallsCredentialListMappingInstance": + """ + Asynchronous coroutine to fetch the AuthCallsCredentialListMappingInstance + + + :returns: The fetched AuthCallsCredentialListMappingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.AuthCallsCredentialListMappingInstance {}>".format( + context + ) + + +class AuthCallsCredentialListMappingContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str): + """ + Initialize the AuthCallsCredentialListMappingContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resource to fetch. + :param domain_sid: The SID of the SIP domain that contains the resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the CredentialListMapping resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/Auth/Calls/CredentialListMappings/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the AuthCallsCredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AuthCallsCredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AuthCallsCredentialListMappingInstance: + """ + Fetch the AuthCallsCredentialListMappingInstance + + + :returns: The fetched AuthCallsCredentialListMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AuthCallsCredentialListMappingInstance: + """ + Asynchronous coroutine to fetch the AuthCallsCredentialListMappingInstance + + + :returns: The fetched AuthCallsCredentialListMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.AuthCallsCredentialListMappingContext {}>".format( + context + ) + + +class AuthCallsCredentialListMappingPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> AuthCallsCredentialListMappingInstance: + """ + Build an instance of AuthCallsCredentialListMappingInstance + + :param payload: Payload response from the API + """ + return AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AuthCallsCredentialListMappingPage>" + + +class AuthCallsCredentialListMappingList(ListResource): + + def __init__(self, version: Version, account_sid: str, domain_sid: str): + """ + Initialize the AuthCallsCredentialListMappingList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resources to read. + :param domain_sid: The SID of the SIP domain that contains the resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/Auth/Calls/CredentialListMappings.json".format( + **self._solution + ) + + def create( + self, credential_list_sid: str + ) -> AuthCallsCredentialListMappingInstance: + """ + Create the AuthCallsCredentialListMappingInstance + + :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. + + :returns: The created AuthCallsCredentialListMappingInstance + """ + + data = values.of( + { + "CredentialListSid": credential_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + async def create_async( + self, credential_list_sid: str + ) -> AuthCallsCredentialListMappingInstance: + """ + Asynchronously create the AuthCallsCredentialListMappingInstance + + :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. + + :returns: The created AuthCallsCredentialListMappingInstance + """ + + data = values.of( + { + "CredentialListSid": credential_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AuthCallsCredentialListMappingInstance]: + """ + Streams AuthCallsCredentialListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AuthCallsCredentialListMappingInstance]: + """ + Asynchronously streams AuthCallsCredentialListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthCallsCredentialListMappingInstance]: + """ + Lists AuthCallsCredentialListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthCallsCredentialListMappingInstance]: + """ + Asynchronously lists AuthCallsCredentialListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthCallsCredentialListMappingPage: + """ + Retrieve a single page of AuthCallsCredentialListMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthCallsCredentialListMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthCallsCredentialListMappingPage( + self._version, response, self._solution + ) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthCallsCredentialListMappingPage: + """ + Asynchronously retrieve a single page of AuthCallsCredentialListMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthCallsCredentialListMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthCallsCredentialListMappingPage( + self._version, response, self._solution + ) + + def get_page(self, target_url: str) -> AuthCallsCredentialListMappingPage: + """ + Retrieve a specific page of AuthCallsCredentialListMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthCallsCredentialListMappingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AuthCallsCredentialListMappingPage( + self._version, response, self._solution + ) + + async def get_page_async( + self, target_url: str + ) -> AuthCallsCredentialListMappingPage: + """ + Asynchronously retrieve a specific page of AuthCallsCredentialListMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthCallsCredentialListMappingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AuthCallsCredentialListMappingPage( + self._version, response, self._solution + ) + + def get(self, sid: str) -> AuthCallsCredentialListMappingContext: + """ + Constructs a AuthCallsCredentialListMappingContext + + :param sid: The Twilio-provided string that uniquely identifies the CredentialListMapping resource to fetch. + """ + return AuthCallsCredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AuthCallsCredentialListMappingContext: + """ + Constructs a AuthCallsCredentialListMappingContext + + :param sid: The Twilio-provided string that uniquely identifies the CredentialListMapping resource to fetch. + """ + return AuthCallsCredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AuthCallsCredentialListMappingList>" diff --git a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_ip_access_control_list_mapping.py b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_ip_access_control_list_mapping.py new file mode 100644 index 0000000000..198f4fc406 --- /dev/null +++ b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/auth_calls_ip_access_control_list_mapping.py @@ -0,0 +1,586 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AuthCallsIpAccessControlListMappingInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IpAccessControlListMapping resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar sid: The unique string that that we created to identify the IpAccessControlListMapping resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + domain_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid or self.sid, + } + self._context: Optional[AuthCallsIpAccessControlListMappingContext] = None + + @property + def _proxy(self) -> "AuthCallsIpAccessControlListMappingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AuthCallsIpAccessControlListMappingContext for this AuthCallsIpAccessControlListMappingInstance + """ + if self._context is None: + self._context = AuthCallsIpAccessControlListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AuthCallsIpAccessControlListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AuthCallsIpAccessControlListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AuthCallsIpAccessControlListMappingInstance": + """ + Fetch the AuthCallsIpAccessControlListMappingInstance + + + :returns: The fetched AuthCallsIpAccessControlListMappingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AuthCallsIpAccessControlListMappingInstance": + """ + Asynchronous coroutine to fetch the AuthCallsIpAccessControlListMappingInstance + + + :returns: The fetched AuthCallsIpAccessControlListMappingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return ( + "<Twilio.Api.V2010.AuthCallsIpAccessControlListMappingInstance {}>".format( + context + ) + ) + + +class AuthCallsIpAccessControlListMappingContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str): + """ + Initialize the AuthCallsIpAccessControlListMappingContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IpAccessControlListMapping resource to fetch. + :param domain_sid: The SID of the SIP domain that contains the resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the IpAccessControlListMapping resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/Auth/Calls/IpAccessControlListMappings/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the AuthCallsIpAccessControlListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AuthCallsIpAccessControlListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AuthCallsIpAccessControlListMappingInstance: + """ + Fetch the AuthCallsIpAccessControlListMappingInstance + + + :returns: The fetched AuthCallsIpAccessControlListMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AuthCallsIpAccessControlListMappingInstance: + """ + Asynchronous coroutine to fetch the AuthCallsIpAccessControlListMappingInstance + + + :returns: The fetched AuthCallsIpAccessControlListMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return ( + "<Twilio.Api.V2010.AuthCallsIpAccessControlListMappingContext {}>".format( + context + ) + ) + + +class AuthCallsIpAccessControlListMappingPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> AuthCallsIpAccessControlListMappingInstance: + """ + Build an instance of AuthCallsIpAccessControlListMappingInstance + + :param payload: Payload response from the API + """ + return AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AuthCallsIpAccessControlListMappingPage>" + + +class AuthCallsIpAccessControlListMappingList(ListResource): + + def __init__(self, version: Version, account_sid: str, domain_sid: str): + """ + Initialize the AuthCallsIpAccessControlListMappingList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IpAccessControlListMapping resources to read. + :param domain_sid: The SID of the SIP domain that contains the resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/Auth/Calls/IpAccessControlListMappings.json".format( + **self._solution + ) + + def create( + self, ip_access_control_list_sid: str + ) -> AuthCallsIpAccessControlListMappingInstance: + """ + Create the AuthCallsIpAccessControlListMappingInstance + + :param ip_access_control_list_sid: The SID of the IpAccessControlList resource to map to the SIP domain. + + :returns: The created AuthCallsIpAccessControlListMappingInstance + """ + + data = values.of( + { + "IpAccessControlListSid": ip_access_control_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + async def create_async( + self, ip_access_control_list_sid: str + ) -> AuthCallsIpAccessControlListMappingInstance: + """ + Asynchronously create the AuthCallsIpAccessControlListMappingInstance + + :param ip_access_control_list_sid: The SID of the IpAccessControlList resource to map to the SIP domain. + + :returns: The created AuthCallsIpAccessControlListMappingInstance + """ + + data = values.of( + { + "IpAccessControlListSid": ip_access_control_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AuthCallsIpAccessControlListMappingInstance]: + """ + Streams AuthCallsIpAccessControlListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AuthCallsIpAccessControlListMappingInstance]: + """ + Asynchronously streams AuthCallsIpAccessControlListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthCallsIpAccessControlListMappingInstance]: + """ + Lists AuthCallsIpAccessControlListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthCallsIpAccessControlListMappingInstance]: + """ + Asynchronously lists AuthCallsIpAccessControlListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthCallsIpAccessControlListMappingPage: + """ + Retrieve a single page of AuthCallsIpAccessControlListMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthCallsIpAccessControlListMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthCallsIpAccessControlListMappingPage( + self._version, response, self._solution + ) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthCallsIpAccessControlListMappingPage: + """ + Asynchronously retrieve a single page of AuthCallsIpAccessControlListMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthCallsIpAccessControlListMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthCallsIpAccessControlListMappingPage( + self._version, response, self._solution + ) + + def get_page(self, target_url: str) -> AuthCallsIpAccessControlListMappingPage: + """ + Retrieve a specific page of AuthCallsIpAccessControlListMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthCallsIpAccessControlListMappingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AuthCallsIpAccessControlListMappingPage( + self._version, response, self._solution + ) + + async def get_page_async( + self, target_url: str + ) -> AuthCallsIpAccessControlListMappingPage: + """ + Asynchronously retrieve a specific page of AuthCallsIpAccessControlListMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthCallsIpAccessControlListMappingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AuthCallsIpAccessControlListMappingPage( + self._version, response, self._solution + ) + + def get(self, sid: str) -> AuthCallsIpAccessControlListMappingContext: + """ + Constructs a AuthCallsIpAccessControlListMappingContext + + :param sid: The Twilio-provided string that uniquely identifies the IpAccessControlListMapping resource to fetch. + """ + return AuthCallsIpAccessControlListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AuthCallsIpAccessControlListMappingContext: + """ + Constructs a AuthCallsIpAccessControlListMappingContext + + :param sid: The Twilio-provided string that uniquely identifies the IpAccessControlListMapping resource to fetch. + """ + return AuthCallsIpAccessControlListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AuthCallsIpAccessControlListMappingList>" diff --git a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/__init__.py b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/__init__.py new file mode 100644 index 0000000000..c10c747378 --- /dev/null +++ b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/__init__.py @@ -0,0 +1,71 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.api.v2010.account.sip.domain.auth_types.auth_type_registrations.auth_registrations_credential_list_mapping import ( + AuthRegistrationsCredentialListMappingList, +) + + +class AuthTypeRegistrationsList(ListResource): + + def __init__(self, version: Version, account_sid: str, domain_sid: str): + """ + Initialize the AuthTypeRegistrationsList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resource to fetch. + :param domain_sid: The SID of the SIP domain that contains the resource to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/Auth/Registrations.json".format( + **self._solution + ) + + self._credential_list_mappings: Optional[ + AuthRegistrationsCredentialListMappingList + ] = None + + @property + def credential_list_mappings(self) -> AuthRegistrationsCredentialListMappingList: + """ + Access the credential_list_mappings + """ + if self._credential_list_mappings is None: + self._credential_list_mappings = AuthRegistrationsCredentialListMappingList( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + return self._credential_list_mappings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AuthTypeRegistrationsList>" diff --git a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/auth_registrations_credential_list_mapping.py b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/auth_registrations_credential_list_mapping.py new file mode 100644 index 0000000000..e4b1bf0d23 --- /dev/null +++ b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/auth_registrations_credential_list_mapping.py @@ -0,0 +1,582 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AuthRegistrationsCredentialListMappingInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar sid: The unique string that that we created to identify the CredentialListMapping resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + domain_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid or self.sid, + } + self._context: Optional[AuthRegistrationsCredentialListMappingContext] = None + + @property + def _proxy(self) -> "AuthRegistrationsCredentialListMappingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AuthRegistrationsCredentialListMappingContext for this AuthRegistrationsCredentialListMappingInstance + """ + if self._context is None: + self._context = AuthRegistrationsCredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AuthRegistrationsCredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AuthRegistrationsCredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AuthRegistrationsCredentialListMappingInstance": + """ + Fetch the AuthRegistrationsCredentialListMappingInstance + + + :returns: The fetched AuthRegistrationsCredentialListMappingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AuthRegistrationsCredentialListMappingInstance": + """ + Asynchronous coroutine to fetch the AuthRegistrationsCredentialListMappingInstance + + + :returns: The fetched AuthRegistrationsCredentialListMappingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.AuthRegistrationsCredentialListMappingInstance {}>".format( + context + ) + + +class AuthRegistrationsCredentialListMappingContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str): + """ + Initialize the AuthRegistrationsCredentialListMappingContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resource to fetch. + :param domain_sid: The SID of the SIP domain that contains the resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the CredentialListMapping resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/Auth/Registrations/CredentialListMappings/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the AuthRegistrationsCredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AuthRegistrationsCredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AuthRegistrationsCredentialListMappingInstance: + """ + Fetch the AuthRegistrationsCredentialListMappingInstance + + + :returns: The fetched AuthRegistrationsCredentialListMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AuthRegistrationsCredentialListMappingInstance: + """ + Asynchronous coroutine to fetch the AuthRegistrationsCredentialListMappingInstance + + + :returns: The fetched AuthRegistrationsCredentialListMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.AuthRegistrationsCredentialListMappingContext {}>".format( + context + ) + + +class AuthRegistrationsCredentialListMappingPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> AuthRegistrationsCredentialListMappingInstance: + """ + Build an instance of AuthRegistrationsCredentialListMappingInstance + + :param payload: Payload response from the API + """ + return AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AuthRegistrationsCredentialListMappingPage>" + + +class AuthRegistrationsCredentialListMappingList(ListResource): + + def __init__(self, version: Version, account_sid: str, domain_sid: str): + """ + Initialize the AuthRegistrationsCredentialListMappingList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resources to read. + :param domain_sid: The SID of the SIP domain that contains the resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/Auth/Registrations/CredentialListMappings.json".format( + **self._solution + ) + + def create( + self, credential_list_sid: str + ) -> AuthRegistrationsCredentialListMappingInstance: + """ + Create the AuthRegistrationsCredentialListMappingInstance + + :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. + + :returns: The created AuthRegistrationsCredentialListMappingInstance + """ + + data = values.of( + { + "CredentialListSid": credential_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + async def create_async( + self, credential_list_sid: str + ) -> AuthRegistrationsCredentialListMappingInstance: + """ + Asynchronously create the AuthRegistrationsCredentialListMappingInstance + + :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. + + :returns: The created AuthRegistrationsCredentialListMappingInstance + """ + + data = values.of( + { + "CredentialListSid": credential_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AuthRegistrationsCredentialListMappingInstance]: + """ + Streams AuthRegistrationsCredentialListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AuthRegistrationsCredentialListMappingInstance]: + """ + Asynchronously streams AuthRegistrationsCredentialListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthRegistrationsCredentialListMappingInstance]: + """ + Lists AuthRegistrationsCredentialListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthRegistrationsCredentialListMappingInstance]: + """ + Asynchronously lists AuthRegistrationsCredentialListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthRegistrationsCredentialListMappingPage: + """ + Retrieve a single page of AuthRegistrationsCredentialListMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthRegistrationsCredentialListMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthRegistrationsCredentialListMappingPage( + self._version, response, self._solution + ) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthRegistrationsCredentialListMappingPage: + """ + Asynchronously retrieve a single page of AuthRegistrationsCredentialListMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthRegistrationsCredentialListMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthRegistrationsCredentialListMappingPage( + self._version, response, self._solution + ) + + def get_page(self, target_url: str) -> AuthRegistrationsCredentialListMappingPage: + """ + Retrieve a specific page of AuthRegistrationsCredentialListMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthRegistrationsCredentialListMappingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AuthRegistrationsCredentialListMappingPage( + self._version, response, self._solution + ) + + async def get_page_async( + self, target_url: str + ) -> AuthRegistrationsCredentialListMappingPage: + """ + Asynchronously retrieve a specific page of AuthRegistrationsCredentialListMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthRegistrationsCredentialListMappingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AuthRegistrationsCredentialListMappingPage( + self._version, response, self._solution + ) + + def get(self, sid: str) -> AuthRegistrationsCredentialListMappingContext: + """ + Constructs a AuthRegistrationsCredentialListMappingContext + + :param sid: The Twilio-provided string that uniquely identifies the CredentialListMapping resource to fetch. + """ + return AuthRegistrationsCredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AuthRegistrationsCredentialListMappingContext: + """ + Constructs a AuthRegistrationsCredentialListMappingContext + + :param sid: The Twilio-provided string that uniquely identifies the CredentialListMapping resource to fetch. + """ + return AuthRegistrationsCredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AuthRegistrationsCredentialListMappingList>" diff --git a/twilio/rest/api/v2010/account/sip/domain/credential_list_mapping.py b/twilio/rest/api/v2010/account/sip/domain/credential_list_mapping.py new file mode 100644 index 0000000000..b520f4813a --- /dev/null +++ b/twilio/rest/api/v2010/account/sip/domain/credential_list_mapping.py @@ -0,0 +1,568 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CredentialListMappingInstance(InstanceResource): + """ + :ivar account_sid: The unique id of the Account that is responsible for this resource. + :ivar date_created: The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar date_updated: The date that this resource was last updated, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar domain_sid: The unique string that is created to identify the SipDomain resource. + :ivar friendly_name: A human readable descriptive text for this resource, up to 64 characters long. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar uri: The URI for this resource, relative to `https://api.twilio.com` + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + domain_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.domain_sid: Optional[str] = payload.get("domain_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid or self.sid, + } + self._context: Optional[CredentialListMappingContext] = None + + @property + def _proxy(self) -> "CredentialListMappingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CredentialListMappingContext for this CredentialListMappingInstance + """ + if self._context is None: + self._context = CredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CredentialListMappingInstance": + """ + Fetch the CredentialListMappingInstance + + + :returns: The fetched CredentialListMappingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialListMappingInstance": + """ + Asynchronous coroutine to fetch the CredentialListMappingInstance + + + :returns: The fetched CredentialListMappingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.CredentialListMappingInstance {}>".format(context) + + +class CredentialListMappingContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str): + """ + Initialize the CredentialListMappingContext + + :param version: Version that contains the resource + :param account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. + :param domain_sid: A 34 character string that uniquely identifies the SIP Domain that includes the resource to fetch. + :param sid: A 34 character string that uniquely identifies the resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/CredentialListMappings/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the CredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialListMappingInstance: + """ + Fetch the CredentialListMappingInstance + + + :returns: The fetched CredentialListMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialListMappingInstance: + """ + Asynchronous coroutine to fetch the CredentialListMappingInstance + + + :returns: The fetched CredentialListMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.CredentialListMappingContext {}>".format(context) + + +class CredentialListMappingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialListMappingInstance: + """ + Build an instance of CredentialListMappingInstance + + :param payload: Payload response from the API + """ + return CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.CredentialListMappingPage>" + + +class CredentialListMappingList(ListResource): + + def __init__(self, version: Version, account_sid: str, domain_sid: str): + """ + Initialize the CredentialListMappingList + + :param version: Version that contains the resource + :param account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. + :param domain_sid: A 34 character string that uniquely identifies the SIP Domain that includes the resource to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/CredentialListMappings.json".format( + **self._solution + ) + + def create(self, credential_list_sid: str) -> CredentialListMappingInstance: + """ + Create the CredentialListMappingInstance + + :param credential_list_sid: A 34 character string that uniquely identifies the CredentialList resource to map to the SIP domain. + + :returns: The created CredentialListMappingInstance + """ + + data = values.of( + { + "CredentialListSid": credential_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + async def create_async( + self, credential_list_sid: str + ) -> CredentialListMappingInstance: + """ + Asynchronously create the CredentialListMappingInstance + + :param credential_list_sid: A 34 character string that uniquely identifies the CredentialList resource to map to the SIP domain. + + :returns: The created CredentialListMappingInstance + """ + + data = values.of( + { + "CredentialListSid": credential_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialListMappingInstance]: + """ + Streams CredentialListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialListMappingInstance]: + """ + Asynchronously streams CredentialListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListMappingInstance]: + """ + Lists CredentialListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListMappingInstance]: + """ + Asynchronously lists CredentialListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialListMappingPage: + """ + Retrieve a single page of CredentialListMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialListMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialListMappingPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialListMappingPage: + """ + Asynchronously retrieve a single page of CredentialListMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialListMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialListMappingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> CredentialListMappingPage: + """ + Retrieve a specific page of CredentialListMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialListMappingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialListMappingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> CredentialListMappingPage: + """ + Asynchronously retrieve a specific page of CredentialListMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialListMappingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialListMappingPage(self._version, response, self._solution) + + def get(self, sid: str) -> CredentialListMappingContext: + """ + Constructs a CredentialListMappingContext + + :param sid: A 34 character string that uniquely identifies the resource to fetch. + """ + return CredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> CredentialListMappingContext: + """ + Constructs a CredentialListMappingContext + + :param sid: A 34 character string that uniquely identifies the resource to fetch. + """ + return CredentialListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.CredentialListMappingList>" diff --git a/twilio/rest/api/v2010/account/sip/domain/ip_access_control_list_mapping.py b/twilio/rest/api/v2010/account/sip/domain/ip_access_control_list_mapping.py new file mode 100644 index 0000000000..4dfecfe826 --- /dev/null +++ b/twilio/rest/api/v2010/account/sip/domain/ip_access_control_list_mapping.py @@ -0,0 +1,574 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class IpAccessControlListMappingInstance(InstanceResource): + """ + :ivar account_sid: The unique id of the Account that is responsible for this resource. + :ivar date_created: The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar date_updated: The date that this resource was last updated, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar domain_sid: The unique string that is created to identify the SipDomain resource. + :ivar friendly_name: A human readable descriptive text for this resource, up to 64 characters long. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar uri: The URI for this resource, relative to `https://api.twilio.com` + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + domain_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.domain_sid: Optional[str] = payload.get("domain_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid or self.sid, + } + self._context: Optional[IpAccessControlListMappingContext] = None + + @property + def _proxy(self) -> "IpAccessControlListMappingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: IpAccessControlListMappingContext for this IpAccessControlListMappingInstance + """ + if self._context is None: + self._context = IpAccessControlListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the IpAccessControlListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAccessControlListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "IpAccessControlListMappingInstance": + """ + Fetch the IpAccessControlListMappingInstance + + + :returns: The fetched IpAccessControlListMappingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "IpAccessControlListMappingInstance": + """ + Asynchronous coroutine to fetch the IpAccessControlListMappingInstance + + + :returns: The fetched IpAccessControlListMappingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.IpAccessControlListMappingInstance {}>".format( + context + ) + + +class IpAccessControlListMappingContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str): + """ + Initialize the IpAccessControlListMappingContext + + :param version: Version that contains the resource + :param account_sid: The unique id of the Account that is responsible for this resource. + :param domain_sid: A 34 character string that uniquely identifies the SIP domain. + :param sid: A 34 character string that uniquely identifies the resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/IpAccessControlListMappings/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the IpAccessControlListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAccessControlListMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpAccessControlListMappingInstance: + """ + Fetch the IpAccessControlListMappingInstance + + + :returns: The fetched IpAccessControlListMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> IpAccessControlListMappingInstance: + """ + Asynchronous coroutine to fetch the IpAccessControlListMappingInstance + + + :returns: The fetched IpAccessControlListMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.IpAccessControlListMappingContext {}>".format(context) + + +class IpAccessControlListMappingPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> IpAccessControlListMappingInstance: + """ + Build an instance of IpAccessControlListMappingInstance + + :param payload: Payload response from the API + """ + return IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.IpAccessControlListMappingPage>" + + +class IpAccessControlListMappingList(ListResource): + + def __init__(self, version: Version, account_sid: str, domain_sid: str): + """ + Initialize the IpAccessControlListMappingList + + :param version: Version that contains the resource + :param account_sid: The unique id of the Account that is responsible for this resource. + :param domain_sid: A 34 character string that uniquely identifies the SIP domain. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "domain_sid": domain_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/Domains/{domain_sid}/IpAccessControlListMappings.json".format( + **self._solution + ) + + def create( + self, ip_access_control_list_sid: str + ) -> IpAccessControlListMappingInstance: + """ + Create the IpAccessControlListMappingInstance + + :param ip_access_control_list_sid: The unique id of the IP access control list to map to the SIP domain. + + :returns: The created IpAccessControlListMappingInstance + """ + + data = values.of( + { + "IpAccessControlListSid": ip_access_control_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + async def create_async( + self, ip_access_control_list_sid: str + ) -> IpAccessControlListMappingInstance: + """ + Asynchronously create the IpAccessControlListMappingInstance + + :param ip_access_control_list_sid: The unique id of the IP access control list to map to the SIP domain. + + :returns: The created IpAccessControlListMappingInstance + """ + + data = values.of( + { + "IpAccessControlListSid": ip_access_control_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[IpAccessControlListMappingInstance]: + """ + Streams IpAccessControlListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpAccessControlListMappingInstance]: + """ + Asynchronously streams IpAccessControlListMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListMappingInstance]: + """ + Lists IpAccessControlListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListMappingInstance]: + """ + Asynchronously lists IpAccessControlListMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpAccessControlListMappingPage: + """ + Retrieve a single page of IpAccessControlListMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpAccessControlListMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAccessControlListMappingPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpAccessControlListMappingPage: + """ + Asynchronously retrieve a single page of IpAccessControlListMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpAccessControlListMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAccessControlListMappingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> IpAccessControlListMappingPage: + """ + Retrieve a specific page of IpAccessControlListMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpAccessControlListMappingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return IpAccessControlListMappingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> IpAccessControlListMappingPage: + """ + Asynchronously retrieve a specific page of IpAccessControlListMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpAccessControlListMappingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpAccessControlListMappingPage(self._version, response, self._solution) + + def get(self, sid: str) -> IpAccessControlListMappingContext: + """ + Constructs a IpAccessControlListMappingContext + + :param sid: A 34 character string that uniquely identifies the resource to fetch. + """ + return IpAccessControlListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> IpAccessControlListMappingContext: + """ + Constructs a IpAccessControlListMappingContext + + :param sid: A 34 character string that uniquely identifies the resource to fetch. + """ + return IpAccessControlListMappingContext( + self._version, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.IpAccessControlListMappingList>" diff --git a/twilio/rest/api/v2010/account/sip/ip_access_control_list/__init__.py b/twilio/rest/api/v2010/account/sip/ip_access_control_list/__init__.py new file mode 100644 index 0000000000..afa504c208 --- /dev/null +++ b/twilio/rest/api/v2010/account/sip/ip_access_control_list/__init__.py @@ -0,0 +1,657 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.sip.ip_access_control_list.ip_address import ( + IpAddressList, +) + + +class IpAccessControlListInstance(InstanceResource): + """ + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) that owns this resource. + :ivar friendly_name: A human readable descriptive text, up to 255 characters long. + :ivar date_created: The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar date_updated: The date that this resource was last updated, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar subresource_uris: A list of the IpAddress resources associated with this IP access control list resource. + :ivar uri: The URI for this resource, relative to `https://api.twilio.com` + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[IpAccessControlListContext] = None + + @property + def _proxy(self) -> "IpAccessControlListContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: IpAccessControlListContext for this IpAccessControlListInstance + """ + if self._context is None: + self._context = IpAccessControlListContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the IpAccessControlListInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "IpAccessControlListInstance": + """ + Fetch the IpAccessControlListInstance + + + :returns: The fetched IpAccessControlListInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "IpAccessControlListInstance": + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance + + + :returns: The fetched IpAccessControlListInstance + """ + return await self._proxy.fetch_async() + + def update(self, friendly_name: str) -> "IpAccessControlListInstance": + """ + Update the IpAccessControlListInstance + + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: The updated IpAccessControlListInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async(self, friendly_name: str) -> "IpAccessControlListInstance": + """ + Asynchronous coroutine to update the IpAccessControlListInstance + + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: The updated IpAccessControlListInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + @property + def ip_addresses(self) -> IpAddressList: + """ + Access the ip_addresses + """ + return self._proxy.ip_addresses + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.IpAccessControlListInstance {}>".format(context) + + +class IpAccessControlListContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the IpAccessControlListContext + + :param version: Version that contains the resource + :param account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. + :param sid: A 34 character string that uniquely identifies the resource to udpate. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = ( + "/Accounts/{account_sid}/SIP/IpAccessControlLists/{sid}.json".format( + **self._solution + ) + ) + + self._ip_addresses: Optional[IpAddressList] = None + + def delete(self) -> bool: + """ + Deletes the IpAccessControlListInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpAccessControlListInstance: + """ + Fetch the IpAccessControlListInstance + + + :returns: The fetched IpAccessControlListInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> IpAccessControlListInstance: + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance + + + :returns: The fetched IpAccessControlListInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update(self, friendly_name: str) -> IpAccessControlListInstance: + """ + Update the IpAccessControlListInstance + + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: The updated IpAccessControlListInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, friendly_name: str) -> IpAccessControlListInstance: + """ + Asynchronous coroutine to update the IpAccessControlListInstance + + :param friendly_name: A human readable descriptive text, up to 255 characters long. + + :returns: The updated IpAccessControlListInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + @property + def ip_addresses(self) -> IpAddressList: + """ + Access the ip_addresses + """ + if self._ip_addresses is None: + self._ip_addresses = IpAddressList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._ip_addresses + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.IpAccessControlListContext {}>".format(context) + + +class IpAccessControlListPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> IpAccessControlListInstance: + """ + Build an instance of IpAccessControlListInstance + + :param payload: Payload response from the API + """ + return IpAccessControlListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.IpAccessControlListPage>" + + +class IpAccessControlListList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the IpAccessControlListList + + :param version: Version that contains the resource + :param account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/IpAccessControlLists.json".format( + **self._solution + ) + + def create(self, friendly_name: str) -> IpAccessControlListInstance: + """ + Create the IpAccessControlListInstance + + :param friendly_name: A human readable descriptive text that describes the IpAccessControlList, up to 255 characters long. + + :returns: The created IpAccessControlListInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAccessControlListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async(self, friendly_name: str) -> IpAccessControlListInstance: + """ + Asynchronously create the IpAccessControlListInstance + + :param friendly_name: A human readable descriptive text that describes the IpAccessControlList, up to 255 characters long. + + :returns: The created IpAccessControlListInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAccessControlListInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[IpAccessControlListInstance]: + """ + Streams IpAccessControlListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpAccessControlListInstance]: + """ + Asynchronously streams IpAccessControlListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListInstance]: + """ + Lists IpAccessControlListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListInstance]: + """ + Asynchronously lists IpAccessControlListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpAccessControlListPage: + """ + Retrieve a single page of IpAccessControlListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpAccessControlListInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAccessControlListPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpAccessControlListPage: + """ + Asynchronously retrieve a single page of IpAccessControlListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpAccessControlListInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAccessControlListPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> IpAccessControlListPage: + """ + Retrieve a specific page of IpAccessControlListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpAccessControlListInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return IpAccessControlListPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> IpAccessControlListPage: + """ + Asynchronously retrieve a specific page of IpAccessControlListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpAccessControlListInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpAccessControlListPage(self._version, response, self._solution) + + def get(self, sid: str) -> IpAccessControlListContext: + """ + Constructs a IpAccessControlListContext + + :param sid: A 34 character string that uniquely identifies the resource to udpate. + """ + return IpAccessControlListContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> IpAccessControlListContext: + """ + Constructs a IpAccessControlListContext + + :param sid: A 34 character string that uniquely identifies the resource to udpate. + """ + return IpAccessControlListContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.IpAccessControlListList>" diff --git a/twilio/rest/api/v2010/account/sip/ip_access_control_list/ip_address.py b/twilio/rest/api/v2010/account/sip/ip_access_control_list/ip_address.py new file mode 100644 index 0000000000..ca2f82eacc --- /dev/null +++ b/twilio/rest/api/v2010/account/sip/ip_access_control_list/ip_address.py @@ -0,0 +1,724 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class IpAddressInstance(InstanceResource): + """ + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar account_sid: The unique id of the Account that is responsible for this resource. + :ivar friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :ivar ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :ivar cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + :ivar ip_access_control_list_sid: The unique id of the IpAccessControlList resource that includes this resource. + :ivar date_created: The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar date_updated: The date that this resource was last updated, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. + :ivar uri: The URI for this resource, relative to `https://api.twilio.com` + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + ip_access_control_list_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.ip_address: Optional[str] = payload.get("ip_address") + self.cidr_prefix_length: Optional[int] = deserialize.integer( + payload.get("cidr_prefix_length") + ) + self.ip_access_control_list_sid: Optional[str] = payload.get( + "ip_access_control_list_sid" + ) + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "ip_access_control_list_sid": ip_access_control_list_sid, + "sid": sid or self.sid, + } + self._context: Optional[IpAddressContext] = None + + @property + def _proxy(self) -> "IpAddressContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: IpAddressContext for this IpAddressInstance + """ + if self._context is None: + self._context = IpAddressContext( + self._version, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the IpAddressInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAddressInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "IpAddressInstance": + """ + Fetch the IpAddressInstance + + + :returns: The fetched IpAddressInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "IpAddressInstance": + """ + Asynchronous coroutine to fetch the IpAddressInstance + + + :returns: The fetched IpAddressInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> "IpAddressInstance": + """ + Update the IpAddressInstance + + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The updated IpAddressInstance + """ + return self._proxy.update( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + + async def update_async( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> "IpAddressInstance": + """ + Asynchronous coroutine to update the IpAddressInstance + + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The updated IpAddressInstance + """ + return await self._proxy.update_async( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.IpAddressInstance {}>".format(context) + + +class IpAddressContext(InstanceContext): + + def __init__( + self, + version: Version, + account_sid: str, + ip_access_control_list_sid: str, + sid: str, + ): + """ + Initialize the IpAddressContext + + :param version: Version that contains the resource + :param account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. + :param ip_access_control_list_sid: The IpAccessControlList Sid that identifies the IpAddress resources to update. + :param sid: A 34 character string that identifies the IpAddress resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "ip_access_control_list_sid": ip_access_control_list_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/SIP/IpAccessControlLists/{ip_access_control_list_sid}/IpAddresses/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the IpAddressInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAddressInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpAddressInstance: + """ + Fetch the IpAddressInstance + + + :returns: The fetched IpAddressInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> IpAddressInstance: + """ + Asynchronous coroutine to fetch the IpAddressInstance + + + :returns: The fetched IpAddressInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpAddressInstance: + """ + Update the IpAddressInstance + + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The updated IpAddressInstance + """ + + data = values.of( + { + "IpAddress": ip_address, + "FriendlyName": friendly_name, + "CidrPrefixLength": cidr_prefix_length, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + ip_address: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpAddressInstance: + """ + Asynchronous coroutine to update the IpAddressInstance + + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The updated IpAddressInstance + """ + + data = values.of( + { + "IpAddress": ip_address, + "FriendlyName": friendly_name, + "CidrPrefixLength": cidr_prefix_length, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.IpAddressContext {}>".format(context) + + +class IpAddressPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> IpAddressInstance: + """ + Build an instance of IpAddressInstance + + :param payload: Payload response from the API + """ + return IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.IpAddressPage>" + + +class IpAddressList(ListResource): + + def __init__( + self, version: Version, account_sid: str, ip_access_control_list_sid: str + ): + """ + Initialize the IpAddressList + + :param version: Version that contains the resource + :param account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. + :param ip_access_control_list_sid: The IpAccessControlList Sid that identifies the IpAddress resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "ip_access_control_list_sid": ip_access_control_list_sid, + } + self._uri = "/Accounts/{account_sid}/SIP/IpAccessControlLists/{ip_access_control_list_sid}/IpAddresses.json".format( + **self._solution + ) + + def create( + self, + friendly_name: str, + ip_address: str, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpAddressInstance: + """ + Create the IpAddressInstance + + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The created IpAddressInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "IpAddress": ip_address, + "CidrPrefixLength": cidr_prefix_length, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + ) + + async def create_async( + self, + friendly_name: str, + ip_address: str, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpAddressInstance: + """ + Asynchronously create the IpAddressInstance + + :param friendly_name: A human readable descriptive text for this resource, up to 255 characters long. + :param ip_address: An IP address in dotted decimal notation from which you want to accept traffic. Any SIP requests from this IP address will be allowed by Twilio. IPv4 only supported today. + :param cidr_prefix_length: An integer representing the length of the CIDR prefix to use with this IP address when accepting traffic. By default the entire IP address is used. + + :returns: The created IpAddressInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "IpAddress": ip_address, + "CidrPrefixLength": cidr_prefix_length, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[IpAddressInstance]: + """ + Streams IpAddressInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpAddressInstance]: + """ + Asynchronously streams IpAddressInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAddressInstance]: + """ + Lists IpAddressInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAddressInstance]: + """ + Asynchronously lists IpAddressInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpAddressPage: + """ + Retrieve a single page of IpAddressInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpAddressInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAddressPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpAddressPage: + """ + Asynchronously retrieve a single page of IpAddressInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpAddressInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAddressPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> IpAddressPage: + """ + Retrieve a specific page of IpAddressInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpAddressInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return IpAddressPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> IpAddressPage: + """ + Asynchronously retrieve a specific page of IpAddressInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpAddressInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpAddressPage(self._version, response, self._solution) + + def get(self, sid: str) -> IpAddressContext: + """ + Constructs a IpAddressContext + + :param sid: A 34 character string that identifies the IpAddress resource to update. + """ + return IpAddressContext( + self._version, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> IpAddressContext: + """ + Constructs a IpAddressContext + + :param sid: A 34 character string that identifies the IpAddress resource to update. + """ + return IpAddressContext( + self._version, + account_sid=self._solution["account_sid"], + ip_access_control_list_sid=self._solution["ip_access_control_list_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.IpAddressList>" diff --git a/twilio/rest/api/v2010/account/token.py b/twilio/rest/api/v2010/account/token.py new file mode 100644 index 0000000000..fa43360fb1 --- /dev/null +++ b/twilio/rest/api/v2010/account/token.py @@ -0,0 +1,146 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TokenInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Token resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar ice_servers: An array representing the ephemeral credentials and the STUN and TURN server URIs. + :ivar password: The temporary password that the username will use when authenticating with Twilio. + :ivar ttl: The duration in seconds for which the username and password are valid. + :ivar username: The temporary username that uniquely identifies a Token. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.ice_servers: Optional[List[str]] = payload.get("ice_servers") + self.password: Optional[str] = payload.get("password") + self.ttl: Optional[str] = payload.get("ttl") + self.username: Optional[str] = payload.get("username") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.TokenInstance {}>".format(context) + + +class TokenList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the TokenList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that will create the resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Tokens.json".format(**self._solution) + + def create(self, ttl: Union[int, object] = values.unset) -> TokenInstance: + """ + Create the TokenInstance + + :param ttl: The duration in seconds for which the generated credentials are valid. The default value is 86400 (24 hours). + + :returns: The created TokenInstance + """ + + data = values.of( + { + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TokenInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, ttl: Union[int, object] = values.unset + ) -> TokenInstance: + """ + Asynchronously create the TokenInstance + + :param ttl: The duration in seconds for which the generated credentials are valid. The default value is 86400 (24 hours). + + :returns: The created TokenInstance + """ + + data = values.of( + { + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TokenInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.TokenList>" diff --git a/twilio/rest/api/v2010/account/transcription.py b/twilio/rest/api/v2010/account/transcription.py new file mode 100644 index 0000000000..386ff9ee74 --- /dev/null +++ b/twilio/rest/api/v2010/account/transcription.py @@ -0,0 +1,504 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TranscriptionInstance(InstanceResource): + + class Status(object): + IN_PROGRESS = "in-progress" + COMPLETED = "completed" + FAILED = "failed" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Transcription resource. + :ivar api_version: The API version used to create the transcription. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar duration: The duration of the transcribed audio in seconds. + :ivar price: The charge for the transcript in the currency associated with the account. This value is populated after the transcript is complete so it may not be available immediately. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar recording_sid: The SID of the [Recording](https://www.twilio.com/docs/voice/api/recording) from which the transcription was created. + :ivar sid: The unique string that that we created to identify the Transcription resource. + :ivar status: + :ivar transcription_text: The text content of the transcription. + :ivar type: The transcription type. Can only be: `fast`. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.duration: Optional[str] = payload.get("duration") + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.recording_sid: Optional[str] = payload.get("recording_sid") + self.sid: Optional[str] = payload.get("sid") + self.status: Optional["TranscriptionInstance.Status"] = payload.get("status") + self.transcription_text: Optional[str] = payload.get("transcription_text") + self.type: Optional[str] = payload.get("type") + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[TranscriptionContext] = None + + @property + def _proxy(self) -> "TranscriptionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TranscriptionContext for this TranscriptionInstance + """ + if self._context is None: + self._context = TranscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TranscriptionInstance": + """ + Fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TranscriptionInstance": + """ + Asynchronous coroutine to fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.TranscriptionInstance {}>".format(context) + + +class TranscriptionContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the TranscriptionContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Transcription resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Transcription resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Transcriptions/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TranscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TranscriptionInstance: + """ + Fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TranscriptionInstance: + """ + Asynchronous coroutine to fetch the TranscriptionInstance + + + :returns: The fetched TranscriptionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.TranscriptionContext {}>".format(context) + + +class TranscriptionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TranscriptionInstance: + """ + Build an instance of TranscriptionInstance + + :param payload: Payload response from the API + """ + return TranscriptionInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.TranscriptionPage>" + + +class TranscriptionList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the TranscriptionList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Transcription resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Transcriptions.json".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TranscriptionInstance]: + """ + Streams TranscriptionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TranscriptionInstance]: + """ + Asynchronously streams TranscriptionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptionInstance]: + """ + Lists TranscriptionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptionInstance]: + """ + Asynchronously lists TranscriptionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TranscriptionPage: + """ + Retrieve a single page of TranscriptionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TranscriptionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TranscriptionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TranscriptionPage: + """ + Asynchronously retrieve a single page of TranscriptionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TranscriptionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TranscriptionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TranscriptionPage: + """ + Retrieve a specific page of TranscriptionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TranscriptionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TranscriptionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TranscriptionPage: + """ + Asynchronously retrieve a specific page of TranscriptionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TranscriptionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TranscriptionPage(self._version, response, self._solution) + + def get(self, sid: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param sid: The Twilio-provided string that uniquely identifies the Transcription resource to fetch. + """ + return TranscriptionContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param sid: The Twilio-provided string that uniquely identifies the Transcription resource to fetch. + """ + return TranscriptionContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.TranscriptionList>" diff --git a/twilio/rest/api/v2010/account/usage/__init__.py b/twilio/rest/api/v2010/account/usage/__init__.py new file mode 100644 index 0000000000..8fe80f64ba --- /dev/null +++ b/twilio/rest/api/v2010/account/usage/__init__.py @@ -0,0 +1,74 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.api.v2010.account.usage.record import RecordList +from twilio.rest.api.v2010.account.usage.trigger import TriggerList + + +class UsageList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the UsageList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage.json".format(**self._solution) + + self._records: Optional[RecordList] = None + self._triggers: Optional[TriggerList] = None + + @property + def records(self) -> RecordList: + """ + Access the records + """ + if self._records is None: + self._records = RecordList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._records + + @property + def triggers(self) -> TriggerList: + """ + Access the triggers + """ + if self._triggers is None: + self._triggers = TriggerList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._triggers + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.UsageList>" diff --git a/twilio/rest/api/v2010/account/usage/record/__init__.py b/twilio/rest/api/v2010/account/usage/record/__init__.py new file mode 100644 index 0000000000..d60bde9b6b --- /dev/null +++ b/twilio/rest/api/v2010/account/usage/record/__init__.py @@ -0,0 +1,1316 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.api.v2010.account.usage.record.all_time import AllTimeList +from twilio.rest.api.v2010.account.usage.record.daily import DailyList +from twilio.rest.api.v2010.account.usage.record.last_month import LastMonthList +from twilio.rest.api.v2010.account.usage.record.monthly import MonthlyList +from twilio.rest.api.v2010.account.usage.record.this_month import ThisMonthList +from twilio.rest.api.v2010.account.usage.record.today import TodayList +from twilio.rest.api.v2010.account.usage.record.yearly import YearlyList +from twilio.rest.api.v2010.account.usage.record.yesterday import YesterdayList + + +class RecordInstance(InstanceResource): + + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" + AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" + ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" + AUTHY_AUTHENTICATIONS = "authy-authentications" + AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" + AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" + AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" + AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" + AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" + CALL_PROGESS_EVENTS = "call-progess-events" + CALLERIDLOOKUPS = "calleridlookups" + CALLS = "calls" + CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" + CALLS_GLOBALCONFERENCE = "calls-globalconference" + CALLS_INBOUND = "calls-inbound" + CALLS_INBOUND_LOCAL = "calls-inbound-local" + CALLS_INBOUND_MOBILE = "calls-inbound-mobile" + CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" + CALLS_OUTBOUND = "calls-outbound" + CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" + CALLS_RECORDINGS = "calls-recordings" + CALLS_SIP = "calls-sip" + CALLS_SIP_INBOUND = "calls-sip-inbound" + CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" + CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" + CONVERSATIONS = "conversations" + CONVERSATIONS_API_REQUESTS = "conversations-api-requests" + CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" + CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" + CONVERSATIONS_EVENTS = "conversations-events" + CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" + CONVERSATIONS_PARTICIPANTS = "conversations-participants" + CPS = "cps" + CREDIT_TRANSFER = "credit-transfer" + EMAIL = "email" + EMERGING_TECH = "emerging-tech" + ENGAGEMENT_SUITE_PACKAGED_PLANS = "engagement-suite-packaged-plans" + ENHANCED_LINE_TYPE_LOOKUPS = "enhanced-line-type-lookups" + ENTERPRISE = "enterprise" + EVENTS = "events" + EXPERIMENT_FRANCE_SMS = "experiment-france-sms" + EXPERIMENT_INDIA_SMS = "experiment-india-sms" + EXPERIMENT_UK_SMS = "experiment-uk-sms" + FAILED_MESSAGE_PROCESSING_FEE = "failed-message-processing-fee" + FLEX = "flex" + FLEX_ACTIVE_USER_HOURS = "flex-active-user-hours" + FLEX_CONCURRENT_USERS = "flex-concurrent-users" + FLEX_CONVERSATIONAL_INSIGHTS = "flex-conversational-insights" + FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES = "flex-conversational-insights-messages" + FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = ( + "flex-conversational-insights-voice-minutes" + ) + FLEX_EMAIL_USAGE = "flex-email-usage" + FLEX_MESSAGING_USAGE = "flex-messaging-usage" + FLEX_PARTNER_SPINSCI = "flex-partner-spinsci" + FLEX_PARTNER_XCELERATE = "flex-partner-xcelerate" + FLEX_RESELLER_ECOSYSTEM = "flex-reseller-ecosystem" + FLEX_UNIQUE_USER = "flex-unique-user" + FLEX_USAGE = "flex-usage" + FLEX_USERS = "flex-users" + FLEX_VOICE_MINUTE = "flex-voice-minute" + FLEX_YTICA = "flex-ytica" + FRAUD_LOOKUPS = "fraud-lookups" + FRONTLINE = "frontline" + FRONTLINE_USERS = "frontline-users" + FUNCTIONS = "functions" + GENERIC_PAY_TRANSACTIONS = "generic-pay-transactions" + GROUP_ROOMS = "group-rooms" + GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" + GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" + GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" + GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" + GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" + GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" + GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" + GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" + IP_MESSAGING = "ip-messaging" + IP_MESSAGING_COMMANDS = "ip-messaging-commands" + IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" + IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" + IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" + IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" + IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" + LINE_STATUS_LOOKUPS = "line-status-lookups" + LIVE_ACTIVITY_LOOKUPS = "live-activity-lookups" + LOOKUP_BUCKET_ADJUSTMENT = "lookup-bucket-adjustment" + LOOKUP_IDENTITY_MATCH = "lookup-identity-match" + LOOKUPS = "lookups" + MARKETPLACE = "marketplace" + MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) + MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" + MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" + MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" + MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" + MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION = "marketplace-deepgram-transcription" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE = ( + "marketplace-deepgram-transcription-base" + ) + MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED = ( + "marketplace-deepgram-transscription-enhanced" + ) + MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( + "marketplace-digital-segment-business-info" + ) + MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( + "marketplace-facebook-offline-conversions" + ) + MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" + MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( + "marketplace-ibm-watson-message-insights" + ) + MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( + "marketplace-ibm-watson-message-sentiment" + ) + MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( + "marketplace-ibm-watson-recording-analysis" + ) + MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" + MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" + MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( + "marketplace-infogroup-dataaxle-bizinfo" + ) + MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( + "marketplace-keen-io-contact-center-analytics" + ) + MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" + MARKETPLACE_MARCHEX_RECORDING_ANALYSIS = ( + "marketplace-marchex-recording-analysis" + ) + MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( + "marketplace-marchex-sentiment-analysis-for-sms" + ) + MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( + "marketplace-marketplace-nextcaller-social-id" + ) + MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( + "marketplace-mobile-commons-opt-out-classifier" + ) + MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( + "marketplace-nexiwave-voicemail-to-text" + ) + MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( + "marketplace-nextcaller-advanced-caller-identification" + ) + MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" + MARKETPLACE_PAY_ADDONS = "marketplace-pay-addons" + MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR = ( + "marketplace-pay-addons-basecommerce-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR = ( + "marketplace-pay-addons-braintree-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR = ( + "marketplace-pay-addons-cardconnect-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR = ( + "marketplace-pay-addons-chase-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplace-pay-addons-shuttle-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplace-pay-addons-stripe-pay-connector" + ) + MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" + MARKETPLACE_POLY_AI_CONNECTOR = "marketplace-poly-ai-connector" + MARKETPLACE_REALPHONEVALIDATION = "marketplace-realphonevalidation" + MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( + "marketplace-remeeting-automatic-speech-recognition" + ) + MARKETPLACE_SPOKE_PHONE_LICENSE_PRO = "marketplace-spoke-phone-license-pro" + MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD = ( + "marketplace-spoke-phone-license-standard" + ) + MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( + "marketplace-tcpa-defense-solutions-blacklist-feed" + ) + MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" + MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION = ( + "marketplace-trestle-solutions-caller-identification" + ) + MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" + MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( + "marketplace-twilio-caller-name-lookup-us" + ) + MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( + "marketplace-twilio-carrier-information-lookup" + ) + MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" + MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" + MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) + MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" + MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( + "marketplace-ytica-contact-center-reporting-analytics" + ) + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplay-pay-addons-shuttle-pay-connector" + ) + MEDIA_COMPOSER_MINUTES = "media-composer-minutes" + MEDIASTORAGE = "mediastorage" + MIN_SPEND_ADJUSTMENTS = "min-spend-adjustments" + MMS = "mms" + MMS_INBOUND = "mms-inbound" + MMS_INBOUND_LONGCODE = "mms-inbound-longcode" + MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" + MMS_INBOUND_TOLL_FREE = "mms-inbound-toll-free" + MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" + MMS_OUTBOUND = "mms-outbound" + MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" + MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" + MMS_OUTBOUND_TOLLFREE = "mms-outbound-tollfree" + MONITOR = "monitor" + MONITOR_READS = "monitor-reads" + MONITOR_STORAGE = "monitor-storage" + MONITOR_WRITES = "monitor-writes" + NOTIFY = "notify" + NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" + NOTIFY_CHANNELS = "notify-channels" + NUMBER_FORMAT_LOOKUPS = "number-format-lookups" + PCHAT = "pchat" + PCHAT_ACTIONS = "pchat-actions" + PCHAT_APS = "pchat-aps" + PCHAT_CONV_MED_STORAGE = "pchat-conv-med-storage" + PCHAT_MESSAGES = "pchat-messages" + PCHAT_NOTIFICATIONS = "pchat-notifications" + PCHAT_READS = "pchat-reads" + PCHAT_USERS = "pchat-users" + PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "peer-to-peer-rooms-participant-minutes" + ) + PFAX = "pfax" + PFAX_MINUTES = "pfax-minutes" + PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" + PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" + PFAX_PAGES = "pfax-pages" + PHONE_QUALITY_SCORE_LOOKUPS = "phone-quality-score-lookups" + PHONENUMBERS = "phonenumbers" + PHONENUMBERS_CPS = "phonenumbers-cps" + PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" + PHONENUMBERS_LOCAL = "phonenumbers-local" + PHONENUMBERS_MOBILE = "phonenumbers-mobile" + PHONENUMBERS_PORTING = "phonenumbers-porting" + PHONENUMBERS_SETUPS = "phonenumbers-setups" + PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" + PREMIUMSUPPORT = "premiumsupport" + PREMIUMSUPPORT_PERCENTAGE_SPEND = "premiumsupport-percentage-spend" + PROGRAMMABLEVOICE_PLATFORM = "programmablevoice-platform" + PROGRAMMABLEVOICECONN_CLIENTSDK = "programmablevoiceconn-clientsdk" + PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND = ( + "programmablevoiceconn-clientsdk-inbound" + ) + PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND = ( + "programmablevoiceconn-clientsdk-outbound" + ) + PROGRAMMABLEVOICECONN_ONNET = "programmablevoiceconn-onnet" + PROGRAMMABLEVOICECONN_ONNET_INBOUND = "programmablevoiceconn-onnet-inbound" + PROGRAMMABLEVOICECONN_ONNET_OUTBOUND = "programmablevoiceconn-onnet-outbound" + PROGRAMMABLEVOICECONN_SIP = "programmablevoiceconn-sip" + PROGRAMMABLEVOICECONN_SIP_INBOUND = "programmablevoiceconn-sip-inbound" + PROGRAMMABLEVOICECONN_SIP_OUTBOUND = "programmablevoiceconn-sip-outbound" + PROGRAMMABLEVOICECONNECTIVITY = "programmablevoiceconnectivity" + PROXY = "proxy" + PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" + PROXY_BUCKET_ADJUSTMENT = "proxy-bucket-adjustment" + PROXY_LICENSES = "proxy-licenses" + PSTNCONNECTIVITY = "pstnconnectivity" + PSTNCONNECTIVITY_INBOUND = "pstnconnectivity-inbound" + PSTNCONNECTIVITY_OUTBOUND = "pstnconnectivity-outbound" + PV = "pv" + PV_BASIC_ROOMS = "pv-basic-rooms" + PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" + PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" + PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" + PV_COMPOSITION_MINUTES = "pv-composition-minutes" + PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" + PV_ROOM_PARTICIPANTS = "pv-room-participants" + PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" + PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" + PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" + PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" + PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" + PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" + PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" + PV_ROOMS = "pv-rooms" + PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" + RCS_MESSAGES = "rcs-messages" + REASSIGNED_NUMBER = "reassigned-number" + RECORDINGS = "recordings" + RECORDINGSTORAGE = "recordingstorage" + SHORTCODES = "shortcodes" + SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" + SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" + SHORTCODES_MPS = "shortcodes-mps" + SHORTCODES_RANDOM = "shortcodes-random" + SHORTCODES_SETUP_FEES = "shortcodes-setup-fees" + SHORTCODES_UK = "shortcodes-uk" + SHORTCODES_VANITY = "shortcodes-vanity" + SIM_SWAP_LOOKUPS = "sim-swap-lookups" + SIP_SECURE_MEDIA = "sip-secure-media" + SMALL_GROUP_ROOMS = "small-group-rooms" + SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" + SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" + SMS = "sms" + SMS_INBOUND = "sms-inbound" + SMS_INBOUND_LONGCODE = "sms-inbound-longcode" + SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" + SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" + SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) + SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" + SMS_OUTBOUND = "sms-outbound" + SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" + SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" + SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" + SPEECH_RECOGNITION = "speech-recognition" + STUDIO_ENGAGEMENTS = "studio-engagements" + SYNC = "sync" + SYNC_ACTIONS = "sync-actions" + SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" + SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" + TASKROUTER_TASKS = "taskrouter-tasks" + TOTALPRICE = "totalprice" + TRANSCRIPTIONS = "transcriptions" + TRUNKING_CPS = "trunking-cps" + TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" + TRUNKING_ORIGINATION = "trunking-origination" + TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" + TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" + TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" + TRUNKING_RECORDINGS = "trunking-recordings" + TRUNKING_SECURE = "trunking-secure" + TRUNKING_TERMINATION = "trunking-termination" + TTS_GOOGLE = "tts-google" + TURNMEGABYTES = "turnmegabytes" + TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" + TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" + TURNMEGABYTES_GERMANY = "turnmegabytes-germany" + TURNMEGABYTES_INDIA = "turnmegabytes-india" + TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" + TURNMEGABYTES_JAPAN = "turnmegabytes-japan" + TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" + TURNMEGABYTES_USEAST = "turnmegabytes-useast" + TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" + TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) + VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" + VOICE_INSIGHTS = "voice-insights" + VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-client-insights-on-demand-minute" + ) + VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-ptsn-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-interface-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-trunking-insights-on-demand-minute" + ) + VOICE_INTELLIGENCE = "voice-intelligence" + VOICE_INTELLIGENCE_EIP_OPERATORS = "voice-intelligence-eip-operators" + VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" + VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" + WDS = "wds" + WIRELESS = "wireless" + WIRELESS_DATA = "wireless-data" + WIRELESS_DATA_PAYG = "wireless-data-payg" + WIRELESS_DATA_PAYG_AFRICA = "wireless-data-payg-africa" + WIRELESS_DATA_PAYG_ASIA = "wireless-data-payg-asia" + WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA = ( + "wireless-data-payg-centralandsouthamerica" + ) + WIRELESS_DATA_PAYG_EUROPE = "wireless-data-payg-europe" + WIRELESS_DATA_PAYG_NORTHAMERICA = "wireless-data-payg-northamerica" + WIRELESS_DATA_PAYG_OCEANIA = "wireless-data-payg-oceania" + WIRELESS_DATA_QUOTA1 = "wireless-data-quota1" + WIRELESS_DATA_QUOTA1_AFRICA = "wireless-data-quota1-africa" + WIRELESS_DATA_QUOTA1_ASIA = "wireless-data-quota1-asia" + WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota1-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA1_EUROPE = "wireless-data-quota1-europe" + WIRELESS_DATA_QUOTA1_NORTHAMERICA = "wireless-data-quota1-northamerica" + WIRELESS_DATA_QUOTA1_OCEANIA = "wireless-data-quota1-oceania" + WIRELESS_DATA_QUOTA10 = "wireless-data-quota10" + WIRELESS_DATA_QUOTA10_AFRICA = "wireless-data-quota10-africa" + WIRELESS_DATA_QUOTA10_ASIA = "wireless-data-quota10-asia" + WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota10-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA10_EUROPE = "wireless-data-quota10-europe" + WIRELESS_DATA_QUOTA10_NORTHAMERICA = "wireless-data-quota10-northamerica" + WIRELESS_DATA_QUOTA10_OCEANIA = "wireless-data-quota10-oceania" + WIRELESS_DATA_QUOTA50 = "wireless-data-quota50" + WIRELESS_DATA_QUOTA50_AFRICA = "wireless-data-quota50-africa" + WIRELESS_DATA_QUOTA50_ASIA = "wireless-data-quota50-asia" + WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota50-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA50_EUROPE = "wireless-data-quota50-europe" + WIRELESS_DATA_QUOTA50_NORTHAMERICA = "wireless-data-quota50-northamerica" + WIRELESS_DATA_QUOTA50_OCEANIA = "wireless-data-quota50-oceania" + WIRELESS_DATA_QUOTACUSTOM = "wireless-data-quotacustom" + WIRELESS_DATA_QUOTACUSTOM_AFRICA = "wireless-data-quotacustom-africa" + WIRELESS_DATA_QUOTACUSTOM_ASIA = "wireless-data-quotacustom-asia" + WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quotacustom-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_EUROPE = "wireless-data-quotacustom-europe" + WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA = ( + "wireless-data-quotacustom-northamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_OCEANIA = "wireless-data-quotacustom-oceania" + WIRELESS_MRC_PAYG = "wireless-mrc-payg" + WIRELESS_MRC_QUOTA1 = "wireless-mrc-quota1" + WIRELESS_MRC_QUOTA10 = "wireless-mrc-quota10" + WIRELESS_MRC_QUOTA50 = "wireless-mrc-quota50" + WIRELESS_MRC_QUOTACUSTOM = "wireless-mrc-quotacustom" + WIRELESS_ORDERS = "wireless-orders" + WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" + WIRELESS_ORDERS_BULK = "wireless-orders-bulk" + WIRELESS_ORDERS_ESIM = "wireless-orders-esim" + WIRELESS_ORDERS_STARTER = "wireless-orders-starter" + WIRELESS_QUOTAS = "wireless-quotas" + WIRELESS_SMS_AFRICA = "wireless-sms-africa" + WIRELESS_SMS_ASIA = "wireless-sms-asia" + WIRELESS_SMS_CENTRALANDSOUTHAMERICA = "wireless-sms-centralandsouthamerica" + WIRELESS_SMS_EUROPE = "wireless-sms-europe" + WIRELESS_SMS_NORTHAMERICA = "wireless-sms-northamerica" + WIRELESS_SMS_OCEANIA = "wireless-sms-oceania" + WIRELESS_SUPER_SIM = "wireless-super-sim" + WIRELESS_SUPER_SIM_DATA = "wireless-super-sim-data" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA = ( + "wireless-super-sim-data-north-america-usa" + ) + WIRELESS_SUPER_SIM_DATA_PAYG = "wireless-super-sim-data-payg" + WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE = "wireless-super-sim-data-payg-europe" + WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA = ( + "wireless-super-sim-data-payg-north-america" + ) + WIRELESS_SUPER_SIM_HARDWARE = "wireless-super-sim-hardware" + WIRELESS_SUPER_SIM_HARDWARE_BULK = "wireless-super-sim-hardware-bulk" + WIRELESS_SUPER_SIM_SMSCOMMANDS = "wireless-super-sim-smscommands" + WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA = "wireless-super-sim-smscommands-africa" + WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA = "wireless-super-sim-smscommands-asia" + WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA = ( + "wireless-super-sim-smscommands-cent-and-south-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE = "wireless-super-sim-smscommands-europe" + WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA = ( + "wireless-super-sim-smscommands-north-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA = ( + "wireless-super-sim-smscommands-oceania" + ) + WIRELESS_SUPER_SIM_SUBSCRIPTION = "wireless-super-sim-subscription" + WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG = "wireless-super-sim-subscription-payg" + WIRELESS_USAGE = "wireless-usage" + WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" + WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" + WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" + WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-commands-centralandsouthamerica" + ) + WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" + WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" + WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" + WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" + WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" + WIRELESS_USAGE_DATA = "wireless-usage-data" + WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" + WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" + WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-data-centralandsouthamerica" + ) + WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( + "wireless-usage-data-custom-additionalmb" + ) + WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" + WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" + WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" + WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( + "wireless-usage-data-individual-additionalgb" + ) + WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( + "wireless-usage-data-individual-firstgb" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( + "wireless-usage-data-international-roaming-canada" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( + "wireless-usage-data-international-roaming-india" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( + "wireless-usage-data-international-roaming-mexico" + ) + WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" + WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" + WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" + WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" + WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" + WIRELESS_USAGE_MRC = "wireless-usage-mrc" + WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" + WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" + WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" + WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" + WIRELESS_USAGE_SMS = "wireless-usage-sms" + WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + :ivar api_version: The API version used to create the resource. + :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + :ivar category: + :ivar count: The number of usage events, such as the number of calls. + :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + :ivar description: A plain-language description of the usage category. + :ivar end_date: The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar price: The total price of the usage in the currency specified in `price_unit` and associated with the account. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + :ivar start_date: The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar subresource_uris: A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage: The amount used to bill usage and measured in units described in `usage_unit`. + :ivar usage_unit: The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.as_of: Optional[str] = payload.get("as_of") + self.category: Optional["RecordInstance.Category"] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.RecordInstance {}>".format(context) + + +class RecordPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RecordInstance: + """ + Build an instance of RecordInstance + + :param payload: Payload response from the API + """ + return RecordInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.RecordPage>" + + +class RecordList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the RecordList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records.json".format( + **self._solution + ) + + self._all_time: Optional[AllTimeList] = None + self._daily: Optional[DailyList] = None + self._last_month: Optional[LastMonthList] = None + self._monthly: Optional[MonthlyList] = None + self._this_month: Optional[ThisMonthList] = None + self._today: Optional[TodayList] = None + self._yearly: Optional[YearlyList] = None + self._yesterday: Optional[YesterdayList] = None + + def stream( + self, + category: Union["RecordInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RecordInstance]: + """ + Streams RecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "RecordInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + category: Union["RecordInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RecordInstance]: + """ + Asynchronously streams RecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "RecordInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["RecordInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordInstance]: + """ + Lists RecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RecordInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + category: Union["RecordInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordInstance]: + """ + Asynchronously lists RecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RecordInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + category: Union["RecordInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordPage: + """ + Retrieve a single page of RecordInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordPage(self._version, response, self._solution) + + async def page_async( + self, + category: Union["RecordInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordPage: + """ + Asynchronously retrieve a single page of RecordInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RecordPage: + """ + Retrieve a specific page of RecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RecordPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RecordPage: + """ + Asynchronously retrieve a specific page of RecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RecordPage(self._version, response, self._solution) + + @property + def all_time(self) -> AllTimeList: + """ + Access the all_time + """ + if self._all_time is None: + self._all_time = AllTimeList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._all_time + + @property + def daily(self) -> DailyList: + """ + Access the daily + """ + if self._daily is None: + self._daily = DailyList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._daily + + @property + def last_month(self) -> LastMonthList: + """ + Access the last_month + """ + if self._last_month is None: + self._last_month = LastMonthList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._last_month + + @property + def monthly(self) -> MonthlyList: + """ + Access the monthly + """ + if self._monthly is None: + self._monthly = MonthlyList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._monthly + + @property + def this_month(self) -> ThisMonthList: + """ + Access the this_month + """ + if self._this_month is None: + self._this_month = ThisMonthList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._this_month + + @property + def today(self) -> TodayList: + """ + Access the today + """ + if self._today is None: + self._today = TodayList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._today + + @property + def yearly(self) -> YearlyList: + """ + Access the yearly + """ + if self._yearly is None: + self._yearly = YearlyList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._yearly + + @property + def yesterday(self) -> YesterdayList: + """ + Access the yesterday + """ + if self._yesterday is None: + self._yesterday = YesterdayList( + self._version, account_sid=self._solution["account_sid"] + ) + return self._yesterday + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.RecordList>" diff --git a/twilio/rest/api/v2010/account/usage/record/all_time.py b/twilio/rest/api/v2010/account/usage/record/all_time.py new file mode 100644 index 0000000000..991f4a0b70 --- /dev/null +++ b/twilio/rest/api/v2010/account/usage/record/all_time.py @@ -0,0 +1,1211 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AllTimeInstance(InstanceResource): + + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" + AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" + ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" + AUTHY_AUTHENTICATIONS = "authy-authentications" + AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" + AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" + AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" + AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" + AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" + CALL_PROGESS_EVENTS = "call-progess-events" + CALLERIDLOOKUPS = "calleridlookups" + CALLS = "calls" + CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" + CALLS_GLOBALCONFERENCE = "calls-globalconference" + CALLS_INBOUND = "calls-inbound" + CALLS_INBOUND_LOCAL = "calls-inbound-local" + CALLS_INBOUND_MOBILE = "calls-inbound-mobile" + CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" + CALLS_OUTBOUND = "calls-outbound" + CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" + CALLS_RECORDINGS = "calls-recordings" + CALLS_SIP = "calls-sip" + CALLS_SIP_INBOUND = "calls-sip-inbound" + CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" + CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" + CONVERSATIONS = "conversations" + CONVERSATIONS_API_REQUESTS = "conversations-api-requests" + CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" + CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" + CONVERSATIONS_EVENTS = "conversations-events" + CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" + CONVERSATIONS_PARTICIPANTS = "conversations-participants" + CPS = "cps" + CREDIT_TRANSFER = "credit-transfer" + EMAIL = "email" + EMERGING_TECH = "emerging-tech" + ENGAGEMENT_SUITE_PACKAGED_PLANS = "engagement-suite-packaged-plans" + ENHANCED_LINE_TYPE_LOOKUPS = "enhanced-line-type-lookups" + ENTERPRISE = "enterprise" + EVENTS = "events" + EXPERIMENT_FRANCE_SMS = "experiment-france-sms" + EXPERIMENT_INDIA_SMS = "experiment-india-sms" + EXPERIMENT_UK_SMS = "experiment-uk-sms" + FAILED_MESSAGE_PROCESSING_FEE = "failed-message-processing-fee" + FLEX = "flex" + FLEX_ACTIVE_USER_HOURS = "flex-active-user-hours" + FLEX_CONCURRENT_USERS = "flex-concurrent-users" + FLEX_CONVERSATIONAL_INSIGHTS = "flex-conversational-insights" + FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES = "flex-conversational-insights-messages" + FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = ( + "flex-conversational-insights-voice-minutes" + ) + FLEX_EMAIL_USAGE = "flex-email-usage" + FLEX_MESSAGING_USAGE = "flex-messaging-usage" + FLEX_PARTNER_SPINSCI = "flex-partner-spinsci" + FLEX_PARTNER_XCELERATE = "flex-partner-xcelerate" + FLEX_RESELLER_ECOSYSTEM = "flex-reseller-ecosystem" + FLEX_UNIQUE_USER = "flex-unique-user" + FLEX_USAGE = "flex-usage" + FLEX_USERS = "flex-users" + FLEX_VOICE_MINUTE = "flex-voice-minute" + FLEX_YTICA = "flex-ytica" + FRAUD_LOOKUPS = "fraud-lookups" + FRONTLINE = "frontline" + FRONTLINE_USERS = "frontline-users" + FUNCTIONS = "functions" + GENERIC_PAY_TRANSACTIONS = "generic-pay-transactions" + GROUP_ROOMS = "group-rooms" + GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" + GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" + GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" + GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" + GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" + GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" + GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" + GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" + IP_MESSAGING = "ip-messaging" + IP_MESSAGING_COMMANDS = "ip-messaging-commands" + IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" + IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" + IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" + IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" + IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" + LINE_STATUS_LOOKUPS = "line-status-lookups" + LIVE_ACTIVITY_LOOKUPS = "live-activity-lookups" + LOOKUP_BUCKET_ADJUSTMENT = "lookup-bucket-adjustment" + LOOKUP_IDENTITY_MATCH = "lookup-identity-match" + LOOKUPS = "lookups" + MARKETPLACE = "marketplace" + MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) + MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" + MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" + MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" + MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" + MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION = "marketplace-deepgram-transcription" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE = ( + "marketplace-deepgram-transcription-base" + ) + MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED = ( + "marketplace-deepgram-transscription-enhanced" + ) + MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( + "marketplace-digital-segment-business-info" + ) + MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( + "marketplace-facebook-offline-conversions" + ) + MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" + MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( + "marketplace-ibm-watson-message-insights" + ) + MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( + "marketplace-ibm-watson-message-sentiment" + ) + MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( + "marketplace-ibm-watson-recording-analysis" + ) + MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" + MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" + MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( + "marketplace-infogroup-dataaxle-bizinfo" + ) + MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( + "marketplace-keen-io-contact-center-analytics" + ) + MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" + MARKETPLACE_MARCHEX_RECORDING_ANALYSIS = ( + "marketplace-marchex-recording-analysis" + ) + MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( + "marketplace-marchex-sentiment-analysis-for-sms" + ) + MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( + "marketplace-marketplace-nextcaller-social-id" + ) + MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( + "marketplace-mobile-commons-opt-out-classifier" + ) + MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( + "marketplace-nexiwave-voicemail-to-text" + ) + MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( + "marketplace-nextcaller-advanced-caller-identification" + ) + MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" + MARKETPLACE_PAY_ADDONS = "marketplace-pay-addons" + MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR = ( + "marketplace-pay-addons-basecommerce-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR = ( + "marketplace-pay-addons-braintree-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR = ( + "marketplace-pay-addons-cardconnect-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR = ( + "marketplace-pay-addons-chase-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplace-pay-addons-shuttle-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplace-pay-addons-stripe-pay-connector" + ) + MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" + MARKETPLACE_POLY_AI_CONNECTOR = "marketplace-poly-ai-connector" + MARKETPLACE_REALPHONEVALIDATION = "marketplace-realphonevalidation" + MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( + "marketplace-remeeting-automatic-speech-recognition" + ) + MARKETPLACE_SPOKE_PHONE_LICENSE_PRO = "marketplace-spoke-phone-license-pro" + MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD = ( + "marketplace-spoke-phone-license-standard" + ) + MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( + "marketplace-tcpa-defense-solutions-blacklist-feed" + ) + MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" + MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION = ( + "marketplace-trestle-solutions-caller-identification" + ) + MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" + MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( + "marketplace-twilio-caller-name-lookup-us" + ) + MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( + "marketplace-twilio-carrier-information-lookup" + ) + MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" + MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" + MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) + MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" + MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( + "marketplace-ytica-contact-center-reporting-analytics" + ) + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplay-pay-addons-shuttle-pay-connector" + ) + MEDIA_COMPOSER_MINUTES = "media-composer-minutes" + MEDIASTORAGE = "mediastorage" + MIN_SPEND_ADJUSTMENTS = "min-spend-adjustments" + MMS = "mms" + MMS_INBOUND = "mms-inbound" + MMS_INBOUND_LONGCODE = "mms-inbound-longcode" + MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" + MMS_INBOUND_TOLL_FREE = "mms-inbound-toll-free" + MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" + MMS_OUTBOUND = "mms-outbound" + MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" + MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" + MMS_OUTBOUND_TOLLFREE = "mms-outbound-tollfree" + MONITOR = "monitor" + MONITOR_READS = "monitor-reads" + MONITOR_STORAGE = "monitor-storage" + MONITOR_WRITES = "monitor-writes" + NOTIFY = "notify" + NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" + NOTIFY_CHANNELS = "notify-channels" + NUMBER_FORMAT_LOOKUPS = "number-format-lookups" + PCHAT = "pchat" + PCHAT_ACTIONS = "pchat-actions" + PCHAT_APS = "pchat-aps" + PCHAT_CONV_MED_STORAGE = "pchat-conv-med-storage" + PCHAT_MESSAGES = "pchat-messages" + PCHAT_NOTIFICATIONS = "pchat-notifications" + PCHAT_READS = "pchat-reads" + PCHAT_USERS = "pchat-users" + PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "peer-to-peer-rooms-participant-minutes" + ) + PFAX = "pfax" + PFAX_MINUTES = "pfax-minutes" + PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" + PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" + PFAX_PAGES = "pfax-pages" + PHONE_QUALITY_SCORE_LOOKUPS = "phone-quality-score-lookups" + PHONENUMBERS = "phonenumbers" + PHONENUMBERS_CPS = "phonenumbers-cps" + PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" + PHONENUMBERS_LOCAL = "phonenumbers-local" + PHONENUMBERS_MOBILE = "phonenumbers-mobile" + PHONENUMBERS_PORTING = "phonenumbers-porting" + PHONENUMBERS_SETUPS = "phonenumbers-setups" + PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" + PREMIUMSUPPORT = "premiumsupport" + PREMIUMSUPPORT_PERCENTAGE_SPEND = "premiumsupport-percentage-spend" + PROGRAMMABLEVOICE_PLATFORM = "programmablevoice-platform" + PROGRAMMABLEVOICECONN_CLIENTSDK = "programmablevoiceconn-clientsdk" + PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND = ( + "programmablevoiceconn-clientsdk-inbound" + ) + PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND = ( + "programmablevoiceconn-clientsdk-outbound" + ) + PROGRAMMABLEVOICECONN_ONNET = "programmablevoiceconn-onnet" + PROGRAMMABLEVOICECONN_ONNET_INBOUND = "programmablevoiceconn-onnet-inbound" + PROGRAMMABLEVOICECONN_ONNET_OUTBOUND = "programmablevoiceconn-onnet-outbound" + PROGRAMMABLEVOICECONN_SIP = "programmablevoiceconn-sip" + PROGRAMMABLEVOICECONN_SIP_INBOUND = "programmablevoiceconn-sip-inbound" + PROGRAMMABLEVOICECONN_SIP_OUTBOUND = "programmablevoiceconn-sip-outbound" + PROGRAMMABLEVOICECONNECTIVITY = "programmablevoiceconnectivity" + PROXY = "proxy" + PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" + PROXY_BUCKET_ADJUSTMENT = "proxy-bucket-adjustment" + PROXY_LICENSES = "proxy-licenses" + PSTNCONNECTIVITY = "pstnconnectivity" + PSTNCONNECTIVITY_INBOUND = "pstnconnectivity-inbound" + PSTNCONNECTIVITY_OUTBOUND = "pstnconnectivity-outbound" + PV = "pv" + PV_BASIC_ROOMS = "pv-basic-rooms" + PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" + PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" + PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" + PV_COMPOSITION_MINUTES = "pv-composition-minutes" + PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" + PV_ROOM_PARTICIPANTS = "pv-room-participants" + PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" + PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" + PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" + PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" + PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" + PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" + PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" + PV_ROOMS = "pv-rooms" + PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" + RCS_MESSAGES = "rcs-messages" + REASSIGNED_NUMBER = "reassigned-number" + RECORDINGS = "recordings" + RECORDINGSTORAGE = "recordingstorage" + SHORTCODES = "shortcodes" + SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" + SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" + SHORTCODES_MPS = "shortcodes-mps" + SHORTCODES_RANDOM = "shortcodes-random" + SHORTCODES_SETUP_FEES = "shortcodes-setup-fees" + SHORTCODES_UK = "shortcodes-uk" + SHORTCODES_VANITY = "shortcodes-vanity" + SIM_SWAP_LOOKUPS = "sim-swap-lookups" + SIP_SECURE_MEDIA = "sip-secure-media" + SMALL_GROUP_ROOMS = "small-group-rooms" + SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" + SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" + SMS = "sms" + SMS_INBOUND = "sms-inbound" + SMS_INBOUND_LONGCODE = "sms-inbound-longcode" + SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" + SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" + SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) + SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" + SMS_OUTBOUND = "sms-outbound" + SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" + SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" + SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" + SPEECH_RECOGNITION = "speech-recognition" + STUDIO_ENGAGEMENTS = "studio-engagements" + SYNC = "sync" + SYNC_ACTIONS = "sync-actions" + SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" + SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" + TASKROUTER_TASKS = "taskrouter-tasks" + TOTALPRICE = "totalprice" + TRANSCRIPTIONS = "transcriptions" + TRUNKING_CPS = "trunking-cps" + TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" + TRUNKING_ORIGINATION = "trunking-origination" + TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" + TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" + TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" + TRUNKING_RECORDINGS = "trunking-recordings" + TRUNKING_SECURE = "trunking-secure" + TRUNKING_TERMINATION = "trunking-termination" + TTS_GOOGLE = "tts-google" + TURNMEGABYTES = "turnmegabytes" + TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" + TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" + TURNMEGABYTES_GERMANY = "turnmegabytes-germany" + TURNMEGABYTES_INDIA = "turnmegabytes-india" + TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" + TURNMEGABYTES_JAPAN = "turnmegabytes-japan" + TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" + TURNMEGABYTES_USEAST = "turnmegabytes-useast" + TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" + TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) + VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" + VOICE_INSIGHTS = "voice-insights" + VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-client-insights-on-demand-minute" + ) + VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-ptsn-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-interface-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-trunking-insights-on-demand-minute" + ) + VOICE_INTELLIGENCE = "voice-intelligence" + VOICE_INTELLIGENCE_EIP_OPERATORS = "voice-intelligence-eip-operators" + VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" + VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" + WDS = "wds" + WIRELESS = "wireless" + WIRELESS_DATA = "wireless-data" + WIRELESS_DATA_PAYG = "wireless-data-payg" + WIRELESS_DATA_PAYG_AFRICA = "wireless-data-payg-africa" + WIRELESS_DATA_PAYG_ASIA = "wireless-data-payg-asia" + WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA = ( + "wireless-data-payg-centralandsouthamerica" + ) + WIRELESS_DATA_PAYG_EUROPE = "wireless-data-payg-europe" + WIRELESS_DATA_PAYG_NORTHAMERICA = "wireless-data-payg-northamerica" + WIRELESS_DATA_PAYG_OCEANIA = "wireless-data-payg-oceania" + WIRELESS_DATA_QUOTA1 = "wireless-data-quota1" + WIRELESS_DATA_QUOTA1_AFRICA = "wireless-data-quota1-africa" + WIRELESS_DATA_QUOTA1_ASIA = "wireless-data-quota1-asia" + WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota1-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA1_EUROPE = "wireless-data-quota1-europe" + WIRELESS_DATA_QUOTA1_NORTHAMERICA = "wireless-data-quota1-northamerica" + WIRELESS_DATA_QUOTA1_OCEANIA = "wireless-data-quota1-oceania" + WIRELESS_DATA_QUOTA10 = "wireless-data-quota10" + WIRELESS_DATA_QUOTA10_AFRICA = "wireless-data-quota10-africa" + WIRELESS_DATA_QUOTA10_ASIA = "wireless-data-quota10-asia" + WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota10-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA10_EUROPE = "wireless-data-quota10-europe" + WIRELESS_DATA_QUOTA10_NORTHAMERICA = "wireless-data-quota10-northamerica" + WIRELESS_DATA_QUOTA10_OCEANIA = "wireless-data-quota10-oceania" + WIRELESS_DATA_QUOTA50 = "wireless-data-quota50" + WIRELESS_DATA_QUOTA50_AFRICA = "wireless-data-quota50-africa" + WIRELESS_DATA_QUOTA50_ASIA = "wireless-data-quota50-asia" + WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota50-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA50_EUROPE = "wireless-data-quota50-europe" + WIRELESS_DATA_QUOTA50_NORTHAMERICA = "wireless-data-quota50-northamerica" + WIRELESS_DATA_QUOTA50_OCEANIA = "wireless-data-quota50-oceania" + WIRELESS_DATA_QUOTACUSTOM = "wireless-data-quotacustom" + WIRELESS_DATA_QUOTACUSTOM_AFRICA = "wireless-data-quotacustom-africa" + WIRELESS_DATA_QUOTACUSTOM_ASIA = "wireless-data-quotacustom-asia" + WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quotacustom-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_EUROPE = "wireless-data-quotacustom-europe" + WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA = ( + "wireless-data-quotacustom-northamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_OCEANIA = "wireless-data-quotacustom-oceania" + WIRELESS_MRC_PAYG = "wireless-mrc-payg" + WIRELESS_MRC_QUOTA1 = "wireless-mrc-quota1" + WIRELESS_MRC_QUOTA10 = "wireless-mrc-quota10" + WIRELESS_MRC_QUOTA50 = "wireless-mrc-quota50" + WIRELESS_MRC_QUOTACUSTOM = "wireless-mrc-quotacustom" + WIRELESS_ORDERS = "wireless-orders" + WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" + WIRELESS_ORDERS_BULK = "wireless-orders-bulk" + WIRELESS_ORDERS_ESIM = "wireless-orders-esim" + WIRELESS_ORDERS_STARTER = "wireless-orders-starter" + WIRELESS_QUOTAS = "wireless-quotas" + WIRELESS_SMS_AFRICA = "wireless-sms-africa" + WIRELESS_SMS_ASIA = "wireless-sms-asia" + WIRELESS_SMS_CENTRALANDSOUTHAMERICA = "wireless-sms-centralandsouthamerica" + WIRELESS_SMS_EUROPE = "wireless-sms-europe" + WIRELESS_SMS_NORTHAMERICA = "wireless-sms-northamerica" + WIRELESS_SMS_OCEANIA = "wireless-sms-oceania" + WIRELESS_SUPER_SIM = "wireless-super-sim" + WIRELESS_SUPER_SIM_DATA = "wireless-super-sim-data" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA = ( + "wireless-super-sim-data-north-america-usa" + ) + WIRELESS_SUPER_SIM_DATA_PAYG = "wireless-super-sim-data-payg" + WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE = "wireless-super-sim-data-payg-europe" + WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA = ( + "wireless-super-sim-data-payg-north-america" + ) + WIRELESS_SUPER_SIM_HARDWARE = "wireless-super-sim-hardware" + WIRELESS_SUPER_SIM_HARDWARE_BULK = "wireless-super-sim-hardware-bulk" + WIRELESS_SUPER_SIM_SMSCOMMANDS = "wireless-super-sim-smscommands" + WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA = "wireless-super-sim-smscommands-africa" + WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA = "wireless-super-sim-smscommands-asia" + WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA = ( + "wireless-super-sim-smscommands-cent-and-south-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE = "wireless-super-sim-smscommands-europe" + WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA = ( + "wireless-super-sim-smscommands-north-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA = ( + "wireless-super-sim-smscommands-oceania" + ) + WIRELESS_SUPER_SIM_SUBSCRIPTION = "wireless-super-sim-subscription" + WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG = "wireless-super-sim-subscription-payg" + WIRELESS_USAGE = "wireless-usage" + WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" + WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" + WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" + WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-commands-centralandsouthamerica" + ) + WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" + WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" + WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" + WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" + WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" + WIRELESS_USAGE_DATA = "wireless-usage-data" + WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" + WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" + WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-data-centralandsouthamerica" + ) + WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( + "wireless-usage-data-custom-additionalmb" + ) + WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" + WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" + WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" + WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( + "wireless-usage-data-individual-additionalgb" + ) + WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( + "wireless-usage-data-individual-firstgb" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( + "wireless-usage-data-international-roaming-canada" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( + "wireless-usage-data-international-roaming-india" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( + "wireless-usage-data-international-roaming-mexico" + ) + WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" + WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" + WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" + WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" + WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" + WIRELESS_USAGE_MRC = "wireless-usage-mrc" + WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" + WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" + WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" + WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" + WIRELESS_USAGE_SMS = "wireless-usage-sms" + WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + :ivar api_version: The API version used to create the resource. + :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + :ivar category: + :ivar count: The number of usage events, such as the number of calls. + :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + :ivar description: A plain-language description of the usage category. + :ivar end_date: The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar price: The total price of the usage in the currency specified in `price_unit` and associated with the account. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + :ivar start_date: The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar subresource_uris: A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage: The amount used to bill usage and measured in units described in `usage_unit`. + :ivar usage_unit: The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.as_of: Optional[str] = payload.get("as_of") + self.category: Optional["AllTimeInstance.Category"] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.AllTimeInstance {}>".format(context) + + +class AllTimePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AllTimeInstance: + """ + Build an instance of AllTimeInstance + + :param payload: Payload response from the API + """ + return AllTimeInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AllTimePage>" + + +class AllTimeList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the AllTimeList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/AllTime.json".format( + **self._solution + ) + + def stream( + self, + category: Union["AllTimeInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AllTimeInstance]: + """ + Streams AllTimeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "AllTimeInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + category: Union["AllTimeInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AllTimeInstance]: + """ + Asynchronously streams AllTimeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "AllTimeInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["AllTimeInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AllTimeInstance]: + """ + Lists AllTimeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "AllTimeInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + category: Union["AllTimeInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AllTimeInstance]: + """ + Asynchronously lists AllTimeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "AllTimeInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + category: Union["AllTimeInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AllTimePage: + """ + Retrieve a single page of AllTimeInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AllTimeInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AllTimePage(self._version, response, self._solution) + + async def page_async( + self, + category: Union["AllTimeInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AllTimePage: + """ + Asynchronously retrieve a single page of AllTimeInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AllTimeInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AllTimePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AllTimePage: + """ + Retrieve a specific page of AllTimeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AllTimeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AllTimePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AllTimePage: + """ + Asynchronously retrieve a specific page of AllTimeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AllTimeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AllTimePage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.AllTimeList>" diff --git a/twilio/rest/api/v2010/account/usage/record/daily.py b/twilio/rest/api/v2010/account/usage/record/daily.py new file mode 100644 index 0000000000..e89c75cb39 --- /dev/null +++ b/twilio/rest/api/v2010/account/usage/record/daily.py @@ -0,0 +1,1211 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DailyInstance(InstanceResource): + + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" + AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" + ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" + AUTHY_AUTHENTICATIONS = "authy-authentications" + AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" + AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" + AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" + AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" + AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" + CALL_PROGESS_EVENTS = "call-progess-events" + CALLERIDLOOKUPS = "calleridlookups" + CALLS = "calls" + CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" + CALLS_GLOBALCONFERENCE = "calls-globalconference" + CALLS_INBOUND = "calls-inbound" + CALLS_INBOUND_LOCAL = "calls-inbound-local" + CALLS_INBOUND_MOBILE = "calls-inbound-mobile" + CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" + CALLS_OUTBOUND = "calls-outbound" + CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" + CALLS_RECORDINGS = "calls-recordings" + CALLS_SIP = "calls-sip" + CALLS_SIP_INBOUND = "calls-sip-inbound" + CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" + CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" + CONVERSATIONS = "conversations" + CONVERSATIONS_API_REQUESTS = "conversations-api-requests" + CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" + CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" + CONVERSATIONS_EVENTS = "conversations-events" + CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" + CONVERSATIONS_PARTICIPANTS = "conversations-participants" + CPS = "cps" + CREDIT_TRANSFER = "credit-transfer" + EMAIL = "email" + EMERGING_TECH = "emerging-tech" + ENGAGEMENT_SUITE_PACKAGED_PLANS = "engagement-suite-packaged-plans" + ENHANCED_LINE_TYPE_LOOKUPS = "enhanced-line-type-lookups" + ENTERPRISE = "enterprise" + EVENTS = "events" + EXPERIMENT_FRANCE_SMS = "experiment-france-sms" + EXPERIMENT_INDIA_SMS = "experiment-india-sms" + EXPERIMENT_UK_SMS = "experiment-uk-sms" + FAILED_MESSAGE_PROCESSING_FEE = "failed-message-processing-fee" + FLEX = "flex" + FLEX_ACTIVE_USER_HOURS = "flex-active-user-hours" + FLEX_CONCURRENT_USERS = "flex-concurrent-users" + FLEX_CONVERSATIONAL_INSIGHTS = "flex-conversational-insights" + FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES = "flex-conversational-insights-messages" + FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = ( + "flex-conversational-insights-voice-minutes" + ) + FLEX_EMAIL_USAGE = "flex-email-usage" + FLEX_MESSAGING_USAGE = "flex-messaging-usage" + FLEX_PARTNER_SPINSCI = "flex-partner-spinsci" + FLEX_PARTNER_XCELERATE = "flex-partner-xcelerate" + FLEX_RESELLER_ECOSYSTEM = "flex-reseller-ecosystem" + FLEX_UNIQUE_USER = "flex-unique-user" + FLEX_USAGE = "flex-usage" + FLEX_USERS = "flex-users" + FLEX_VOICE_MINUTE = "flex-voice-minute" + FLEX_YTICA = "flex-ytica" + FRAUD_LOOKUPS = "fraud-lookups" + FRONTLINE = "frontline" + FRONTLINE_USERS = "frontline-users" + FUNCTIONS = "functions" + GENERIC_PAY_TRANSACTIONS = "generic-pay-transactions" + GROUP_ROOMS = "group-rooms" + GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" + GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" + GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" + GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" + GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" + GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" + GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" + GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" + IP_MESSAGING = "ip-messaging" + IP_MESSAGING_COMMANDS = "ip-messaging-commands" + IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" + IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" + IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" + IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" + IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" + LINE_STATUS_LOOKUPS = "line-status-lookups" + LIVE_ACTIVITY_LOOKUPS = "live-activity-lookups" + LOOKUP_BUCKET_ADJUSTMENT = "lookup-bucket-adjustment" + LOOKUP_IDENTITY_MATCH = "lookup-identity-match" + LOOKUPS = "lookups" + MARKETPLACE = "marketplace" + MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) + MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" + MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" + MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" + MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" + MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION = "marketplace-deepgram-transcription" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE = ( + "marketplace-deepgram-transcription-base" + ) + MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED = ( + "marketplace-deepgram-transscription-enhanced" + ) + MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( + "marketplace-digital-segment-business-info" + ) + MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( + "marketplace-facebook-offline-conversions" + ) + MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" + MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( + "marketplace-ibm-watson-message-insights" + ) + MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( + "marketplace-ibm-watson-message-sentiment" + ) + MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( + "marketplace-ibm-watson-recording-analysis" + ) + MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" + MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" + MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( + "marketplace-infogroup-dataaxle-bizinfo" + ) + MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( + "marketplace-keen-io-contact-center-analytics" + ) + MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" + MARKETPLACE_MARCHEX_RECORDING_ANALYSIS = ( + "marketplace-marchex-recording-analysis" + ) + MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( + "marketplace-marchex-sentiment-analysis-for-sms" + ) + MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( + "marketplace-marketplace-nextcaller-social-id" + ) + MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( + "marketplace-mobile-commons-opt-out-classifier" + ) + MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( + "marketplace-nexiwave-voicemail-to-text" + ) + MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( + "marketplace-nextcaller-advanced-caller-identification" + ) + MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" + MARKETPLACE_PAY_ADDONS = "marketplace-pay-addons" + MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR = ( + "marketplace-pay-addons-basecommerce-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR = ( + "marketplace-pay-addons-braintree-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR = ( + "marketplace-pay-addons-cardconnect-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR = ( + "marketplace-pay-addons-chase-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplace-pay-addons-shuttle-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplace-pay-addons-stripe-pay-connector" + ) + MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" + MARKETPLACE_POLY_AI_CONNECTOR = "marketplace-poly-ai-connector" + MARKETPLACE_REALPHONEVALIDATION = "marketplace-realphonevalidation" + MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( + "marketplace-remeeting-automatic-speech-recognition" + ) + MARKETPLACE_SPOKE_PHONE_LICENSE_PRO = "marketplace-spoke-phone-license-pro" + MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD = ( + "marketplace-spoke-phone-license-standard" + ) + MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( + "marketplace-tcpa-defense-solutions-blacklist-feed" + ) + MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" + MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION = ( + "marketplace-trestle-solutions-caller-identification" + ) + MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" + MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( + "marketplace-twilio-caller-name-lookup-us" + ) + MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( + "marketplace-twilio-carrier-information-lookup" + ) + MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" + MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" + MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) + MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" + MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( + "marketplace-ytica-contact-center-reporting-analytics" + ) + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplay-pay-addons-shuttle-pay-connector" + ) + MEDIA_COMPOSER_MINUTES = "media-composer-minutes" + MEDIASTORAGE = "mediastorage" + MIN_SPEND_ADJUSTMENTS = "min-spend-adjustments" + MMS = "mms" + MMS_INBOUND = "mms-inbound" + MMS_INBOUND_LONGCODE = "mms-inbound-longcode" + MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" + MMS_INBOUND_TOLL_FREE = "mms-inbound-toll-free" + MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" + MMS_OUTBOUND = "mms-outbound" + MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" + MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" + MMS_OUTBOUND_TOLLFREE = "mms-outbound-tollfree" + MONITOR = "monitor" + MONITOR_READS = "monitor-reads" + MONITOR_STORAGE = "monitor-storage" + MONITOR_WRITES = "monitor-writes" + NOTIFY = "notify" + NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" + NOTIFY_CHANNELS = "notify-channels" + NUMBER_FORMAT_LOOKUPS = "number-format-lookups" + PCHAT = "pchat" + PCHAT_ACTIONS = "pchat-actions" + PCHAT_APS = "pchat-aps" + PCHAT_CONV_MED_STORAGE = "pchat-conv-med-storage" + PCHAT_MESSAGES = "pchat-messages" + PCHAT_NOTIFICATIONS = "pchat-notifications" + PCHAT_READS = "pchat-reads" + PCHAT_USERS = "pchat-users" + PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "peer-to-peer-rooms-participant-minutes" + ) + PFAX = "pfax" + PFAX_MINUTES = "pfax-minutes" + PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" + PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" + PFAX_PAGES = "pfax-pages" + PHONE_QUALITY_SCORE_LOOKUPS = "phone-quality-score-lookups" + PHONENUMBERS = "phonenumbers" + PHONENUMBERS_CPS = "phonenumbers-cps" + PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" + PHONENUMBERS_LOCAL = "phonenumbers-local" + PHONENUMBERS_MOBILE = "phonenumbers-mobile" + PHONENUMBERS_PORTING = "phonenumbers-porting" + PHONENUMBERS_SETUPS = "phonenumbers-setups" + PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" + PREMIUMSUPPORT = "premiumsupport" + PREMIUMSUPPORT_PERCENTAGE_SPEND = "premiumsupport-percentage-spend" + PROGRAMMABLEVOICE_PLATFORM = "programmablevoice-platform" + PROGRAMMABLEVOICECONN_CLIENTSDK = "programmablevoiceconn-clientsdk" + PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND = ( + "programmablevoiceconn-clientsdk-inbound" + ) + PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND = ( + "programmablevoiceconn-clientsdk-outbound" + ) + PROGRAMMABLEVOICECONN_ONNET = "programmablevoiceconn-onnet" + PROGRAMMABLEVOICECONN_ONNET_INBOUND = "programmablevoiceconn-onnet-inbound" + PROGRAMMABLEVOICECONN_ONNET_OUTBOUND = "programmablevoiceconn-onnet-outbound" + PROGRAMMABLEVOICECONN_SIP = "programmablevoiceconn-sip" + PROGRAMMABLEVOICECONN_SIP_INBOUND = "programmablevoiceconn-sip-inbound" + PROGRAMMABLEVOICECONN_SIP_OUTBOUND = "programmablevoiceconn-sip-outbound" + PROGRAMMABLEVOICECONNECTIVITY = "programmablevoiceconnectivity" + PROXY = "proxy" + PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" + PROXY_BUCKET_ADJUSTMENT = "proxy-bucket-adjustment" + PROXY_LICENSES = "proxy-licenses" + PSTNCONNECTIVITY = "pstnconnectivity" + PSTNCONNECTIVITY_INBOUND = "pstnconnectivity-inbound" + PSTNCONNECTIVITY_OUTBOUND = "pstnconnectivity-outbound" + PV = "pv" + PV_BASIC_ROOMS = "pv-basic-rooms" + PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" + PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" + PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" + PV_COMPOSITION_MINUTES = "pv-composition-minutes" + PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" + PV_ROOM_PARTICIPANTS = "pv-room-participants" + PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" + PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" + PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" + PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" + PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" + PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" + PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" + PV_ROOMS = "pv-rooms" + PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" + RCS_MESSAGES = "rcs-messages" + REASSIGNED_NUMBER = "reassigned-number" + RECORDINGS = "recordings" + RECORDINGSTORAGE = "recordingstorage" + SHORTCODES = "shortcodes" + SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" + SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" + SHORTCODES_MPS = "shortcodes-mps" + SHORTCODES_RANDOM = "shortcodes-random" + SHORTCODES_SETUP_FEES = "shortcodes-setup-fees" + SHORTCODES_UK = "shortcodes-uk" + SHORTCODES_VANITY = "shortcodes-vanity" + SIM_SWAP_LOOKUPS = "sim-swap-lookups" + SIP_SECURE_MEDIA = "sip-secure-media" + SMALL_GROUP_ROOMS = "small-group-rooms" + SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" + SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" + SMS = "sms" + SMS_INBOUND = "sms-inbound" + SMS_INBOUND_LONGCODE = "sms-inbound-longcode" + SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" + SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" + SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) + SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" + SMS_OUTBOUND = "sms-outbound" + SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" + SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" + SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" + SPEECH_RECOGNITION = "speech-recognition" + STUDIO_ENGAGEMENTS = "studio-engagements" + SYNC = "sync" + SYNC_ACTIONS = "sync-actions" + SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" + SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" + TASKROUTER_TASKS = "taskrouter-tasks" + TOTALPRICE = "totalprice" + TRANSCRIPTIONS = "transcriptions" + TRUNKING_CPS = "trunking-cps" + TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" + TRUNKING_ORIGINATION = "trunking-origination" + TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" + TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" + TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" + TRUNKING_RECORDINGS = "trunking-recordings" + TRUNKING_SECURE = "trunking-secure" + TRUNKING_TERMINATION = "trunking-termination" + TTS_GOOGLE = "tts-google" + TURNMEGABYTES = "turnmegabytes" + TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" + TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" + TURNMEGABYTES_GERMANY = "turnmegabytes-germany" + TURNMEGABYTES_INDIA = "turnmegabytes-india" + TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" + TURNMEGABYTES_JAPAN = "turnmegabytes-japan" + TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" + TURNMEGABYTES_USEAST = "turnmegabytes-useast" + TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" + TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) + VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" + VOICE_INSIGHTS = "voice-insights" + VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-client-insights-on-demand-minute" + ) + VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-ptsn-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-interface-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-trunking-insights-on-demand-minute" + ) + VOICE_INTELLIGENCE = "voice-intelligence" + VOICE_INTELLIGENCE_EIP_OPERATORS = "voice-intelligence-eip-operators" + VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" + VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" + WDS = "wds" + WIRELESS = "wireless" + WIRELESS_DATA = "wireless-data" + WIRELESS_DATA_PAYG = "wireless-data-payg" + WIRELESS_DATA_PAYG_AFRICA = "wireless-data-payg-africa" + WIRELESS_DATA_PAYG_ASIA = "wireless-data-payg-asia" + WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA = ( + "wireless-data-payg-centralandsouthamerica" + ) + WIRELESS_DATA_PAYG_EUROPE = "wireless-data-payg-europe" + WIRELESS_DATA_PAYG_NORTHAMERICA = "wireless-data-payg-northamerica" + WIRELESS_DATA_PAYG_OCEANIA = "wireless-data-payg-oceania" + WIRELESS_DATA_QUOTA1 = "wireless-data-quota1" + WIRELESS_DATA_QUOTA1_AFRICA = "wireless-data-quota1-africa" + WIRELESS_DATA_QUOTA1_ASIA = "wireless-data-quota1-asia" + WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota1-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA1_EUROPE = "wireless-data-quota1-europe" + WIRELESS_DATA_QUOTA1_NORTHAMERICA = "wireless-data-quota1-northamerica" + WIRELESS_DATA_QUOTA1_OCEANIA = "wireless-data-quota1-oceania" + WIRELESS_DATA_QUOTA10 = "wireless-data-quota10" + WIRELESS_DATA_QUOTA10_AFRICA = "wireless-data-quota10-africa" + WIRELESS_DATA_QUOTA10_ASIA = "wireless-data-quota10-asia" + WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota10-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA10_EUROPE = "wireless-data-quota10-europe" + WIRELESS_DATA_QUOTA10_NORTHAMERICA = "wireless-data-quota10-northamerica" + WIRELESS_DATA_QUOTA10_OCEANIA = "wireless-data-quota10-oceania" + WIRELESS_DATA_QUOTA50 = "wireless-data-quota50" + WIRELESS_DATA_QUOTA50_AFRICA = "wireless-data-quota50-africa" + WIRELESS_DATA_QUOTA50_ASIA = "wireless-data-quota50-asia" + WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota50-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA50_EUROPE = "wireless-data-quota50-europe" + WIRELESS_DATA_QUOTA50_NORTHAMERICA = "wireless-data-quota50-northamerica" + WIRELESS_DATA_QUOTA50_OCEANIA = "wireless-data-quota50-oceania" + WIRELESS_DATA_QUOTACUSTOM = "wireless-data-quotacustom" + WIRELESS_DATA_QUOTACUSTOM_AFRICA = "wireless-data-quotacustom-africa" + WIRELESS_DATA_QUOTACUSTOM_ASIA = "wireless-data-quotacustom-asia" + WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quotacustom-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_EUROPE = "wireless-data-quotacustom-europe" + WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA = ( + "wireless-data-quotacustom-northamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_OCEANIA = "wireless-data-quotacustom-oceania" + WIRELESS_MRC_PAYG = "wireless-mrc-payg" + WIRELESS_MRC_QUOTA1 = "wireless-mrc-quota1" + WIRELESS_MRC_QUOTA10 = "wireless-mrc-quota10" + WIRELESS_MRC_QUOTA50 = "wireless-mrc-quota50" + WIRELESS_MRC_QUOTACUSTOM = "wireless-mrc-quotacustom" + WIRELESS_ORDERS = "wireless-orders" + WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" + WIRELESS_ORDERS_BULK = "wireless-orders-bulk" + WIRELESS_ORDERS_ESIM = "wireless-orders-esim" + WIRELESS_ORDERS_STARTER = "wireless-orders-starter" + WIRELESS_QUOTAS = "wireless-quotas" + WIRELESS_SMS_AFRICA = "wireless-sms-africa" + WIRELESS_SMS_ASIA = "wireless-sms-asia" + WIRELESS_SMS_CENTRALANDSOUTHAMERICA = "wireless-sms-centralandsouthamerica" + WIRELESS_SMS_EUROPE = "wireless-sms-europe" + WIRELESS_SMS_NORTHAMERICA = "wireless-sms-northamerica" + WIRELESS_SMS_OCEANIA = "wireless-sms-oceania" + WIRELESS_SUPER_SIM = "wireless-super-sim" + WIRELESS_SUPER_SIM_DATA = "wireless-super-sim-data" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA = ( + "wireless-super-sim-data-north-america-usa" + ) + WIRELESS_SUPER_SIM_DATA_PAYG = "wireless-super-sim-data-payg" + WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE = "wireless-super-sim-data-payg-europe" + WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA = ( + "wireless-super-sim-data-payg-north-america" + ) + WIRELESS_SUPER_SIM_HARDWARE = "wireless-super-sim-hardware" + WIRELESS_SUPER_SIM_HARDWARE_BULK = "wireless-super-sim-hardware-bulk" + WIRELESS_SUPER_SIM_SMSCOMMANDS = "wireless-super-sim-smscommands" + WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA = "wireless-super-sim-smscommands-africa" + WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA = "wireless-super-sim-smscommands-asia" + WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA = ( + "wireless-super-sim-smscommands-cent-and-south-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE = "wireless-super-sim-smscommands-europe" + WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA = ( + "wireless-super-sim-smscommands-north-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA = ( + "wireless-super-sim-smscommands-oceania" + ) + WIRELESS_SUPER_SIM_SUBSCRIPTION = "wireless-super-sim-subscription" + WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG = "wireless-super-sim-subscription-payg" + WIRELESS_USAGE = "wireless-usage" + WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" + WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" + WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" + WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-commands-centralandsouthamerica" + ) + WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" + WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" + WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" + WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" + WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" + WIRELESS_USAGE_DATA = "wireless-usage-data" + WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" + WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" + WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-data-centralandsouthamerica" + ) + WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( + "wireless-usage-data-custom-additionalmb" + ) + WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" + WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" + WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" + WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( + "wireless-usage-data-individual-additionalgb" + ) + WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( + "wireless-usage-data-individual-firstgb" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( + "wireless-usage-data-international-roaming-canada" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( + "wireless-usage-data-international-roaming-india" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( + "wireless-usage-data-international-roaming-mexico" + ) + WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" + WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" + WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" + WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" + WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" + WIRELESS_USAGE_MRC = "wireless-usage-mrc" + WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" + WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" + WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" + WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" + WIRELESS_USAGE_SMS = "wireless-usage-sms" + WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + :ivar api_version: The API version used to create the resource. + :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + :ivar category: + :ivar count: The number of usage events, such as the number of calls. + :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + :ivar description: A plain-language description of the usage category. + :ivar end_date: The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar price: The total price of the usage in the currency specified in `price_unit` and associated with the account. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + :ivar start_date: The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar subresource_uris: A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage: The amount used to bill usage and measured in units described in `usage_unit`. + :ivar usage_unit: The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.as_of: Optional[str] = payload.get("as_of") + self.category: Optional["DailyInstance.Category"] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.DailyInstance {}>".format(context) + + +class DailyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DailyInstance: + """ + Build an instance of DailyInstance + + :param payload: Payload response from the API + """ + return DailyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.DailyPage>" + + +class DailyList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the DailyList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/Daily.json".format( + **self._solution + ) + + def stream( + self, + category: Union["DailyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DailyInstance]: + """ + Streams DailyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "DailyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + category: Union["DailyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DailyInstance]: + """ + Asynchronously streams DailyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "DailyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["DailyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DailyInstance]: + """ + Lists DailyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "DailyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + category: Union["DailyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DailyInstance]: + """ + Asynchronously lists DailyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "DailyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + category: Union["DailyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DailyPage: + """ + Retrieve a single page of DailyInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DailyInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DailyPage(self._version, response, self._solution) + + async def page_async( + self, + category: Union["DailyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DailyPage: + """ + Asynchronously retrieve a single page of DailyInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DailyInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DailyPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DailyPage: + """ + Retrieve a specific page of DailyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DailyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DailyPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DailyPage: + """ + Asynchronously retrieve a specific page of DailyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DailyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DailyPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.DailyList>" diff --git a/twilio/rest/api/v2010/account/usage/record/last_month.py b/twilio/rest/api/v2010/account/usage/record/last_month.py new file mode 100644 index 0000000000..4057283e4a --- /dev/null +++ b/twilio/rest/api/v2010/account/usage/record/last_month.py @@ -0,0 +1,1211 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class LastMonthInstance(InstanceResource): + + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" + AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" + ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" + AUTHY_AUTHENTICATIONS = "authy-authentications" + AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" + AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" + AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" + AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" + AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" + CALL_PROGESS_EVENTS = "call-progess-events" + CALLERIDLOOKUPS = "calleridlookups" + CALLS = "calls" + CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" + CALLS_GLOBALCONFERENCE = "calls-globalconference" + CALLS_INBOUND = "calls-inbound" + CALLS_INBOUND_LOCAL = "calls-inbound-local" + CALLS_INBOUND_MOBILE = "calls-inbound-mobile" + CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" + CALLS_OUTBOUND = "calls-outbound" + CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" + CALLS_RECORDINGS = "calls-recordings" + CALLS_SIP = "calls-sip" + CALLS_SIP_INBOUND = "calls-sip-inbound" + CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" + CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" + CONVERSATIONS = "conversations" + CONVERSATIONS_API_REQUESTS = "conversations-api-requests" + CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" + CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" + CONVERSATIONS_EVENTS = "conversations-events" + CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" + CONVERSATIONS_PARTICIPANTS = "conversations-participants" + CPS = "cps" + CREDIT_TRANSFER = "credit-transfer" + EMAIL = "email" + EMERGING_TECH = "emerging-tech" + ENGAGEMENT_SUITE_PACKAGED_PLANS = "engagement-suite-packaged-plans" + ENHANCED_LINE_TYPE_LOOKUPS = "enhanced-line-type-lookups" + ENTERPRISE = "enterprise" + EVENTS = "events" + EXPERIMENT_FRANCE_SMS = "experiment-france-sms" + EXPERIMENT_INDIA_SMS = "experiment-india-sms" + EXPERIMENT_UK_SMS = "experiment-uk-sms" + FAILED_MESSAGE_PROCESSING_FEE = "failed-message-processing-fee" + FLEX = "flex" + FLEX_ACTIVE_USER_HOURS = "flex-active-user-hours" + FLEX_CONCURRENT_USERS = "flex-concurrent-users" + FLEX_CONVERSATIONAL_INSIGHTS = "flex-conversational-insights" + FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES = "flex-conversational-insights-messages" + FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = ( + "flex-conversational-insights-voice-minutes" + ) + FLEX_EMAIL_USAGE = "flex-email-usage" + FLEX_MESSAGING_USAGE = "flex-messaging-usage" + FLEX_PARTNER_SPINSCI = "flex-partner-spinsci" + FLEX_PARTNER_XCELERATE = "flex-partner-xcelerate" + FLEX_RESELLER_ECOSYSTEM = "flex-reseller-ecosystem" + FLEX_UNIQUE_USER = "flex-unique-user" + FLEX_USAGE = "flex-usage" + FLEX_USERS = "flex-users" + FLEX_VOICE_MINUTE = "flex-voice-minute" + FLEX_YTICA = "flex-ytica" + FRAUD_LOOKUPS = "fraud-lookups" + FRONTLINE = "frontline" + FRONTLINE_USERS = "frontline-users" + FUNCTIONS = "functions" + GENERIC_PAY_TRANSACTIONS = "generic-pay-transactions" + GROUP_ROOMS = "group-rooms" + GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" + GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" + GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" + GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" + GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" + GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" + GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" + GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" + IP_MESSAGING = "ip-messaging" + IP_MESSAGING_COMMANDS = "ip-messaging-commands" + IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" + IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" + IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" + IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" + IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" + LINE_STATUS_LOOKUPS = "line-status-lookups" + LIVE_ACTIVITY_LOOKUPS = "live-activity-lookups" + LOOKUP_BUCKET_ADJUSTMENT = "lookup-bucket-adjustment" + LOOKUP_IDENTITY_MATCH = "lookup-identity-match" + LOOKUPS = "lookups" + MARKETPLACE = "marketplace" + MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) + MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" + MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" + MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" + MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" + MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION = "marketplace-deepgram-transcription" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE = ( + "marketplace-deepgram-transcription-base" + ) + MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED = ( + "marketplace-deepgram-transscription-enhanced" + ) + MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( + "marketplace-digital-segment-business-info" + ) + MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( + "marketplace-facebook-offline-conversions" + ) + MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" + MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( + "marketplace-ibm-watson-message-insights" + ) + MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( + "marketplace-ibm-watson-message-sentiment" + ) + MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( + "marketplace-ibm-watson-recording-analysis" + ) + MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" + MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" + MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( + "marketplace-infogroup-dataaxle-bizinfo" + ) + MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( + "marketplace-keen-io-contact-center-analytics" + ) + MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" + MARKETPLACE_MARCHEX_RECORDING_ANALYSIS = ( + "marketplace-marchex-recording-analysis" + ) + MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( + "marketplace-marchex-sentiment-analysis-for-sms" + ) + MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( + "marketplace-marketplace-nextcaller-social-id" + ) + MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( + "marketplace-mobile-commons-opt-out-classifier" + ) + MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( + "marketplace-nexiwave-voicemail-to-text" + ) + MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( + "marketplace-nextcaller-advanced-caller-identification" + ) + MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" + MARKETPLACE_PAY_ADDONS = "marketplace-pay-addons" + MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR = ( + "marketplace-pay-addons-basecommerce-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR = ( + "marketplace-pay-addons-braintree-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR = ( + "marketplace-pay-addons-cardconnect-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR = ( + "marketplace-pay-addons-chase-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplace-pay-addons-shuttle-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplace-pay-addons-stripe-pay-connector" + ) + MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" + MARKETPLACE_POLY_AI_CONNECTOR = "marketplace-poly-ai-connector" + MARKETPLACE_REALPHONEVALIDATION = "marketplace-realphonevalidation" + MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( + "marketplace-remeeting-automatic-speech-recognition" + ) + MARKETPLACE_SPOKE_PHONE_LICENSE_PRO = "marketplace-spoke-phone-license-pro" + MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD = ( + "marketplace-spoke-phone-license-standard" + ) + MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( + "marketplace-tcpa-defense-solutions-blacklist-feed" + ) + MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" + MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION = ( + "marketplace-trestle-solutions-caller-identification" + ) + MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" + MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( + "marketplace-twilio-caller-name-lookup-us" + ) + MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( + "marketplace-twilio-carrier-information-lookup" + ) + MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" + MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" + MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) + MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" + MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( + "marketplace-ytica-contact-center-reporting-analytics" + ) + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplay-pay-addons-shuttle-pay-connector" + ) + MEDIA_COMPOSER_MINUTES = "media-composer-minutes" + MEDIASTORAGE = "mediastorage" + MIN_SPEND_ADJUSTMENTS = "min-spend-adjustments" + MMS = "mms" + MMS_INBOUND = "mms-inbound" + MMS_INBOUND_LONGCODE = "mms-inbound-longcode" + MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" + MMS_INBOUND_TOLL_FREE = "mms-inbound-toll-free" + MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" + MMS_OUTBOUND = "mms-outbound" + MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" + MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" + MMS_OUTBOUND_TOLLFREE = "mms-outbound-tollfree" + MONITOR = "monitor" + MONITOR_READS = "monitor-reads" + MONITOR_STORAGE = "monitor-storage" + MONITOR_WRITES = "monitor-writes" + NOTIFY = "notify" + NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" + NOTIFY_CHANNELS = "notify-channels" + NUMBER_FORMAT_LOOKUPS = "number-format-lookups" + PCHAT = "pchat" + PCHAT_ACTIONS = "pchat-actions" + PCHAT_APS = "pchat-aps" + PCHAT_CONV_MED_STORAGE = "pchat-conv-med-storage" + PCHAT_MESSAGES = "pchat-messages" + PCHAT_NOTIFICATIONS = "pchat-notifications" + PCHAT_READS = "pchat-reads" + PCHAT_USERS = "pchat-users" + PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "peer-to-peer-rooms-participant-minutes" + ) + PFAX = "pfax" + PFAX_MINUTES = "pfax-minutes" + PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" + PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" + PFAX_PAGES = "pfax-pages" + PHONE_QUALITY_SCORE_LOOKUPS = "phone-quality-score-lookups" + PHONENUMBERS = "phonenumbers" + PHONENUMBERS_CPS = "phonenumbers-cps" + PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" + PHONENUMBERS_LOCAL = "phonenumbers-local" + PHONENUMBERS_MOBILE = "phonenumbers-mobile" + PHONENUMBERS_PORTING = "phonenumbers-porting" + PHONENUMBERS_SETUPS = "phonenumbers-setups" + PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" + PREMIUMSUPPORT = "premiumsupport" + PREMIUMSUPPORT_PERCENTAGE_SPEND = "premiumsupport-percentage-spend" + PROGRAMMABLEVOICE_PLATFORM = "programmablevoice-platform" + PROGRAMMABLEVOICECONN_CLIENTSDK = "programmablevoiceconn-clientsdk" + PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND = ( + "programmablevoiceconn-clientsdk-inbound" + ) + PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND = ( + "programmablevoiceconn-clientsdk-outbound" + ) + PROGRAMMABLEVOICECONN_ONNET = "programmablevoiceconn-onnet" + PROGRAMMABLEVOICECONN_ONNET_INBOUND = "programmablevoiceconn-onnet-inbound" + PROGRAMMABLEVOICECONN_ONNET_OUTBOUND = "programmablevoiceconn-onnet-outbound" + PROGRAMMABLEVOICECONN_SIP = "programmablevoiceconn-sip" + PROGRAMMABLEVOICECONN_SIP_INBOUND = "programmablevoiceconn-sip-inbound" + PROGRAMMABLEVOICECONN_SIP_OUTBOUND = "programmablevoiceconn-sip-outbound" + PROGRAMMABLEVOICECONNECTIVITY = "programmablevoiceconnectivity" + PROXY = "proxy" + PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" + PROXY_BUCKET_ADJUSTMENT = "proxy-bucket-adjustment" + PROXY_LICENSES = "proxy-licenses" + PSTNCONNECTIVITY = "pstnconnectivity" + PSTNCONNECTIVITY_INBOUND = "pstnconnectivity-inbound" + PSTNCONNECTIVITY_OUTBOUND = "pstnconnectivity-outbound" + PV = "pv" + PV_BASIC_ROOMS = "pv-basic-rooms" + PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" + PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" + PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" + PV_COMPOSITION_MINUTES = "pv-composition-minutes" + PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" + PV_ROOM_PARTICIPANTS = "pv-room-participants" + PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" + PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" + PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" + PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" + PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" + PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" + PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" + PV_ROOMS = "pv-rooms" + PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" + RCS_MESSAGES = "rcs-messages" + REASSIGNED_NUMBER = "reassigned-number" + RECORDINGS = "recordings" + RECORDINGSTORAGE = "recordingstorage" + SHORTCODES = "shortcodes" + SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" + SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" + SHORTCODES_MPS = "shortcodes-mps" + SHORTCODES_RANDOM = "shortcodes-random" + SHORTCODES_SETUP_FEES = "shortcodes-setup-fees" + SHORTCODES_UK = "shortcodes-uk" + SHORTCODES_VANITY = "shortcodes-vanity" + SIM_SWAP_LOOKUPS = "sim-swap-lookups" + SIP_SECURE_MEDIA = "sip-secure-media" + SMALL_GROUP_ROOMS = "small-group-rooms" + SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" + SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" + SMS = "sms" + SMS_INBOUND = "sms-inbound" + SMS_INBOUND_LONGCODE = "sms-inbound-longcode" + SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" + SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" + SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) + SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" + SMS_OUTBOUND = "sms-outbound" + SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" + SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" + SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" + SPEECH_RECOGNITION = "speech-recognition" + STUDIO_ENGAGEMENTS = "studio-engagements" + SYNC = "sync" + SYNC_ACTIONS = "sync-actions" + SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" + SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" + TASKROUTER_TASKS = "taskrouter-tasks" + TOTALPRICE = "totalprice" + TRANSCRIPTIONS = "transcriptions" + TRUNKING_CPS = "trunking-cps" + TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" + TRUNKING_ORIGINATION = "trunking-origination" + TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" + TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" + TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" + TRUNKING_RECORDINGS = "trunking-recordings" + TRUNKING_SECURE = "trunking-secure" + TRUNKING_TERMINATION = "trunking-termination" + TTS_GOOGLE = "tts-google" + TURNMEGABYTES = "turnmegabytes" + TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" + TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" + TURNMEGABYTES_GERMANY = "turnmegabytes-germany" + TURNMEGABYTES_INDIA = "turnmegabytes-india" + TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" + TURNMEGABYTES_JAPAN = "turnmegabytes-japan" + TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" + TURNMEGABYTES_USEAST = "turnmegabytes-useast" + TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" + TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) + VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" + VOICE_INSIGHTS = "voice-insights" + VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-client-insights-on-demand-minute" + ) + VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-ptsn-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-interface-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-trunking-insights-on-demand-minute" + ) + VOICE_INTELLIGENCE = "voice-intelligence" + VOICE_INTELLIGENCE_EIP_OPERATORS = "voice-intelligence-eip-operators" + VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" + VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" + WDS = "wds" + WIRELESS = "wireless" + WIRELESS_DATA = "wireless-data" + WIRELESS_DATA_PAYG = "wireless-data-payg" + WIRELESS_DATA_PAYG_AFRICA = "wireless-data-payg-africa" + WIRELESS_DATA_PAYG_ASIA = "wireless-data-payg-asia" + WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA = ( + "wireless-data-payg-centralandsouthamerica" + ) + WIRELESS_DATA_PAYG_EUROPE = "wireless-data-payg-europe" + WIRELESS_DATA_PAYG_NORTHAMERICA = "wireless-data-payg-northamerica" + WIRELESS_DATA_PAYG_OCEANIA = "wireless-data-payg-oceania" + WIRELESS_DATA_QUOTA1 = "wireless-data-quota1" + WIRELESS_DATA_QUOTA1_AFRICA = "wireless-data-quota1-africa" + WIRELESS_DATA_QUOTA1_ASIA = "wireless-data-quota1-asia" + WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota1-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA1_EUROPE = "wireless-data-quota1-europe" + WIRELESS_DATA_QUOTA1_NORTHAMERICA = "wireless-data-quota1-northamerica" + WIRELESS_DATA_QUOTA1_OCEANIA = "wireless-data-quota1-oceania" + WIRELESS_DATA_QUOTA10 = "wireless-data-quota10" + WIRELESS_DATA_QUOTA10_AFRICA = "wireless-data-quota10-africa" + WIRELESS_DATA_QUOTA10_ASIA = "wireless-data-quota10-asia" + WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota10-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA10_EUROPE = "wireless-data-quota10-europe" + WIRELESS_DATA_QUOTA10_NORTHAMERICA = "wireless-data-quota10-northamerica" + WIRELESS_DATA_QUOTA10_OCEANIA = "wireless-data-quota10-oceania" + WIRELESS_DATA_QUOTA50 = "wireless-data-quota50" + WIRELESS_DATA_QUOTA50_AFRICA = "wireless-data-quota50-africa" + WIRELESS_DATA_QUOTA50_ASIA = "wireless-data-quota50-asia" + WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota50-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA50_EUROPE = "wireless-data-quota50-europe" + WIRELESS_DATA_QUOTA50_NORTHAMERICA = "wireless-data-quota50-northamerica" + WIRELESS_DATA_QUOTA50_OCEANIA = "wireless-data-quota50-oceania" + WIRELESS_DATA_QUOTACUSTOM = "wireless-data-quotacustom" + WIRELESS_DATA_QUOTACUSTOM_AFRICA = "wireless-data-quotacustom-africa" + WIRELESS_DATA_QUOTACUSTOM_ASIA = "wireless-data-quotacustom-asia" + WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quotacustom-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_EUROPE = "wireless-data-quotacustom-europe" + WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA = ( + "wireless-data-quotacustom-northamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_OCEANIA = "wireless-data-quotacustom-oceania" + WIRELESS_MRC_PAYG = "wireless-mrc-payg" + WIRELESS_MRC_QUOTA1 = "wireless-mrc-quota1" + WIRELESS_MRC_QUOTA10 = "wireless-mrc-quota10" + WIRELESS_MRC_QUOTA50 = "wireless-mrc-quota50" + WIRELESS_MRC_QUOTACUSTOM = "wireless-mrc-quotacustom" + WIRELESS_ORDERS = "wireless-orders" + WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" + WIRELESS_ORDERS_BULK = "wireless-orders-bulk" + WIRELESS_ORDERS_ESIM = "wireless-orders-esim" + WIRELESS_ORDERS_STARTER = "wireless-orders-starter" + WIRELESS_QUOTAS = "wireless-quotas" + WIRELESS_SMS_AFRICA = "wireless-sms-africa" + WIRELESS_SMS_ASIA = "wireless-sms-asia" + WIRELESS_SMS_CENTRALANDSOUTHAMERICA = "wireless-sms-centralandsouthamerica" + WIRELESS_SMS_EUROPE = "wireless-sms-europe" + WIRELESS_SMS_NORTHAMERICA = "wireless-sms-northamerica" + WIRELESS_SMS_OCEANIA = "wireless-sms-oceania" + WIRELESS_SUPER_SIM = "wireless-super-sim" + WIRELESS_SUPER_SIM_DATA = "wireless-super-sim-data" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA = ( + "wireless-super-sim-data-north-america-usa" + ) + WIRELESS_SUPER_SIM_DATA_PAYG = "wireless-super-sim-data-payg" + WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE = "wireless-super-sim-data-payg-europe" + WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA = ( + "wireless-super-sim-data-payg-north-america" + ) + WIRELESS_SUPER_SIM_HARDWARE = "wireless-super-sim-hardware" + WIRELESS_SUPER_SIM_HARDWARE_BULK = "wireless-super-sim-hardware-bulk" + WIRELESS_SUPER_SIM_SMSCOMMANDS = "wireless-super-sim-smscommands" + WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA = "wireless-super-sim-smscommands-africa" + WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA = "wireless-super-sim-smscommands-asia" + WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA = ( + "wireless-super-sim-smscommands-cent-and-south-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE = "wireless-super-sim-smscommands-europe" + WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA = ( + "wireless-super-sim-smscommands-north-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA = ( + "wireless-super-sim-smscommands-oceania" + ) + WIRELESS_SUPER_SIM_SUBSCRIPTION = "wireless-super-sim-subscription" + WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG = "wireless-super-sim-subscription-payg" + WIRELESS_USAGE = "wireless-usage" + WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" + WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" + WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" + WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-commands-centralandsouthamerica" + ) + WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" + WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" + WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" + WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" + WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" + WIRELESS_USAGE_DATA = "wireless-usage-data" + WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" + WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" + WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-data-centralandsouthamerica" + ) + WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( + "wireless-usage-data-custom-additionalmb" + ) + WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" + WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" + WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" + WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( + "wireless-usage-data-individual-additionalgb" + ) + WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( + "wireless-usage-data-individual-firstgb" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( + "wireless-usage-data-international-roaming-canada" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( + "wireless-usage-data-international-roaming-india" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( + "wireless-usage-data-international-roaming-mexico" + ) + WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" + WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" + WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" + WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" + WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" + WIRELESS_USAGE_MRC = "wireless-usage-mrc" + WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" + WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" + WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" + WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" + WIRELESS_USAGE_SMS = "wireless-usage-sms" + WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + :ivar api_version: The API version used to create the resource. + :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + :ivar category: + :ivar count: The number of usage events, such as the number of calls. + :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + :ivar description: A plain-language description of the usage category. + :ivar end_date: The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar price: The total price of the usage in the currency specified in `price_unit` and associated with the account. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + :ivar start_date: The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar subresource_uris: A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage: The amount used to bill usage and measured in units described in `usage_unit`. + :ivar usage_unit: The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.as_of: Optional[str] = payload.get("as_of") + self.category: Optional["LastMonthInstance.Category"] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.LastMonthInstance {}>".format(context) + + +class LastMonthPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> LastMonthInstance: + """ + Build an instance of LastMonthInstance + + :param payload: Payload response from the API + """ + return LastMonthInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.LastMonthPage>" + + +class LastMonthList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the LastMonthList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/LastMonth.json".format( + **self._solution + ) + + def stream( + self, + category: Union["LastMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[LastMonthInstance]: + """ + Streams LastMonthInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "LastMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + category: Union["LastMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[LastMonthInstance]: + """ + Asynchronously streams LastMonthInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "LastMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["LastMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LastMonthInstance]: + """ + Lists LastMonthInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "LastMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + category: Union["LastMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LastMonthInstance]: + """ + Asynchronously lists LastMonthInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "LastMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + category: Union["LastMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LastMonthPage: + """ + Retrieve a single page of LastMonthInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LastMonthInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LastMonthPage(self._version, response, self._solution) + + async def page_async( + self, + category: Union["LastMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LastMonthPage: + """ + Asynchronously retrieve a single page of LastMonthInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LastMonthInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LastMonthPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> LastMonthPage: + """ + Retrieve a specific page of LastMonthInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of LastMonthInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return LastMonthPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> LastMonthPage: + """ + Asynchronously retrieve a specific page of LastMonthInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of LastMonthInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return LastMonthPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.LastMonthList>" diff --git a/twilio/rest/api/v2010/account/usage/record/monthly.py b/twilio/rest/api/v2010/account/usage/record/monthly.py new file mode 100644 index 0000000000..117db692bf --- /dev/null +++ b/twilio/rest/api/v2010/account/usage/record/monthly.py @@ -0,0 +1,1211 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MonthlyInstance(InstanceResource): + + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" + AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" + ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" + AUTHY_AUTHENTICATIONS = "authy-authentications" + AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" + AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" + AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" + AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" + AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" + CALL_PROGESS_EVENTS = "call-progess-events" + CALLERIDLOOKUPS = "calleridlookups" + CALLS = "calls" + CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" + CALLS_GLOBALCONFERENCE = "calls-globalconference" + CALLS_INBOUND = "calls-inbound" + CALLS_INBOUND_LOCAL = "calls-inbound-local" + CALLS_INBOUND_MOBILE = "calls-inbound-mobile" + CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" + CALLS_OUTBOUND = "calls-outbound" + CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" + CALLS_RECORDINGS = "calls-recordings" + CALLS_SIP = "calls-sip" + CALLS_SIP_INBOUND = "calls-sip-inbound" + CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" + CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" + CONVERSATIONS = "conversations" + CONVERSATIONS_API_REQUESTS = "conversations-api-requests" + CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" + CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" + CONVERSATIONS_EVENTS = "conversations-events" + CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" + CONVERSATIONS_PARTICIPANTS = "conversations-participants" + CPS = "cps" + CREDIT_TRANSFER = "credit-transfer" + EMAIL = "email" + EMERGING_TECH = "emerging-tech" + ENGAGEMENT_SUITE_PACKAGED_PLANS = "engagement-suite-packaged-plans" + ENHANCED_LINE_TYPE_LOOKUPS = "enhanced-line-type-lookups" + ENTERPRISE = "enterprise" + EVENTS = "events" + EXPERIMENT_FRANCE_SMS = "experiment-france-sms" + EXPERIMENT_INDIA_SMS = "experiment-india-sms" + EXPERIMENT_UK_SMS = "experiment-uk-sms" + FAILED_MESSAGE_PROCESSING_FEE = "failed-message-processing-fee" + FLEX = "flex" + FLEX_ACTIVE_USER_HOURS = "flex-active-user-hours" + FLEX_CONCURRENT_USERS = "flex-concurrent-users" + FLEX_CONVERSATIONAL_INSIGHTS = "flex-conversational-insights" + FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES = "flex-conversational-insights-messages" + FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = ( + "flex-conversational-insights-voice-minutes" + ) + FLEX_EMAIL_USAGE = "flex-email-usage" + FLEX_MESSAGING_USAGE = "flex-messaging-usage" + FLEX_PARTNER_SPINSCI = "flex-partner-spinsci" + FLEX_PARTNER_XCELERATE = "flex-partner-xcelerate" + FLEX_RESELLER_ECOSYSTEM = "flex-reseller-ecosystem" + FLEX_UNIQUE_USER = "flex-unique-user" + FLEX_USAGE = "flex-usage" + FLEX_USERS = "flex-users" + FLEX_VOICE_MINUTE = "flex-voice-minute" + FLEX_YTICA = "flex-ytica" + FRAUD_LOOKUPS = "fraud-lookups" + FRONTLINE = "frontline" + FRONTLINE_USERS = "frontline-users" + FUNCTIONS = "functions" + GENERIC_PAY_TRANSACTIONS = "generic-pay-transactions" + GROUP_ROOMS = "group-rooms" + GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" + GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" + GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" + GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" + GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" + GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" + GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" + GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" + IP_MESSAGING = "ip-messaging" + IP_MESSAGING_COMMANDS = "ip-messaging-commands" + IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" + IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" + IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" + IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" + IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" + LINE_STATUS_LOOKUPS = "line-status-lookups" + LIVE_ACTIVITY_LOOKUPS = "live-activity-lookups" + LOOKUP_BUCKET_ADJUSTMENT = "lookup-bucket-adjustment" + LOOKUP_IDENTITY_MATCH = "lookup-identity-match" + LOOKUPS = "lookups" + MARKETPLACE = "marketplace" + MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) + MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" + MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" + MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" + MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" + MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION = "marketplace-deepgram-transcription" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE = ( + "marketplace-deepgram-transcription-base" + ) + MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED = ( + "marketplace-deepgram-transscription-enhanced" + ) + MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( + "marketplace-digital-segment-business-info" + ) + MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( + "marketplace-facebook-offline-conversions" + ) + MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" + MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( + "marketplace-ibm-watson-message-insights" + ) + MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( + "marketplace-ibm-watson-message-sentiment" + ) + MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( + "marketplace-ibm-watson-recording-analysis" + ) + MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" + MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" + MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( + "marketplace-infogroup-dataaxle-bizinfo" + ) + MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( + "marketplace-keen-io-contact-center-analytics" + ) + MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" + MARKETPLACE_MARCHEX_RECORDING_ANALYSIS = ( + "marketplace-marchex-recording-analysis" + ) + MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( + "marketplace-marchex-sentiment-analysis-for-sms" + ) + MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( + "marketplace-marketplace-nextcaller-social-id" + ) + MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( + "marketplace-mobile-commons-opt-out-classifier" + ) + MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( + "marketplace-nexiwave-voicemail-to-text" + ) + MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( + "marketplace-nextcaller-advanced-caller-identification" + ) + MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" + MARKETPLACE_PAY_ADDONS = "marketplace-pay-addons" + MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR = ( + "marketplace-pay-addons-basecommerce-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR = ( + "marketplace-pay-addons-braintree-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR = ( + "marketplace-pay-addons-cardconnect-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR = ( + "marketplace-pay-addons-chase-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplace-pay-addons-shuttle-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplace-pay-addons-stripe-pay-connector" + ) + MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" + MARKETPLACE_POLY_AI_CONNECTOR = "marketplace-poly-ai-connector" + MARKETPLACE_REALPHONEVALIDATION = "marketplace-realphonevalidation" + MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( + "marketplace-remeeting-automatic-speech-recognition" + ) + MARKETPLACE_SPOKE_PHONE_LICENSE_PRO = "marketplace-spoke-phone-license-pro" + MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD = ( + "marketplace-spoke-phone-license-standard" + ) + MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( + "marketplace-tcpa-defense-solutions-blacklist-feed" + ) + MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" + MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION = ( + "marketplace-trestle-solutions-caller-identification" + ) + MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" + MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( + "marketplace-twilio-caller-name-lookup-us" + ) + MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( + "marketplace-twilio-carrier-information-lookup" + ) + MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" + MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" + MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) + MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" + MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( + "marketplace-ytica-contact-center-reporting-analytics" + ) + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplay-pay-addons-shuttle-pay-connector" + ) + MEDIA_COMPOSER_MINUTES = "media-composer-minutes" + MEDIASTORAGE = "mediastorage" + MIN_SPEND_ADJUSTMENTS = "min-spend-adjustments" + MMS = "mms" + MMS_INBOUND = "mms-inbound" + MMS_INBOUND_LONGCODE = "mms-inbound-longcode" + MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" + MMS_INBOUND_TOLL_FREE = "mms-inbound-toll-free" + MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" + MMS_OUTBOUND = "mms-outbound" + MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" + MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" + MMS_OUTBOUND_TOLLFREE = "mms-outbound-tollfree" + MONITOR = "monitor" + MONITOR_READS = "monitor-reads" + MONITOR_STORAGE = "monitor-storage" + MONITOR_WRITES = "monitor-writes" + NOTIFY = "notify" + NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" + NOTIFY_CHANNELS = "notify-channels" + NUMBER_FORMAT_LOOKUPS = "number-format-lookups" + PCHAT = "pchat" + PCHAT_ACTIONS = "pchat-actions" + PCHAT_APS = "pchat-aps" + PCHAT_CONV_MED_STORAGE = "pchat-conv-med-storage" + PCHAT_MESSAGES = "pchat-messages" + PCHAT_NOTIFICATIONS = "pchat-notifications" + PCHAT_READS = "pchat-reads" + PCHAT_USERS = "pchat-users" + PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "peer-to-peer-rooms-participant-minutes" + ) + PFAX = "pfax" + PFAX_MINUTES = "pfax-minutes" + PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" + PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" + PFAX_PAGES = "pfax-pages" + PHONE_QUALITY_SCORE_LOOKUPS = "phone-quality-score-lookups" + PHONENUMBERS = "phonenumbers" + PHONENUMBERS_CPS = "phonenumbers-cps" + PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" + PHONENUMBERS_LOCAL = "phonenumbers-local" + PHONENUMBERS_MOBILE = "phonenumbers-mobile" + PHONENUMBERS_PORTING = "phonenumbers-porting" + PHONENUMBERS_SETUPS = "phonenumbers-setups" + PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" + PREMIUMSUPPORT = "premiumsupport" + PREMIUMSUPPORT_PERCENTAGE_SPEND = "premiumsupport-percentage-spend" + PROGRAMMABLEVOICE_PLATFORM = "programmablevoice-platform" + PROGRAMMABLEVOICECONN_CLIENTSDK = "programmablevoiceconn-clientsdk" + PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND = ( + "programmablevoiceconn-clientsdk-inbound" + ) + PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND = ( + "programmablevoiceconn-clientsdk-outbound" + ) + PROGRAMMABLEVOICECONN_ONNET = "programmablevoiceconn-onnet" + PROGRAMMABLEVOICECONN_ONNET_INBOUND = "programmablevoiceconn-onnet-inbound" + PROGRAMMABLEVOICECONN_ONNET_OUTBOUND = "programmablevoiceconn-onnet-outbound" + PROGRAMMABLEVOICECONN_SIP = "programmablevoiceconn-sip" + PROGRAMMABLEVOICECONN_SIP_INBOUND = "programmablevoiceconn-sip-inbound" + PROGRAMMABLEVOICECONN_SIP_OUTBOUND = "programmablevoiceconn-sip-outbound" + PROGRAMMABLEVOICECONNECTIVITY = "programmablevoiceconnectivity" + PROXY = "proxy" + PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" + PROXY_BUCKET_ADJUSTMENT = "proxy-bucket-adjustment" + PROXY_LICENSES = "proxy-licenses" + PSTNCONNECTIVITY = "pstnconnectivity" + PSTNCONNECTIVITY_INBOUND = "pstnconnectivity-inbound" + PSTNCONNECTIVITY_OUTBOUND = "pstnconnectivity-outbound" + PV = "pv" + PV_BASIC_ROOMS = "pv-basic-rooms" + PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" + PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" + PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" + PV_COMPOSITION_MINUTES = "pv-composition-minutes" + PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" + PV_ROOM_PARTICIPANTS = "pv-room-participants" + PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" + PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" + PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" + PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" + PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" + PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" + PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" + PV_ROOMS = "pv-rooms" + PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" + RCS_MESSAGES = "rcs-messages" + REASSIGNED_NUMBER = "reassigned-number" + RECORDINGS = "recordings" + RECORDINGSTORAGE = "recordingstorage" + SHORTCODES = "shortcodes" + SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" + SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" + SHORTCODES_MPS = "shortcodes-mps" + SHORTCODES_RANDOM = "shortcodes-random" + SHORTCODES_SETUP_FEES = "shortcodes-setup-fees" + SHORTCODES_UK = "shortcodes-uk" + SHORTCODES_VANITY = "shortcodes-vanity" + SIM_SWAP_LOOKUPS = "sim-swap-lookups" + SIP_SECURE_MEDIA = "sip-secure-media" + SMALL_GROUP_ROOMS = "small-group-rooms" + SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" + SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" + SMS = "sms" + SMS_INBOUND = "sms-inbound" + SMS_INBOUND_LONGCODE = "sms-inbound-longcode" + SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" + SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" + SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) + SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" + SMS_OUTBOUND = "sms-outbound" + SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" + SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" + SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" + SPEECH_RECOGNITION = "speech-recognition" + STUDIO_ENGAGEMENTS = "studio-engagements" + SYNC = "sync" + SYNC_ACTIONS = "sync-actions" + SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" + SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" + TASKROUTER_TASKS = "taskrouter-tasks" + TOTALPRICE = "totalprice" + TRANSCRIPTIONS = "transcriptions" + TRUNKING_CPS = "trunking-cps" + TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" + TRUNKING_ORIGINATION = "trunking-origination" + TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" + TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" + TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" + TRUNKING_RECORDINGS = "trunking-recordings" + TRUNKING_SECURE = "trunking-secure" + TRUNKING_TERMINATION = "trunking-termination" + TTS_GOOGLE = "tts-google" + TURNMEGABYTES = "turnmegabytes" + TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" + TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" + TURNMEGABYTES_GERMANY = "turnmegabytes-germany" + TURNMEGABYTES_INDIA = "turnmegabytes-india" + TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" + TURNMEGABYTES_JAPAN = "turnmegabytes-japan" + TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" + TURNMEGABYTES_USEAST = "turnmegabytes-useast" + TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" + TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) + VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" + VOICE_INSIGHTS = "voice-insights" + VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-client-insights-on-demand-minute" + ) + VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-ptsn-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-interface-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-trunking-insights-on-demand-minute" + ) + VOICE_INTELLIGENCE = "voice-intelligence" + VOICE_INTELLIGENCE_EIP_OPERATORS = "voice-intelligence-eip-operators" + VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" + VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" + WDS = "wds" + WIRELESS = "wireless" + WIRELESS_DATA = "wireless-data" + WIRELESS_DATA_PAYG = "wireless-data-payg" + WIRELESS_DATA_PAYG_AFRICA = "wireless-data-payg-africa" + WIRELESS_DATA_PAYG_ASIA = "wireless-data-payg-asia" + WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA = ( + "wireless-data-payg-centralandsouthamerica" + ) + WIRELESS_DATA_PAYG_EUROPE = "wireless-data-payg-europe" + WIRELESS_DATA_PAYG_NORTHAMERICA = "wireless-data-payg-northamerica" + WIRELESS_DATA_PAYG_OCEANIA = "wireless-data-payg-oceania" + WIRELESS_DATA_QUOTA1 = "wireless-data-quota1" + WIRELESS_DATA_QUOTA1_AFRICA = "wireless-data-quota1-africa" + WIRELESS_DATA_QUOTA1_ASIA = "wireless-data-quota1-asia" + WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota1-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA1_EUROPE = "wireless-data-quota1-europe" + WIRELESS_DATA_QUOTA1_NORTHAMERICA = "wireless-data-quota1-northamerica" + WIRELESS_DATA_QUOTA1_OCEANIA = "wireless-data-quota1-oceania" + WIRELESS_DATA_QUOTA10 = "wireless-data-quota10" + WIRELESS_DATA_QUOTA10_AFRICA = "wireless-data-quota10-africa" + WIRELESS_DATA_QUOTA10_ASIA = "wireless-data-quota10-asia" + WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota10-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA10_EUROPE = "wireless-data-quota10-europe" + WIRELESS_DATA_QUOTA10_NORTHAMERICA = "wireless-data-quota10-northamerica" + WIRELESS_DATA_QUOTA10_OCEANIA = "wireless-data-quota10-oceania" + WIRELESS_DATA_QUOTA50 = "wireless-data-quota50" + WIRELESS_DATA_QUOTA50_AFRICA = "wireless-data-quota50-africa" + WIRELESS_DATA_QUOTA50_ASIA = "wireless-data-quota50-asia" + WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota50-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA50_EUROPE = "wireless-data-quota50-europe" + WIRELESS_DATA_QUOTA50_NORTHAMERICA = "wireless-data-quota50-northamerica" + WIRELESS_DATA_QUOTA50_OCEANIA = "wireless-data-quota50-oceania" + WIRELESS_DATA_QUOTACUSTOM = "wireless-data-quotacustom" + WIRELESS_DATA_QUOTACUSTOM_AFRICA = "wireless-data-quotacustom-africa" + WIRELESS_DATA_QUOTACUSTOM_ASIA = "wireless-data-quotacustom-asia" + WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quotacustom-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_EUROPE = "wireless-data-quotacustom-europe" + WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA = ( + "wireless-data-quotacustom-northamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_OCEANIA = "wireless-data-quotacustom-oceania" + WIRELESS_MRC_PAYG = "wireless-mrc-payg" + WIRELESS_MRC_QUOTA1 = "wireless-mrc-quota1" + WIRELESS_MRC_QUOTA10 = "wireless-mrc-quota10" + WIRELESS_MRC_QUOTA50 = "wireless-mrc-quota50" + WIRELESS_MRC_QUOTACUSTOM = "wireless-mrc-quotacustom" + WIRELESS_ORDERS = "wireless-orders" + WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" + WIRELESS_ORDERS_BULK = "wireless-orders-bulk" + WIRELESS_ORDERS_ESIM = "wireless-orders-esim" + WIRELESS_ORDERS_STARTER = "wireless-orders-starter" + WIRELESS_QUOTAS = "wireless-quotas" + WIRELESS_SMS_AFRICA = "wireless-sms-africa" + WIRELESS_SMS_ASIA = "wireless-sms-asia" + WIRELESS_SMS_CENTRALANDSOUTHAMERICA = "wireless-sms-centralandsouthamerica" + WIRELESS_SMS_EUROPE = "wireless-sms-europe" + WIRELESS_SMS_NORTHAMERICA = "wireless-sms-northamerica" + WIRELESS_SMS_OCEANIA = "wireless-sms-oceania" + WIRELESS_SUPER_SIM = "wireless-super-sim" + WIRELESS_SUPER_SIM_DATA = "wireless-super-sim-data" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA = ( + "wireless-super-sim-data-north-america-usa" + ) + WIRELESS_SUPER_SIM_DATA_PAYG = "wireless-super-sim-data-payg" + WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE = "wireless-super-sim-data-payg-europe" + WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA = ( + "wireless-super-sim-data-payg-north-america" + ) + WIRELESS_SUPER_SIM_HARDWARE = "wireless-super-sim-hardware" + WIRELESS_SUPER_SIM_HARDWARE_BULK = "wireless-super-sim-hardware-bulk" + WIRELESS_SUPER_SIM_SMSCOMMANDS = "wireless-super-sim-smscommands" + WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA = "wireless-super-sim-smscommands-africa" + WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA = "wireless-super-sim-smscommands-asia" + WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA = ( + "wireless-super-sim-smscommands-cent-and-south-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE = "wireless-super-sim-smscommands-europe" + WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA = ( + "wireless-super-sim-smscommands-north-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA = ( + "wireless-super-sim-smscommands-oceania" + ) + WIRELESS_SUPER_SIM_SUBSCRIPTION = "wireless-super-sim-subscription" + WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG = "wireless-super-sim-subscription-payg" + WIRELESS_USAGE = "wireless-usage" + WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" + WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" + WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" + WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-commands-centralandsouthamerica" + ) + WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" + WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" + WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" + WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" + WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" + WIRELESS_USAGE_DATA = "wireless-usage-data" + WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" + WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" + WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-data-centralandsouthamerica" + ) + WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( + "wireless-usage-data-custom-additionalmb" + ) + WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" + WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" + WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" + WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( + "wireless-usage-data-individual-additionalgb" + ) + WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( + "wireless-usage-data-individual-firstgb" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( + "wireless-usage-data-international-roaming-canada" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( + "wireless-usage-data-international-roaming-india" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( + "wireless-usage-data-international-roaming-mexico" + ) + WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" + WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" + WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" + WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" + WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" + WIRELESS_USAGE_MRC = "wireless-usage-mrc" + WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" + WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" + WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" + WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" + WIRELESS_USAGE_SMS = "wireless-usage-sms" + WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + :ivar api_version: The API version used to create the resource. + :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + :ivar category: + :ivar count: The number of usage events, such as the number of calls. + :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + :ivar description: A plain-language description of the usage category. + :ivar end_date: The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar price: The total price of the usage in the currency specified in `price_unit` and associated with the account. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + :ivar start_date: The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar subresource_uris: A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage: The amount used to bill usage and measured in units described in `usage_unit`. + :ivar usage_unit: The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.as_of: Optional[str] = payload.get("as_of") + self.category: Optional["MonthlyInstance.Category"] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.MonthlyInstance {}>".format(context) + + +class MonthlyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MonthlyInstance: + """ + Build an instance of MonthlyInstance + + :param payload: Payload response from the API + """ + return MonthlyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.MonthlyPage>" + + +class MonthlyList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the MonthlyList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/Monthly.json".format( + **self._solution + ) + + def stream( + self, + category: Union["MonthlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MonthlyInstance]: + """ + Streams MonthlyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MonthlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + category: Union["MonthlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MonthlyInstance]: + """ + Asynchronously streams MonthlyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MonthlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["MonthlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MonthlyInstance]: + """ + Lists MonthlyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MonthlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + category: Union["MonthlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MonthlyInstance]: + """ + Asynchronously lists MonthlyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MonthlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + category: Union["MonthlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MonthlyPage: + """ + Retrieve a single page of MonthlyInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MonthlyInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MonthlyPage(self._version, response, self._solution) + + async def page_async( + self, + category: Union["MonthlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MonthlyPage: + """ + Asynchronously retrieve a single page of MonthlyInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MonthlyInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MonthlyPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MonthlyPage: + """ + Retrieve a specific page of MonthlyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MonthlyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MonthlyPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MonthlyPage: + """ + Asynchronously retrieve a specific page of MonthlyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MonthlyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MonthlyPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.MonthlyList>" diff --git a/twilio/rest/api/v2010/account/usage/record/this_month.py b/twilio/rest/api/v2010/account/usage/record/this_month.py new file mode 100644 index 0000000000..ab65a177d3 --- /dev/null +++ b/twilio/rest/api/v2010/account/usage/record/this_month.py @@ -0,0 +1,1211 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ThisMonthInstance(InstanceResource): + + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" + AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" + ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" + AUTHY_AUTHENTICATIONS = "authy-authentications" + AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" + AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" + AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" + AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" + AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" + CALL_PROGESS_EVENTS = "call-progess-events" + CALLERIDLOOKUPS = "calleridlookups" + CALLS = "calls" + CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" + CALLS_GLOBALCONFERENCE = "calls-globalconference" + CALLS_INBOUND = "calls-inbound" + CALLS_INBOUND_LOCAL = "calls-inbound-local" + CALLS_INBOUND_MOBILE = "calls-inbound-mobile" + CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" + CALLS_OUTBOUND = "calls-outbound" + CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" + CALLS_RECORDINGS = "calls-recordings" + CALLS_SIP = "calls-sip" + CALLS_SIP_INBOUND = "calls-sip-inbound" + CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" + CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" + CONVERSATIONS = "conversations" + CONVERSATIONS_API_REQUESTS = "conversations-api-requests" + CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" + CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" + CONVERSATIONS_EVENTS = "conversations-events" + CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" + CONVERSATIONS_PARTICIPANTS = "conversations-participants" + CPS = "cps" + CREDIT_TRANSFER = "credit-transfer" + EMAIL = "email" + EMERGING_TECH = "emerging-tech" + ENGAGEMENT_SUITE_PACKAGED_PLANS = "engagement-suite-packaged-plans" + ENHANCED_LINE_TYPE_LOOKUPS = "enhanced-line-type-lookups" + ENTERPRISE = "enterprise" + EVENTS = "events" + EXPERIMENT_FRANCE_SMS = "experiment-france-sms" + EXPERIMENT_INDIA_SMS = "experiment-india-sms" + EXPERIMENT_UK_SMS = "experiment-uk-sms" + FAILED_MESSAGE_PROCESSING_FEE = "failed-message-processing-fee" + FLEX = "flex" + FLEX_ACTIVE_USER_HOURS = "flex-active-user-hours" + FLEX_CONCURRENT_USERS = "flex-concurrent-users" + FLEX_CONVERSATIONAL_INSIGHTS = "flex-conversational-insights" + FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES = "flex-conversational-insights-messages" + FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = ( + "flex-conversational-insights-voice-minutes" + ) + FLEX_EMAIL_USAGE = "flex-email-usage" + FLEX_MESSAGING_USAGE = "flex-messaging-usage" + FLEX_PARTNER_SPINSCI = "flex-partner-spinsci" + FLEX_PARTNER_XCELERATE = "flex-partner-xcelerate" + FLEX_RESELLER_ECOSYSTEM = "flex-reseller-ecosystem" + FLEX_UNIQUE_USER = "flex-unique-user" + FLEX_USAGE = "flex-usage" + FLEX_USERS = "flex-users" + FLEX_VOICE_MINUTE = "flex-voice-minute" + FLEX_YTICA = "flex-ytica" + FRAUD_LOOKUPS = "fraud-lookups" + FRONTLINE = "frontline" + FRONTLINE_USERS = "frontline-users" + FUNCTIONS = "functions" + GENERIC_PAY_TRANSACTIONS = "generic-pay-transactions" + GROUP_ROOMS = "group-rooms" + GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" + GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" + GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" + GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" + GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" + GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" + GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" + GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" + IP_MESSAGING = "ip-messaging" + IP_MESSAGING_COMMANDS = "ip-messaging-commands" + IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" + IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" + IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" + IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" + IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" + LINE_STATUS_LOOKUPS = "line-status-lookups" + LIVE_ACTIVITY_LOOKUPS = "live-activity-lookups" + LOOKUP_BUCKET_ADJUSTMENT = "lookup-bucket-adjustment" + LOOKUP_IDENTITY_MATCH = "lookup-identity-match" + LOOKUPS = "lookups" + MARKETPLACE = "marketplace" + MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) + MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" + MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" + MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" + MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" + MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION = "marketplace-deepgram-transcription" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE = ( + "marketplace-deepgram-transcription-base" + ) + MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED = ( + "marketplace-deepgram-transscription-enhanced" + ) + MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( + "marketplace-digital-segment-business-info" + ) + MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( + "marketplace-facebook-offline-conversions" + ) + MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" + MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( + "marketplace-ibm-watson-message-insights" + ) + MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( + "marketplace-ibm-watson-message-sentiment" + ) + MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( + "marketplace-ibm-watson-recording-analysis" + ) + MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" + MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" + MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( + "marketplace-infogroup-dataaxle-bizinfo" + ) + MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( + "marketplace-keen-io-contact-center-analytics" + ) + MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" + MARKETPLACE_MARCHEX_RECORDING_ANALYSIS = ( + "marketplace-marchex-recording-analysis" + ) + MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( + "marketplace-marchex-sentiment-analysis-for-sms" + ) + MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( + "marketplace-marketplace-nextcaller-social-id" + ) + MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( + "marketplace-mobile-commons-opt-out-classifier" + ) + MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( + "marketplace-nexiwave-voicemail-to-text" + ) + MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( + "marketplace-nextcaller-advanced-caller-identification" + ) + MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" + MARKETPLACE_PAY_ADDONS = "marketplace-pay-addons" + MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR = ( + "marketplace-pay-addons-basecommerce-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR = ( + "marketplace-pay-addons-braintree-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR = ( + "marketplace-pay-addons-cardconnect-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR = ( + "marketplace-pay-addons-chase-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplace-pay-addons-shuttle-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplace-pay-addons-stripe-pay-connector" + ) + MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" + MARKETPLACE_POLY_AI_CONNECTOR = "marketplace-poly-ai-connector" + MARKETPLACE_REALPHONEVALIDATION = "marketplace-realphonevalidation" + MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( + "marketplace-remeeting-automatic-speech-recognition" + ) + MARKETPLACE_SPOKE_PHONE_LICENSE_PRO = "marketplace-spoke-phone-license-pro" + MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD = ( + "marketplace-spoke-phone-license-standard" + ) + MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( + "marketplace-tcpa-defense-solutions-blacklist-feed" + ) + MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" + MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION = ( + "marketplace-trestle-solutions-caller-identification" + ) + MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" + MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( + "marketplace-twilio-caller-name-lookup-us" + ) + MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( + "marketplace-twilio-carrier-information-lookup" + ) + MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" + MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" + MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) + MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" + MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( + "marketplace-ytica-contact-center-reporting-analytics" + ) + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplay-pay-addons-shuttle-pay-connector" + ) + MEDIA_COMPOSER_MINUTES = "media-composer-minutes" + MEDIASTORAGE = "mediastorage" + MIN_SPEND_ADJUSTMENTS = "min-spend-adjustments" + MMS = "mms" + MMS_INBOUND = "mms-inbound" + MMS_INBOUND_LONGCODE = "mms-inbound-longcode" + MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" + MMS_INBOUND_TOLL_FREE = "mms-inbound-toll-free" + MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" + MMS_OUTBOUND = "mms-outbound" + MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" + MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" + MMS_OUTBOUND_TOLLFREE = "mms-outbound-tollfree" + MONITOR = "monitor" + MONITOR_READS = "monitor-reads" + MONITOR_STORAGE = "monitor-storage" + MONITOR_WRITES = "monitor-writes" + NOTIFY = "notify" + NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" + NOTIFY_CHANNELS = "notify-channels" + NUMBER_FORMAT_LOOKUPS = "number-format-lookups" + PCHAT = "pchat" + PCHAT_ACTIONS = "pchat-actions" + PCHAT_APS = "pchat-aps" + PCHAT_CONV_MED_STORAGE = "pchat-conv-med-storage" + PCHAT_MESSAGES = "pchat-messages" + PCHAT_NOTIFICATIONS = "pchat-notifications" + PCHAT_READS = "pchat-reads" + PCHAT_USERS = "pchat-users" + PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "peer-to-peer-rooms-participant-minutes" + ) + PFAX = "pfax" + PFAX_MINUTES = "pfax-minutes" + PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" + PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" + PFAX_PAGES = "pfax-pages" + PHONE_QUALITY_SCORE_LOOKUPS = "phone-quality-score-lookups" + PHONENUMBERS = "phonenumbers" + PHONENUMBERS_CPS = "phonenumbers-cps" + PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" + PHONENUMBERS_LOCAL = "phonenumbers-local" + PHONENUMBERS_MOBILE = "phonenumbers-mobile" + PHONENUMBERS_PORTING = "phonenumbers-porting" + PHONENUMBERS_SETUPS = "phonenumbers-setups" + PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" + PREMIUMSUPPORT = "premiumsupport" + PREMIUMSUPPORT_PERCENTAGE_SPEND = "premiumsupport-percentage-spend" + PROGRAMMABLEVOICE_PLATFORM = "programmablevoice-platform" + PROGRAMMABLEVOICECONN_CLIENTSDK = "programmablevoiceconn-clientsdk" + PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND = ( + "programmablevoiceconn-clientsdk-inbound" + ) + PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND = ( + "programmablevoiceconn-clientsdk-outbound" + ) + PROGRAMMABLEVOICECONN_ONNET = "programmablevoiceconn-onnet" + PROGRAMMABLEVOICECONN_ONNET_INBOUND = "programmablevoiceconn-onnet-inbound" + PROGRAMMABLEVOICECONN_ONNET_OUTBOUND = "programmablevoiceconn-onnet-outbound" + PROGRAMMABLEVOICECONN_SIP = "programmablevoiceconn-sip" + PROGRAMMABLEVOICECONN_SIP_INBOUND = "programmablevoiceconn-sip-inbound" + PROGRAMMABLEVOICECONN_SIP_OUTBOUND = "programmablevoiceconn-sip-outbound" + PROGRAMMABLEVOICECONNECTIVITY = "programmablevoiceconnectivity" + PROXY = "proxy" + PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" + PROXY_BUCKET_ADJUSTMENT = "proxy-bucket-adjustment" + PROXY_LICENSES = "proxy-licenses" + PSTNCONNECTIVITY = "pstnconnectivity" + PSTNCONNECTIVITY_INBOUND = "pstnconnectivity-inbound" + PSTNCONNECTIVITY_OUTBOUND = "pstnconnectivity-outbound" + PV = "pv" + PV_BASIC_ROOMS = "pv-basic-rooms" + PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" + PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" + PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" + PV_COMPOSITION_MINUTES = "pv-composition-minutes" + PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" + PV_ROOM_PARTICIPANTS = "pv-room-participants" + PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" + PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" + PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" + PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" + PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" + PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" + PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" + PV_ROOMS = "pv-rooms" + PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" + RCS_MESSAGES = "rcs-messages" + REASSIGNED_NUMBER = "reassigned-number" + RECORDINGS = "recordings" + RECORDINGSTORAGE = "recordingstorage" + SHORTCODES = "shortcodes" + SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" + SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" + SHORTCODES_MPS = "shortcodes-mps" + SHORTCODES_RANDOM = "shortcodes-random" + SHORTCODES_SETUP_FEES = "shortcodes-setup-fees" + SHORTCODES_UK = "shortcodes-uk" + SHORTCODES_VANITY = "shortcodes-vanity" + SIM_SWAP_LOOKUPS = "sim-swap-lookups" + SIP_SECURE_MEDIA = "sip-secure-media" + SMALL_GROUP_ROOMS = "small-group-rooms" + SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" + SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" + SMS = "sms" + SMS_INBOUND = "sms-inbound" + SMS_INBOUND_LONGCODE = "sms-inbound-longcode" + SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" + SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" + SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) + SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" + SMS_OUTBOUND = "sms-outbound" + SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" + SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" + SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" + SPEECH_RECOGNITION = "speech-recognition" + STUDIO_ENGAGEMENTS = "studio-engagements" + SYNC = "sync" + SYNC_ACTIONS = "sync-actions" + SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" + SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" + TASKROUTER_TASKS = "taskrouter-tasks" + TOTALPRICE = "totalprice" + TRANSCRIPTIONS = "transcriptions" + TRUNKING_CPS = "trunking-cps" + TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" + TRUNKING_ORIGINATION = "trunking-origination" + TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" + TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" + TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" + TRUNKING_RECORDINGS = "trunking-recordings" + TRUNKING_SECURE = "trunking-secure" + TRUNKING_TERMINATION = "trunking-termination" + TTS_GOOGLE = "tts-google" + TURNMEGABYTES = "turnmegabytes" + TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" + TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" + TURNMEGABYTES_GERMANY = "turnmegabytes-germany" + TURNMEGABYTES_INDIA = "turnmegabytes-india" + TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" + TURNMEGABYTES_JAPAN = "turnmegabytes-japan" + TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" + TURNMEGABYTES_USEAST = "turnmegabytes-useast" + TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" + TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) + VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" + VOICE_INSIGHTS = "voice-insights" + VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-client-insights-on-demand-minute" + ) + VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-ptsn-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-interface-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-trunking-insights-on-demand-minute" + ) + VOICE_INTELLIGENCE = "voice-intelligence" + VOICE_INTELLIGENCE_EIP_OPERATORS = "voice-intelligence-eip-operators" + VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" + VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" + WDS = "wds" + WIRELESS = "wireless" + WIRELESS_DATA = "wireless-data" + WIRELESS_DATA_PAYG = "wireless-data-payg" + WIRELESS_DATA_PAYG_AFRICA = "wireless-data-payg-africa" + WIRELESS_DATA_PAYG_ASIA = "wireless-data-payg-asia" + WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA = ( + "wireless-data-payg-centralandsouthamerica" + ) + WIRELESS_DATA_PAYG_EUROPE = "wireless-data-payg-europe" + WIRELESS_DATA_PAYG_NORTHAMERICA = "wireless-data-payg-northamerica" + WIRELESS_DATA_PAYG_OCEANIA = "wireless-data-payg-oceania" + WIRELESS_DATA_QUOTA1 = "wireless-data-quota1" + WIRELESS_DATA_QUOTA1_AFRICA = "wireless-data-quota1-africa" + WIRELESS_DATA_QUOTA1_ASIA = "wireless-data-quota1-asia" + WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota1-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA1_EUROPE = "wireless-data-quota1-europe" + WIRELESS_DATA_QUOTA1_NORTHAMERICA = "wireless-data-quota1-northamerica" + WIRELESS_DATA_QUOTA1_OCEANIA = "wireless-data-quota1-oceania" + WIRELESS_DATA_QUOTA10 = "wireless-data-quota10" + WIRELESS_DATA_QUOTA10_AFRICA = "wireless-data-quota10-africa" + WIRELESS_DATA_QUOTA10_ASIA = "wireless-data-quota10-asia" + WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota10-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA10_EUROPE = "wireless-data-quota10-europe" + WIRELESS_DATA_QUOTA10_NORTHAMERICA = "wireless-data-quota10-northamerica" + WIRELESS_DATA_QUOTA10_OCEANIA = "wireless-data-quota10-oceania" + WIRELESS_DATA_QUOTA50 = "wireless-data-quota50" + WIRELESS_DATA_QUOTA50_AFRICA = "wireless-data-quota50-africa" + WIRELESS_DATA_QUOTA50_ASIA = "wireless-data-quota50-asia" + WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota50-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA50_EUROPE = "wireless-data-quota50-europe" + WIRELESS_DATA_QUOTA50_NORTHAMERICA = "wireless-data-quota50-northamerica" + WIRELESS_DATA_QUOTA50_OCEANIA = "wireless-data-quota50-oceania" + WIRELESS_DATA_QUOTACUSTOM = "wireless-data-quotacustom" + WIRELESS_DATA_QUOTACUSTOM_AFRICA = "wireless-data-quotacustom-africa" + WIRELESS_DATA_QUOTACUSTOM_ASIA = "wireless-data-quotacustom-asia" + WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quotacustom-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_EUROPE = "wireless-data-quotacustom-europe" + WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA = ( + "wireless-data-quotacustom-northamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_OCEANIA = "wireless-data-quotacustom-oceania" + WIRELESS_MRC_PAYG = "wireless-mrc-payg" + WIRELESS_MRC_QUOTA1 = "wireless-mrc-quota1" + WIRELESS_MRC_QUOTA10 = "wireless-mrc-quota10" + WIRELESS_MRC_QUOTA50 = "wireless-mrc-quota50" + WIRELESS_MRC_QUOTACUSTOM = "wireless-mrc-quotacustom" + WIRELESS_ORDERS = "wireless-orders" + WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" + WIRELESS_ORDERS_BULK = "wireless-orders-bulk" + WIRELESS_ORDERS_ESIM = "wireless-orders-esim" + WIRELESS_ORDERS_STARTER = "wireless-orders-starter" + WIRELESS_QUOTAS = "wireless-quotas" + WIRELESS_SMS_AFRICA = "wireless-sms-africa" + WIRELESS_SMS_ASIA = "wireless-sms-asia" + WIRELESS_SMS_CENTRALANDSOUTHAMERICA = "wireless-sms-centralandsouthamerica" + WIRELESS_SMS_EUROPE = "wireless-sms-europe" + WIRELESS_SMS_NORTHAMERICA = "wireless-sms-northamerica" + WIRELESS_SMS_OCEANIA = "wireless-sms-oceania" + WIRELESS_SUPER_SIM = "wireless-super-sim" + WIRELESS_SUPER_SIM_DATA = "wireless-super-sim-data" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA = ( + "wireless-super-sim-data-north-america-usa" + ) + WIRELESS_SUPER_SIM_DATA_PAYG = "wireless-super-sim-data-payg" + WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE = "wireless-super-sim-data-payg-europe" + WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA = ( + "wireless-super-sim-data-payg-north-america" + ) + WIRELESS_SUPER_SIM_HARDWARE = "wireless-super-sim-hardware" + WIRELESS_SUPER_SIM_HARDWARE_BULK = "wireless-super-sim-hardware-bulk" + WIRELESS_SUPER_SIM_SMSCOMMANDS = "wireless-super-sim-smscommands" + WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA = "wireless-super-sim-smscommands-africa" + WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA = "wireless-super-sim-smscommands-asia" + WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA = ( + "wireless-super-sim-smscommands-cent-and-south-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE = "wireless-super-sim-smscommands-europe" + WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA = ( + "wireless-super-sim-smscommands-north-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA = ( + "wireless-super-sim-smscommands-oceania" + ) + WIRELESS_SUPER_SIM_SUBSCRIPTION = "wireless-super-sim-subscription" + WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG = "wireless-super-sim-subscription-payg" + WIRELESS_USAGE = "wireless-usage" + WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" + WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" + WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" + WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-commands-centralandsouthamerica" + ) + WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" + WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" + WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" + WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" + WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" + WIRELESS_USAGE_DATA = "wireless-usage-data" + WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" + WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" + WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-data-centralandsouthamerica" + ) + WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( + "wireless-usage-data-custom-additionalmb" + ) + WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" + WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" + WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" + WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( + "wireless-usage-data-individual-additionalgb" + ) + WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( + "wireless-usage-data-individual-firstgb" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( + "wireless-usage-data-international-roaming-canada" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( + "wireless-usage-data-international-roaming-india" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( + "wireless-usage-data-international-roaming-mexico" + ) + WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" + WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" + WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" + WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" + WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" + WIRELESS_USAGE_MRC = "wireless-usage-mrc" + WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" + WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" + WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" + WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" + WIRELESS_USAGE_SMS = "wireless-usage-sms" + WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + :ivar api_version: The API version used to create the resource. + :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + :ivar category: + :ivar count: The number of usage events, such as the number of calls. + :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + :ivar description: A plain-language description of the usage category. + :ivar end_date: The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar price: The total price of the usage in the currency specified in `price_unit` and associated with the account. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + :ivar start_date: The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar subresource_uris: A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage: The amount used to bill usage and measured in units described in `usage_unit`. + :ivar usage_unit: The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.as_of: Optional[str] = payload.get("as_of") + self.category: Optional["ThisMonthInstance.Category"] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.ThisMonthInstance {}>".format(context) + + +class ThisMonthPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ThisMonthInstance: + """ + Build an instance of ThisMonthInstance + + :param payload: Payload response from the API + """ + return ThisMonthInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.ThisMonthPage>" + + +class ThisMonthList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the ThisMonthList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/ThisMonth.json".format( + **self._solution + ) + + def stream( + self, + category: Union["ThisMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ThisMonthInstance]: + """ + Streams ThisMonthInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "ThisMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + category: Union["ThisMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ThisMonthInstance]: + """ + Asynchronously streams ThisMonthInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "ThisMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["ThisMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ThisMonthInstance]: + """ + Lists ThisMonthInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "ThisMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + category: Union["ThisMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ThisMonthInstance]: + """ + Asynchronously lists ThisMonthInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "ThisMonthInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + category: Union["ThisMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ThisMonthPage: + """ + Retrieve a single page of ThisMonthInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ThisMonthInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ThisMonthPage(self._version, response, self._solution) + + async def page_async( + self, + category: Union["ThisMonthInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ThisMonthPage: + """ + Asynchronously retrieve a single page of ThisMonthInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ThisMonthInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ThisMonthPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ThisMonthPage: + """ + Retrieve a specific page of ThisMonthInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ThisMonthInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ThisMonthPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ThisMonthPage: + """ + Asynchronously retrieve a specific page of ThisMonthInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ThisMonthInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ThisMonthPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.ThisMonthList>" diff --git a/twilio/rest/api/v2010/account/usage/record/today.py b/twilio/rest/api/v2010/account/usage/record/today.py new file mode 100644 index 0000000000..393238e76f --- /dev/null +++ b/twilio/rest/api/v2010/account/usage/record/today.py @@ -0,0 +1,1211 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TodayInstance(InstanceResource): + + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" + AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" + ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" + AUTHY_AUTHENTICATIONS = "authy-authentications" + AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" + AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" + AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" + AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" + AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" + CALL_PROGESS_EVENTS = "call-progess-events" + CALLERIDLOOKUPS = "calleridlookups" + CALLS = "calls" + CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" + CALLS_GLOBALCONFERENCE = "calls-globalconference" + CALLS_INBOUND = "calls-inbound" + CALLS_INBOUND_LOCAL = "calls-inbound-local" + CALLS_INBOUND_MOBILE = "calls-inbound-mobile" + CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" + CALLS_OUTBOUND = "calls-outbound" + CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" + CALLS_RECORDINGS = "calls-recordings" + CALLS_SIP = "calls-sip" + CALLS_SIP_INBOUND = "calls-sip-inbound" + CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" + CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" + CONVERSATIONS = "conversations" + CONVERSATIONS_API_REQUESTS = "conversations-api-requests" + CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" + CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" + CONVERSATIONS_EVENTS = "conversations-events" + CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" + CONVERSATIONS_PARTICIPANTS = "conversations-participants" + CPS = "cps" + CREDIT_TRANSFER = "credit-transfer" + EMAIL = "email" + EMERGING_TECH = "emerging-tech" + ENGAGEMENT_SUITE_PACKAGED_PLANS = "engagement-suite-packaged-plans" + ENHANCED_LINE_TYPE_LOOKUPS = "enhanced-line-type-lookups" + ENTERPRISE = "enterprise" + EVENTS = "events" + EXPERIMENT_FRANCE_SMS = "experiment-france-sms" + EXPERIMENT_INDIA_SMS = "experiment-india-sms" + EXPERIMENT_UK_SMS = "experiment-uk-sms" + FAILED_MESSAGE_PROCESSING_FEE = "failed-message-processing-fee" + FLEX = "flex" + FLEX_ACTIVE_USER_HOURS = "flex-active-user-hours" + FLEX_CONCURRENT_USERS = "flex-concurrent-users" + FLEX_CONVERSATIONAL_INSIGHTS = "flex-conversational-insights" + FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES = "flex-conversational-insights-messages" + FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = ( + "flex-conversational-insights-voice-minutes" + ) + FLEX_EMAIL_USAGE = "flex-email-usage" + FLEX_MESSAGING_USAGE = "flex-messaging-usage" + FLEX_PARTNER_SPINSCI = "flex-partner-spinsci" + FLEX_PARTNER_XCELERATE = "flex-partner-xcelerate" + FLEX_RESELLER_ECOSYSTEM = "flex-reseller-ecosystem" + FLEX_UNIQUE_USER = "flex-unique-user" + FLEX_USAGE = "flex-usage" + FLEX_USERS = "flex-users" + FLEX_VOICE_MINUTE = "flex-voice-minute" + FLEX_YTICA = "flex-ytica" + FRAUD_LOOKUPS = "fraud-lookups" + FRONTLINE = "frontline" + FRONTLINE_USERS = "frontline-users" + FUNCTIONS = "functions" + GENERIC_PAY_TRANSACTIONS = "generic-pay-transactions" + GROUP_ROOMS = "group-rooms" + GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" + GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" + GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" + GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" + GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" + GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" + GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" + GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" + IP_MESSAGING = "ip-messaging" + IP_MESSAGING_COMMANDS = "ip-messaging-commands" + IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" + IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" + IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" + IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" + IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" + LINE_STATUS_LOOKUPS = "line-status-lookups" + LIVE_ACTIVITY_LOOKUPS = "live-activity-lookups" + LOOKUP_BUCKET_ADJUSTMENT = "lookup-bucket-adjustment" + LOOKUP_IDENTITY_MATCH = "lookup-identity-match" + LOOKUPS = "lookups" + MARKETPLACE = "marketplace" + MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) + MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" + MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" + MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" + MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" + MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION = "marketplace-deepgram-transcription" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE = ( + "marketplace-deepgram-transcription-base" + ) + MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED = ( + "marketplace-deepgram-transscription-enhanced" + ) + MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( + "marketplace-digital-segment-business-info" + ) + MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( + "marketplace-facebook-offline-conversions" + ) + MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" + MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( + "marketplace-ibm-watson-message-insights" + ) + MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( + "marketplace-ibm-watson-message-sentiment" + ) + MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( + "marketplace-ibm-watson-recording-analysis" + ) + MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" + MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" + MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( + "marketplace-infogroup-dataaxle-bizinfo" + ) + MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( + "marketplace-keen-io-contact-center-analytics" + ) + MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" + MARKETPLACE_MARCHEX_RECORDING_ANALYSIS = ( + "marketplace-marchex-recording-analysis" + ) + MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( + "marketplace-marchex-sentiment-analysis-for-sms" + ) + MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( + "marketplace-marketplace-nextcaller-social-id" + ) + MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( + "marketplace-mobile-commons-opt-out-classifier" + ) + MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( + "marketplace-nexiwave-voicemail-to-text" + ) + MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( + "marketplace-nextcaller-advanced-caller-identification" + ) + MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" + MARKETPLACE_PAY_ADDONS = "marketplace-pay-addons" + MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR = ( + "marketplace-pay-addons-basecommerce-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR = ( + "marketplace-pay-addons-braintree-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR = ( + "marketplace-pay-addons-cardconnect-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR = ( + "marketplace-pay-addons-chase-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplace-pay-addons-shuttle-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplace-pay-addons-stripe-pay-connector" + ) + MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" + MARKETPLACE_POLY_AI_CONNECTOR = "marketplace-poly-ai-connector" + MARKETPLACE_REALPHONEVALIDATION = "marketplace-realphonevalidation" + MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( + "marketplace-remeeting-automatic-speech-recognition" + ) + MARKETPLACE_SPOKE_PHONE_LICENSE_PRO = "marketplace-spoke-phone-license-pro" + MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD = ( + "marketplace-spoke-phone-license-standard" + ) + MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( + "marketplace-tcpa-defense-solutions-blacklist-feed" + ) + MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" + MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION = ( + "marketplace-trestle-solutions-caller-identification" + ) + MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" + MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( + "marketplace-twilio-caller-name-lookup-us" + ) + MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( + "marketplace-twilio-carrier-information-lookup" + ) + MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" + MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" + MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) + MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" + MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( + "marketplace-ytica-contact-center-reporting-analytics" + ) + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplay-pay-addons-shuttle-pay-connector" + ) + MEDIA_COMPOSER_MINUTES = "media-composer-minutes" + MEDIASTORAGE = "mediastorage" + MIN_SPEND_ADJUSTMENTS = "min-spend-adjustments" + MMS = "mms" + MMS_INBOUND = "mms-inbound" + MMS_INBOUND_LONGCODE = "mms-inbound-longcode" + MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" + MMS_INBOUND_TOLL_FREE = "mms-inbound-toll-free" + MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" + MMS_OUTBOUND = "mms-outbound" + MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" + MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" + MMS_OUTBOUND_TOLLFREE = "mms-outbound-tollfree" + MONITOR = "monitor" + MONITOR_READS = "monitor-reads" + MONITOR_STORAGE = "monitor-storage" + MONITOR_WRITES = "monitor-writes" + NOTIFY = "notify" + NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" + NOTIFY_CHANNELS = "notify-channels" + NUMBER_FORMAT_LOOKUPS = "number-format-lookups" + PCHAT = "pchat" + PCHAT_ACTIONS = "pchat-actions" + PCHAT_APS = "pchat-aps" + PCHAT_CONV_MED_STORAGE = "pchat-conv-med-storage" + PCHAT_MESSAGES = "pchat-messages" + PCHAT_NOTIFICATIONS = "pchat-notifications" + PCHAT_READS = "pchat-reads" + PCHAT_USERS = "pchat-users" + PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "peer-to-peer-rooms-participant-minutes" + ) + PFAX = "pfax" + PFAX_MINUTES = "pfax-minutes" + PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" + PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" + PFAX_PAGES = "pfax-pages" + PHONE_QUALITY_SCORE_LOOKUPS = "phone-quality-score-lookups" + PHONENUMBERS = "phonenumbers" + PHONENUMBERS_CPS = "phonenumbers-cps" + PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" + PHONENUMBERS_LOCAL = "phonenumbers-local" + PHONENUMBERS_MOBILE = "phonenumbers-mobile" + PHONENUMBERS_PORTING = "phonenumbers-porting" + PHONENUMBERS_SETUPS = "phonenumbers-setups" + PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" + PREMIUMSUPPORT = "premiumsupport" + PREMIUMSUPPORT_PERCENTAGE_SPEND = "premiumsupport-percentage-spend" + PROGRAMMABLEVOICE_PLATFORM = "programmablevoice-platform" + PROGRAMMABLEVOICECONN_CLIENTSDK = "programmablevoiceconn-clientsdk" + PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND = ( + "programmablevoiceconn-clientsdk-inbound" + ) + PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND = ( + "programmablevoiceconn-clientsdk-outbound" + ) + PROGRAMMABLEVOICECONN_ONNET = "programmablevoiceconn-onnet" + PROGRAMMABLEVOICECONN_ONNET_INBOUND = "programmablevoiceconn-onnet-inbound" + PROGRAMMABLEVOICECONN_ONNET_OUTBOUND = "programmablevoiceconn-onnet-outbound" + PROGRAMMABLEVOICECONN_SIP = "programmablevoiceconn-sip" + PROGRAMMABLEVOICECONN_SIP_INBOUND = "programmablevoiceconn-sip-inbound" + PROGRAMMABLEVOICECONN_SIP_OUTBOUND = "programmablevoiceconn-sip-outbound" + PROGRAMMABLEVOICECONNECTIVITY = "programmablevoiceconnectivity" + PROXY = "proxy" + PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" + PROXY_BUCKET_ADJUSTMENT = "proxy-bucket-adjustment" + PROXY_LICENSES = "proxy-licenses" + PSTNCONNECTIVITY = "pstnconnectivity" + PSTNCONNECTIVITY_INBOUND = "pstnconnectivity-inbound" + PSTNCONNECTIVITY_OUTBOUND = "pstnconnectivity-outbound" + PV = "pv" + PV_BASIC_ROOMS = "pv-basic-rooms" + PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" + PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" + PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" + PV_COMPOSITION_MINUTES = "pv-composition-minutes" + PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" + PV_ROOM_PARTICIPANTS = "pv-room-participants" + PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" + PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" + PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" + PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" + PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" + PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" + PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" + PV_ROOMS = "pv-rooms" + PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" + RCS_MESSAGES = "rcs-messages" + REASSIGNED_NUMBER = "reassigned-number" + RECORDINGS = "recordings" + RECORDINGSTORAGE = "recordingstorage" + SHORTCODES = "shortcodes" + SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" + SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" + SHORTCODES_MPS = "shortcodes-mps" + SHORTCODES_RANDOM = "shortcodes-random" + SHORTCODES_SETUP_FEES = "shortcodes-setup-fees" + SHORTCODES_UK = "shortcodes-uk" + SHORTCODES_VANITY = "shortcodes-vanity" + SIM_SWAP_LOOKUPS = "sim-swap-lookups" + SIP_SECURE_MEDIA = "sip-secure-media" + SMALL_GROUP_ROOMS = "small-group-rooms" + SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" + SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" + SMS = "sms" + SMS_INBOUND = "sms-inbound" + SMS_INBOUND_LONGCODE = "sms-inbound-longcode" + SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" + SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" + SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) + SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" + SMS_OUTBOUND = "sms-outbound" + SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" + SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" + SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" + SPEECH_RECOGNITION = "speech-recognition" + STUDIO_ENGAGEMENTS = "studio-engagements" + SYNC = "sync" + SYNC_ACTIONS = "sync-actions" + SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" + SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" + TASKROUTER_TASKS = "taskrouter-tasks" + TOTALPRICE = "totalprice" + TRANSCRIPTIONS = "transcriptions" + TRUNKING_CPS = "trunking-cps" + TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" + TRUNKING_ORIGINATION = "trunking-origination" + TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" + TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" + TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" + TRUNKING_RECORDINGS = "trunking-recordings" + TRUNKING_SECURE = "trunking-secure" + TRUNKING_TERMINATION = "trunking-termination" + TTS_GOOGLE = "tts-google" + TURNMEGABYTES = "turnmegabytes" + TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" + TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" + TURNMEGABYTES_GERMANY = "turnmegabytes-germany" + TURNMEGABYTES_INDIA = "turnmegabytes-india" + TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" + TURNMEGABYTES_JAPAN = "turnmegabytes-japan" + TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" + TURNMEGABYTES_USEAST = "turnmegabytes-useast" + TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" + TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) + VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" + VOICE_INSIGHTS = "voice-insights" + VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-client-insights-on-demand-minute" + ) + VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-ptsn-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-interface-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-trunking-insights-on-demand-minute" + ) + VOICE_INTELLIGENCE = "voice-intelligence" + VOICE_INTELLIGENCE_EIP_OPERATORS = "voice-intelligence-eip-operators" + VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" + VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" + WDS = "wds" + WIRELESS = "wireless" + WIRELESS_DATA = "wireless-data" + WIRELESS_DATA_PAYG = "wireless-data-payg" + WIRELESS_DATA_PAYG_AFRICA = "wireless-data-payg-africa" + WIRELESS_DATA_PAYG_ASIA = "wireless-data-payg-asia" + WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA = ( + "wireless-data-payg-centralandsouthamerica" + ) + WIRELESS_DATA_PAYG_EUROPE = "wireless-data-payg-europe" + WIRELESS_DATA_PAYG_NORTHAMERICA = "wireless-data-payg-northamerica" + WIRELESS_DATA_PAYG_OCEANIA = "wireless-data-payg-oceania" + WIRELESS_DATA_QUOTA1 = "wireless-data-quota1" + WIRELESS_DATA_QUOTA1_AFRICA = "wireless-data-quota1-africa" + WIRELESS_DATA_QUOTA1_ASIA = "wireless-data-quota1-asia" + WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota1-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA1_EUROPE = "wireless-data-quota1-europe" + WIRELESS_DATA_QUOTA1_NORTHAMERICA = "wireless-data-quota1-northamerica" + WIRELESS_DATA_QUOTA1_OCEANIA = "wireless-data-quota1-oceania" + WIRELESS_DATA_QUOTA10 = "wireless-data-quota10" + WIRELESS_DATA_QUOTA10_AFRICA = "wireless-data-quota10-africa" + WIRELESS_DATA_QUOTA10_ASIA = "wireless-data-quota10-asia" + WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota10-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA10_EUROPE = "wireless-data-quota10-europe" + WIRELESS_DATA_QUOTA10_NORTHAMERICA = "wireless-data-quota10-northamerica" + WIRELESS_DATA_QUOTA10_OCEANIA = "wireless-data-quota10-oceania" + WIRELESS_DATA_QUOTA50 = "wireless-data-quota50" + WIRELESS_DATA_QUOTA50_AFRICA = "wireless-data-quota50-africa" + WIRELESS_DATA_QUOTA50_ASIA = "wireless-data-quota50-asia" + WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota50-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA50_EUROPE = "wireless-data-quota50-europe" + WIRELESS_DATA_QUOTA50_NORTHAMERICA = "wireless-data-quota50-northamerica" + WIRELESS_DATA_QUOTA50_OCEANIA = "wireless-data-quota50-oceania" + WIRELESS_DATA_QUOTACUSTOM = "wireless-data-quotacustom" + WIRELESS_DATA_QUOTACUSTOM_AFRICA = "wireless-data-quotacustom-africa" + WIRELESS_DATA_QUOTACUSTOM_ASIA = "wireless-data-quotacustom-asia" + WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quotacustom-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_EUROPE = "wireless-data-quotacustom-europe" + WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA = ( + "wireless-data-quotacustom-northamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_OCEANIA = "wireless-data-quotacustom-oceania" + WIRELESS_MRC_PAYG = "wireless-mrc-payg" + WIRELESS_MRC_QUOTA1 = "wireless-mrc-quota1" + WIRELESS_MRC_QUOTA10 = "wireless-mrc-quota10" + WIRELESS_MRC_QUOTA50 = "wireless-mrc-quota50" + WIRELESS_MRC_QUOTACUSTOM = "wireless-mrc-quotacustom" + WIRELESS_ORDERS = "wireless-orders" + WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" + WIRELESS_ORDERS_BULK = "wireless-orders-bulk" + WIRELESS_ORDERS_ESIM = "wireless-orders-esim" + WIRELESS_ORDERS_STARTER = "wireless-orders-starter" + WIRELESS_QUOTAS = "wireless-quotas" + WIRELESS_SMS_AFRICA = "wireless-sms-africa" + WIRELESS_SMS_ASIA = "wireless-sms-asia" + WIRELESS_SMS_CENTRALANDSOUTHAMERICA = "wireless-sms-centralandsouthamerica" + WIRELESS_SMS_EUROPE = "wireless-sms-europe" + WIRELESS_SMS_NORTHAMERICA = "wireless-sms-northamerica" + WIRELESS_SMS_OCEANIA = "wireless-sms-oceania" + WIRELESS_SUPER_SIM = "wireless-super-sim" + WIRELESS_SUPER_SIM_DATA = "wireless-super-sim-data" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA = ( + "wireless-super-sim-data-north-america-usa" + ) + WIRELESS_SUPER_SIM_DATA_PAYG = "wireless-super-sim-data-payg" + WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE = "wireless-super-sim-data-payg-europe" + WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA = ( + "wireless-super-sim-data-payg-north-america" + ) + WIRELESS_SUPER_SIM_HARDWARE = "wireless-super-sim-hardware" + WIRELESS_SUPER_SIM_HARDWARE_BULK = "wireless-super-sim-hardware-bulk" + WIRELESS_SUPER_SIM_SMSCOMMANDS = "wireless-super-sim-smscommands" + WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA = "wireless-super-sim-smscommands-africa" + WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA = "wireless-super-sim-smscommands-asia" + WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA = ( + "wireless-super-sim-smscommands-cent-and-south-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE = "wireless-super-sim-smscommands-europe" + WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA = ( + "wireless-super-sim-smscommands-north-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA = ( + "wireless-super-sim-smscommands-oceania" + ) + WIRELESS_SUPER_SIM_SUBSCRIPTION = "wireless-super-sim-subscription" + WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG = "wireless-super-sim-subscription-payg" + WIRELESS_USAGE = "wireless-usage" + WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" + WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" + WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" + WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-commands-centralandsouthamerica" + ) + WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" + WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" + WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" + WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" + WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" + WIRELESS_USAGE_DATA = "wireless-usage-data" + WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" + WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" + WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-data-centralandsouthamerica" + ) + WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( + "wireless-usage-data-custom-additionalmb" + ) + WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" + WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" + WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" + WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( + "wireless-usage-data-individual-additionalgb" + ) + WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( + "wireless-usage-data-individual-firstgb" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( + "wireless-usage-data-international-roaming-canada" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( + "wireless-usage-data-international-roaming-india" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( + "wireless-usage-data-international-roaming-mexico" + ) + WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" + WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" + WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" + WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" + WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" + WIRELESS_USAGE_MRC = "wireless-usage-mrc" + WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" + WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" + WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" + WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" + WIRELESS_USAGE_SMS = "wireless-usage-sms" + WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + :ivar api_version: The API version used to create the resource. + :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + :ivar category: + :ivar count: The number of usage events, such as the number of calls. + :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + :ivar description: A plain-language description of the usage category. + :ivar end_date: The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar price: The total price of the usage in the currency specified in `price_unit` and associated with the account. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + :ivar start_date: The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar subresource_uris: A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage: The amount used to bill usage and measured in units described in `usage_unit`. + :ivar usage_unit: The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.as_of: Optional[str] = payload.get("as_of") + self.category: Optional["TodayInstance.Category"] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.TodayInstance {}>".format(context) + + +class TodayPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TodayInstance: + """ + Build an instance of TodayInstance + + :param payload: Payload response from the API + """ + return TodayInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.TodayPage>" + + +class TodayList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the TodayList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/Today.json".format( + **self._solution + ) + + def stream( + self, + category: Union["TodayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TodayInstance]: + """ + Streams TodayInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "TodayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + category: Union["TodayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TodayInstance]: + """ + Asynchronously streams TodayInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "TodayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["TodayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TodayInstance]: + """ + Lists TodayInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "TodayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + category: Union["TodayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TodayInstance]: + """ + Asynchronously lists TodayInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "TodayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + category: Union["TodayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TodayPage: + """ + Retrieve a single page of TodayInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TodayInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TodayPage(self._version, response, self._solution) + + async def page_async( + self, + category: Union["TodayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TodayPage: + """ + Asynchronously retrieve a single page of TodayInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TodayInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TodayPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TodayPage: + """ + Retrieve a specific page of TodayInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TodayInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TodayPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TodayPage: + """ + Asynchronously retrieve a specific page of TodayInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TodayInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TodayPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.TodayList>" diff --git a/twilio/rest/api/v2010/account/usage/record/yearly.py b/twilio/rest/api/v2010/account/usage/record/yearly.py new file mode 100644 index 0000000000..ad9e5a36d8 --- /dev/null +++ b/twilio/rest/api/v2010/account/usage/record/yearly.py @@ -0,0 +1,1211 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class YearlyInstance(InstanceResource): + + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" + AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" + ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" + AUTHY_AUTHENTICATIONS = "authy-authentications" + AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" + AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" + AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" + AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" + AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" + CALL_PROGESS_EVENTS = "call-progess-events" + CALLERIDLOOKUPS = "calleridlookups" + CALLS = "calls" + CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" + CALLS_GLOBALCONFERENCE = "calls-globalconference" + CALLS_INBOUND = "calls-inbound" + CALLS_INBOUND_LOCAL = "calls-inbound-local" + CALLS_INBOUND_MOBILE = "calls-inbound-mobile" + CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" + CALLS_OUTBOUND = "calls-outbound" + CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" + CALLS_RECORDINGS = "calls-recordings" + CALLS_SIP = "calls-sip" + CALLS_SIP_INBOUND = "calls-sip-inbound" + CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" + CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" + CONVERSATIONS = "conversations" + CONVERSATIONS_API_REQUESTS = "conversations-api-requests" + CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" + CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" + CONVERSATIONS_EVENTS = "conversations-events" + CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" + CONVERSATIONS_PARTICIPANTS = "conversations-participants" + CPS = "cps" + CREDIT_TRANSFER = "credit-transfer" + EMAIL = "email" + EMERGING_TECH = "emerging-tech" + ENGAGEMENT_SUITE_PACKAGED_PLANS = "engagement-suite-packaged-plans" + ENHANCED_LINE_TYPE_LOOKUPS = "enhanced-line-type-lookups" + ENTERPRISE = "enterprise" + EVENTS = "events" + EXPERIMENT_FRANCE_SMS = "experiment-france-sms" + EXPERIMENT_INDIA_SMS = "experiment-india-sms" + EXPERIMENT_UK_SMS = "experiment-uk-sms" + FAILED_MESSAGE_PROCESSING_FEE = "failed-message-processing-fee" + FLEX = "flex" + FLEX_ACTIVE_USER_HOURS = "flex-active-user-hours" + FLEX_CONCURRENT_USERS = "flex-concurrent-users" + FLEX_CONVERSATIONAL_INSIGHTS = "flex-conversational-insights" + FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES = "flex-conversational-insights-messages" + FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = ( + "flex-conversational-insights-voice-minutes" + ) + FLEX_EMAIL_USAGE = "flex-email-usage" + FLEX_MESSAGING_USAGE = "flex-messaging-usage" + FLEX_PARTNER_SPINSCI = "flex-partner-spinsci" + FLEX_PARTNER_XCELERATE = "flex-partner-xcelerate" + FLEX_RESELLER_ECOSYSTEM = "flex-reseller-ecosystem" + FLEX_UNIQUE_USER = "flex-unique-user" + FLEX_USAGE = "flex-usage" + FLEX_USERS = "flex-users" + FLEX_VOICE_MINUTE = "flex-voice-minute" + FLEX_YTICA = "flex-ytica" + FRAUD_LOOKUPS = "fraud-lookups" + FRONTLINE = "frontline" + FRONTLINE_USERS = "frontline-users" + FUNCTIONS = "functions" + GENERIC_PAY_TRANSACTIONS = "generic-pay-transactions" + GROUP_ROOMS = "group-rooms" + GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" + GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" + GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" + GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" + GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" + GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" + GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" + GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" + IP_MESSAGING = "ip-messaging" + IP_MESSAGING_COMMANDS = "ip-messaging-commands" + IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" + IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" + IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" + IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" + IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" + LINE_STATUS_LOOKUPS = "line-status-lookups" + LIVE_ACTIVITY_LOOKUPS = "live-activity-lookups" + LOOKUP_BUCKET_ADJUSTMENT = "lookup-bucket-adjustment" + LOOKUP_IDENTITY_MATCH = "lookup-identity-match" + LOOKUPS = "lookups" + MARKETPLACE = "marketplace" + MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) + MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" + MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" + MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" + MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" + MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION = "marketplace-deepgram-transcription" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE = ( + "marketplace-deepgram-transcription-base" + ) + MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED = ( + "marketplace-deepgram-transscription-enhanced" + ) + MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( + "marketplace-digital-segment-business-info" + ) + MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( + "marketplace-facebook-offline-conversions" + ) + MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" + MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( + "marketplace-ibm-watson-message-insights" + ) + MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( + "marketplace-ibm-watson-message-sentiment" + ) + MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( + "marketplace-ibm-watson-recording-analysis" + ) + MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" + MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" + MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( + "marketplace-infogroup-dataaxle-bizinfo" + ) + MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( + "marketplace-keen-io-contact-center-analytics" + ) + MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" + MARKETPLACE_MARCHEX_RECORDING_ANALYSIS = ( + "marketplace-marchex-recording-analysis" + ) + MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( + "marketplace-marchex-sentiment-analysis-for-sms" + ) + MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( + "marketplace-marketplace-nextcaller-social-id" + ) + MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( + "marketplace-mobile-commons-opt-out-classifier" + ) + MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( + "marketplace-nexiwave-voicemail-to-text" + ) + MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( + "marketplace-nextcaller-advanced-caller-identification" + ) + MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" + MARKETPLACE_PAY_ADDONS = "marketplace-pay-addons" + MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR = ( + "marketplace-pay-addons-basecommerce-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR = ( + "marketplace-pay-addons-braintree-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR = ( + "marketplace-pay-addons-cardconnect-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR = ( + "marketplace-pay-addons-chase-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplace-pay-addons-shuttle-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplace-pay-addons-stripe-pay-connector" + ) + MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" + MARKETPLACE_POLY_AI_CONNECTOR = "marketplace-poly-ai-connector" + MARKETPLACE_REALPHONEVALIDATION = "marketplace-realphonevalidation" + MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( + "marketplace-remeeting-automatic-speech-recognition" + ) + MARKETPLACE_SPOKE_PHONE_LICENSE_PRO = "marketplace-spoke-phone-license-pro" + MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD = ( + "marketplace-spoke-phone-license-standard" + ) + MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( + "marketplace-tcpa-defense-solutions-blacklist-feed" + ) + MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" + MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION = ( + "marketplace-trestle-solutions-caller-identification" + ) + MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" + MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( + "marketplace-twilio-caller-name-lookup-us" + ) + MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( + "marketplace-twilio-carrier-information-lookup" + ) + MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" + MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" + MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) + MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" + MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( + "marketplace-ytica-contact-center-reporting-analytics" + ) + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplay-pay-addons-shuttle-pay-connector" + ) + MEDIA_COMPOSER_MINUTES = "media-composer-minutes" + MEDIASTORAGE = "mediastorage" + MIN_SPEND_ADJUSTMENTS = "min-spend-adjustments" + MMS = "mms" + MMS_INBOUND = "mms-inbound" + MMS_INBOUND_LONGCODE = "mms-inbound-longcode" + MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" + MMS_INBOUND_TOLL_FREE = "mms-inbound-toll-free" + MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" + MMS_OUTBOUND = "mms-outbound" + MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" + MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" + MMS_OUTBOUND_TOLLFREE = "mms-outbound-tollfree" + MONITOR = "monitor" + MONITOR_READS = "monitor-reads" + MONITOR_STORAGE = "monitor-storage" + MONITOR_WRITES = "monitor-writes" + NOTIFY = "notify" + NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" + NOTIFY_CHANNELS = "notify-channels" + NUMBER_FORMAT_LOOKUPS = "number-format-lookups" + PCHAT = "pchat" + PCHAT_ACTIONS = "pchat-actions" + PCHAT_APS = "pchat-aps" + PCHAT_CONV_MED_STORAGE = "pchat-conv-med-storage" + PCHAT_MESSAGES = "pchat-messages" + PCHAT_NOTIFICATIONS = "pchat-notifications" + PCHAT_READS = "pchat-reads" + PCHAT_USERS = "pchat-users" + PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "peer-to-peer-rooms-participant-minutes" + ) + PFAX = "pfax" + PFAX_MINUTES = "pfax-minutes" + PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" + PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" + PFAX_PAGES = "pfax-pages" + PHONE_QUALITY_SCORE_LOOKUPS = "phone-quality-score-lookups" + PHONENUMBERS = "phonenumbers" + PHONENUMBERS_CPS = "phonenumbers-cps" + PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" + PHONENUMBERS_LOCAL = "phonenumbers-local" + PHONENUMBERS_MOBILE = "phonenumbers-mobile" + PHONENUMBERS_PORTING = "phonenumbers-porting" + PHONENUMBERS_SETUPS = "phonenumbers-setups" + PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" + PREMIUMSUPPORT = "premiumsupport" + PREMIUMSUPPORT_PERCENTAGE_SPEND = "premiumsupport-percentage-spend" + PROGRAMMABLEVOICE_PLATFORM = "programmablevoice-platform" + PROGRAMMABLEVOICECONN_CLIENTSDK = "programmablevoiceconn-clientsdk" + PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND = ( + "programmablevoiceconn-clientsdk-inbound" + ) + PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND = ( + "programmablevoiceconn-clientsdk-outbound" + ) + PROGRAMMABLEVOICECONN_ONNET = "programmablevoiceconn-onnet" + PROGRAMMABLEVOICECONN_ONNET_INBOUND = "programmablevoiceconn-onnet-inbound" + PROGRAMMABLEVOICECONN_ONNET_OUTBOUND = "programmablevoiceconn-onnet-outbound" + PROGRAMMABLEVOICECONN_SIP = "programmablevoiceconn-sip" + PROGRAMMABLEVOICECONN_SIP_INBOUND = "programmablevoiceconn-sip-inbound" + PROGRAMMABLEVOICECONN_SIP_OUTBOUND = "programmablevoiceconn-sip-outbound" + PROGRAMMABLEVOICECONNECTIVITY = "programmablevoiceconnectivity" + PROXY = "proxy" + PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" + PROXY_BUCKET_ADJUSTMENT = "proxy-bucket-adjustment" + PROXY_LICENSES = "proxy-licenses" + PSTNCONNECTIVITY = "pstnconnectivity" + PSTNCONNECTIVITY_INBOUND = "pstnconnectivity-inbound" + PSTNCONNECTIVITY_OUTBOUND = "pstnconnectivity-outbound" + PV = "pv" + PV_BASIC_ROOMS = "pv-basic-rooms" + PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" + PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" + PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" + PV_COMPOSITION_MINUTES = "pv-composition-minutes" + PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" + PV_ROOM_PARTICIPANTS = "pv-room-participants" + PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" + PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" + PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" + PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" + PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" + PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" + PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" + PV_ROOMS = "pv-rooms" + PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" + RCS_MESSAGES = "rcs-messages" + REASSIGNED_NUMBER = "reassigned-number" + RECORDINGS = "recordings" + RECORDINGSTORAGE = "recordingstorage" + SHORTCODES = "shortcodes" + SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" + SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" + SHORTCODES_MPS = "shortcodes-mps" + SHORTCODES_RANDOM = "shortcodes-random" + SHORTCODES_SETUP_FEES = "shortcodes-setup-fees" + SHORTCODES_UK = "shortcodes-uk" + SHORTCODES_VANITY = "shortcodes-vanity" + SIM_SWAP_LOOKUPS = "sim-swap-lookups" + SIP_SECURE_MEDIA = "sip-secure-media" + SMALL_GROUP_ROOMS = "small-group-rooms" + SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" + SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" + SMS = "sms" + SMS_INBOUND = "sms-inbound" + SMS_INBOUND_LONGCODE = "sms-inbound-longcode" + SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" + SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" + SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) + SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" + SMS_OUTBOUND = "sms-outbound" + SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" + SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" + SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" + SPEECH_RECOGNITION = "speech-recognition" + STUDIO_ENGAGEMENTS = "studio-engagements" + SYNC = "sync" + SYNC_ACTIONS = "sync-actions" + SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" + SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" + TASKROUTER_TASKS = "taskrouter-tasks" + TOTALPRICE = "totalprice" + TRANSCRIPTIONS = "transcriptions" + TRUNKING_CPS = "trunking-cps" + TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" + TRUNKING_ORIGINATION = "trunking-origination" + TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" + TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" + TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" + TRUNKING_RECORDINGS = "trunking-recordings" + TRUNKING_SECURE = "trunking-secure" + TRUNKING_TERMINATION = "trunking-termination" + TTS_GOOGLE = "tts-google" + TURNMEGABYTES = "turnmegabytes" + TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" + TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" + TURNMEGABYTES_GERMANY = "turnmegabytes-germany" + TURNMEGABYTES_INDIA = "turnmegabytes-india" + TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" + TURNMEGABYTES_JAPAN = "turnmegabytes-japan" + TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" + TURNMEGABYTES_USEAST = "turnmegabytes-useast" + TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" + TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) + VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" + VOICE_INSIGHTS = "voice-insights" + VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-client-insights-on-demand-minute" + ) + VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-ptsn-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-interface-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-trunking-insights-on-demand-minute" + ) + VOICE_INTELLIGENCE = "voice-intelligence" + VOICE_INTELLIGENCE_EIP_OPERATORS = "voice-intelligence-eip-operators" + VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" + VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" + WDS = "wds" + WIRELESS = "wireless" + WIRELESS_DATA = "wireless-data" + WIRELESS_DATA_PAYG = "wireless-data-payg" + WIRELESS_DATA_PAYG_AFRICA = "wireless-data-payg-africa" + WIRELESS_DATA_PAYG_ASIA = "wireless-data-payg-asia" + WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA = ( + "wireless-data-payg-centralandsouthamerica" + ) + WIRELESS_DATA_PAYG_EUROPE = "wireless-data-payg-europe" + WIRELESS_DATA_PAYG_NORTHAMERICA = "wireless-data-payg-northamerica" + WIRELESS_DATA_PAYG_OCEANIA = "wireless-data-payg-oceania" + WIRELESS_DATA_QUOTA1 = "wireless-data-quota1" + WIRELESS_DATA_QUOTA1_AFRICA = "wireless-data-quota1-africa" + WIRELESS_DATA_QUOTA1_ASIA = "wireless-data-quota1-asia" + WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota1-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA1_EUROPE = "wireless-data-quota1-europe" + WIRELESS_DATA_QUOTA1_NORTHAMERICA = "wireless-data-quota1-northamerica" + WIRELESS_DATA_QUOTA1_OCEANIA = "wireless-data-quota1-oceania" + WIRELESS_DATA_QUOTA10 = "wireless-data-quota10" + WIRELESS_DATA_QUOTA10_AFRICA = "wireless-data-quota10-africa" + WIRELESS_DATA_QUOTA10_ASIA = "wireless-data-quota10-asia" + WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota10-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA10_EUROPE = "wireless-data-quota10-europe" + WIRELESS_DATA_QUOTA10_NORTHAMERICA = "wireless-data-quota10-northamerica" + WIRELESS_DATA_QUOTA10_OCEANIA = "wireless-data-quota10-oceania" + WIRELESS_DATA_QUOTA50 = "wireless-data-quota50" + WIRELESS_DATA_QUOTA50_AFRICA = "wireless-data-quota50-africa" + WIRELESS_DATA_QUOTA50_ASIA = "wireless-data-quota50-asia" + WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota50-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA50_EUROPE = "wireless-data-quota50-europe" + WIRELESS_DATA_QUOTA50_NORTHAMERICA = "wireless-data-quota50-northamerica" + WIRELESS_DATA_QUOTA50_OCEANIA = "wireless-data-quota50-oceania" + WIRELESS_DATA_QUOTACUSTOM = "wireless-data-quotacustom" + WIRELESS_DATA_QUOTACUSTOM_AFRICA = "wireless-data-quotacustom-africa" + WIRELESS_DATA_QUOTACUSTOM_ASIA = "wireless-data-quotacustom-asia" + WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quotacustom-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_EUROPE = "wireless-data-quotacustom-europe" + WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA = ( + "wireless-data-quotacustom-northamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_OCEANIA = "wireless-data-quotacustom-oceania" + WIRELESS_MRC_PAYG = "wireless-mrc-payg" + WIRELESS_MRC_QUOTA1 = "wireless-mrc-quota1" + WIRELESS_MRC_QUOTA10 = "wireless-mrc-quota10" + WIRELESS_MRC_QUOTA50 = "wireless-mrc-quota50" + WIRELESS_MRC_QUOTACUSTOM = "wireless-mrc-quotacustom" + WIRELESS_ORDERS = "wireless-orders" + WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" + WIRELESS_ORDERS_BULK = "wireless-orders-bulk" + WIRELESS_ORDERS_ESIM = "wireless-orders-esim" + WIRELESS_ORDERS_STARTER = "wireless-orders-starter" + WIRELESS_QUOTAS = "wireless-quotas" + WIRELESS_SMS_AFRICA = "wireless-sms-africa" + WIRELESS_SMS_ASIA = "wireless-sms-asia" + WIRELESS_SMS_CENTRALANDSOUTHAMERICA = "wireless-sms-centralandsouthamerica" + WIRELESS_SMS_EUROPE = "wireless-sms-europe" + WIRELESS_SMS_NORTHAMERICA = "wireless-sms-northamerica" + WIRELESS_SMS_OCEANIA = "wireless-sms-oceania" + WIRELESS_SUPER_SIM = "wireless-super-sim" + WIRELESS_SUPER_SIM_DATA = "wireless-super-sim-data" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA = ( + "wireless-super-sim-data-north-america-usa" + ) + WIRELESS_SUPER_SIM_DATA_PAYG = "wireless-super-sim-data-payg" + WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE = "wireless-super-sim-data-payg-europe" + WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA = ( + "wireless-super-sim-data-payg-north-america" + ) + WIRELESS_SUPER_SIM_HARDWARE = "wireless-super-sim-hardware" + WIRELESS_SUPER_SIM_HARDWARE_BULK = "wireless-super-sim-hardware-bulk" + WIRELESS_SUPER_SIM_SMSCOMMANDS = "wireless-super-sim-smscommands" + WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA = "wireless-super-sim-smscommands-africa" + WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA = "wireless-super-sim-smscommands-asia" + WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA = ( + "wireless-super-sim-smscommands-cent-and-south-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE = "wireless-super-sim-smscommands-europe" + WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA = ( + "wireless-super-sim-smscommands-north-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA = ( + "wireless-super-sim-smscommands-oceania" + ) + WIRELESS_SUPER_SIM_SUBSCRIPTION = "wireless-super-sim-subscription" + WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG = "wireless-super-sim-subscription-payg" + WIRELESS_USAGE = "wireless-usage" + WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" + WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" + WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" + WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-commands-centralandsouthamerica" + ) + WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" + WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" + WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" + WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" + WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" + WIRELESS_USAGE_DATA = "wireless-usage-data" + WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" + WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" + WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-data-centralandsouthamerica" + ) + WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( + "wireless-usage-data-custom-additionalmb" + ) + WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" + WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" + WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" + WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( + "wireless-usage-data-individual-additionalgb" + ) + WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( + "wireless-usage-data-individual-firstgb" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( + "wireless-usage-data-international-roaming-canada" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( + "wireless-usage-data-international-roaming-india" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( + "wireless-usage-data-international-roaming-mexico" + ) + WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" + WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" + WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" + WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" + WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" + WIRELESS_USAGE_MRC = "wireless-usage-mrc" + WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" + WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" + WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" + WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" + WIRELESS_USAGE_SMS = "wireless-usage-sms" + WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + :ivar api_version: The API version used to create the resource. + :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + :ivar category: + :ivar count: The number of usage events, such as the number of calls. + :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + :ivar description: A plain-language description of the usage category. + :ivar end_date: The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar price: The total price of the usage in the currency specified in `price_unit` and associated with the account. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + :ivar start_date: The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar subresource_uris: A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage: The amount used to bill usage and measured in units described in `usage_unit`. + :ivar usage_unit: The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.as_of: Optional[str] = payload.get("as_of") + self.category: Optional["YearlyInstance.Category"] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.YearlyInstance {}>".format(context) + + +class YearlyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> YearlyInstance: + """ + Build an instance of YearlyInstance + + :param payload: Payload response from the API + """ + return YearlyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.YearlyPage>" + + +class YearlyList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the YearlyList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/Yearly.json".format( + **self._solution + ) + + def stream( + self, + category: Union["YearlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[YearlyInstance]: + """ + Streams YearlyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "YearlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + category: Union["YearlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[YearlyInstance]: + """ + Asynchronously streams YearlyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "YearlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["YearlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[YearlyInstance]: + """ + Lists YearlyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "YearlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + category: Union["YearlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[YearlyInstance]: + """ + Asynchronously lists YearlyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "YearlyInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + category: Union["YearlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> YearlyPage: + """ + Retrieve a single page of YearlyInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of YearlyInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return YearlyPage(self._version, response, self._solution) + + async def page_async( + self, + category: Union["YearlyInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> YearlyPage: + """ + Asynchronously retrieve a single page of YearlyInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of YearlyInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return YearlyPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> YearlyPage: + """ + Retrieve a specific page of YearlyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of YearlyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return YearlyPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> YearlyPage: + """ + Asynchronously retrieve a specific page of YearlyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of YearlyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return YearlyPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.YearlyList>" diff --git a/twilio/rest/api/v2010/account/usage/record/yesterday.py b/twilio/rest/api/v2010/account/usage/record/yesterday.py new file mode 100644 index 0000000000..f3aacda8b9 --- /dev/null +++ b/twilio/rest/api/v2010/account/usage/record/yesterday.py @@ -0,0 +1,1211 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class YesterdayInstance(InstanceResource): + + class Category(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" + AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" + ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" + AUTHY_AUTHENTICATIONS = "authy-authentications" + AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" + AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" + AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" + AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" + AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" + CALL_PROGESS_EVENTS = "call-progess-events" + CALLERIDLOOKUPS = "calleridlookups" + CALLS = "calls" + CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" + CALLS_GLOBALCONFERENCE = "calls-globalconference" + CALLS_INBOUND = "calls-inbound" + CALLS_INBOUND_LOCAL = "calls-inbound-local" + CALLS_INBOUND_MOBILE = "calls-inbound-mobile" + CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" + CALLS_OUTBOUND = "calls-outbound" + CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" + CALLS_RECORDINGS = "calls-recordings" + CALLS_SIP = "calls-sip" + CALLS_SIP_INBOUND = "calls-sip-inbound" + CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" + CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" + CONVERSATIONS = "conversations" + CONVERSATIONS_API_REQUESTS = "conversations-api-requests" + CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" + CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" + CONVERSATIONS_EVENTS = "conversations-events" + CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" + CONVERSATIONS_PARTICIPANTS = "conversations-participants" + CPS = "cps" + CREDIT_TRANSFER = "credit-transfer" + EMAIL = "email" + EMERGING_TECH = "emerging-tech" + ENGAGEMENT_SUITE_PACKAGED_PLANS = "engagement-suite-packaged-plans" + ENHANCED_LINE_TYPE_LOOKUPS = "enhanced-line-type-lookups" + ENTERPRISE = "enterprise" + EVENTS = "events" + EXPERIMENT_FRANCE_SMS = "experiment-france-sms" + EXPERIMENT_INDIA_SMS = "experiment-india-sms" + EXPERIMENT_UK_SMS = "experiment-uk-sms" + FAILED_MESSAGE_PROCESSING_FEE = "failed-message-processing-fee" + FLEX = "flex" + FLEX_ACTIVE_USER_HOURS = "flex-active-user-hours" + FLEX_CONCURRENT_USERS = "flex-concurrent-users" + FLEX_CONVERSATIONAL_INSIGHTS = "flex-conversational-insights" + FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES = "flex-conversational-insights-messages" + FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = ( + "flex-conversational-insights-voice-minutes" + ) + FLEX_EMAIL_USAGE = "flex-email-usage" + FLEX_MESSAGING_USAGE = "flex-messaging-usage" + FLEX_PARTNER_SPINSCI = "flex-partner-spinsci" + FLEX_PARTNER_XCELERATE = "flex-partner-xcelerate" + FLEX_RESELLER_ECOSYSTEM = "flex-reseller-ecosystem" + FLEX_UNIQUE_USER = "flex-unique-user" + FLEX_USAGE = "flex-usage" + FLEX_USERS = "flex-users" + FLEX_VOICE_MINUTE = "flex-voice-minute" + FLEX_YTICA = "flex-ytica" + FRAUD_LOOKUPS = "fraud-lookups" + FRONTLINE = "frontline" + FRONTLINE_USERS = "frontline-users" + FUNCTIONS = "functions" + GENERIC_PAY_TRANSACTIONS = "generic-pay-transactions" + GROUP_ROOMS = "group-rooms" + GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" + GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" + GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" + GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" + GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" + GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" + GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" + GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" + IP_MESSAGING = "ip-messaging" + IP_MESSAGING_COMMANDS = "ip-messaging-commands" + IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" + IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" + IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" + IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" + IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" + LINE_STATUS_LOOKUPS = "line-status-lookups" + LIVE_ACTIVITY_LOOKUPS = "live-activity-lookups" + LOOKUP_BUCKET_ADJUSTMENT = "lookup-bucket-adjustment" + LOOKUP_IDENTITY_MATCH = "lookup-identity-match" + LOOKUPS = "lookups" + MARKETPLACE = "marketplace" + MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) + MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" + MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" + MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" + MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" + MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION = "marketplace-deepgram-transcription" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE = ( + "marketplace-deepgram-transcription-base" + ) + MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED = ( + "marketplace-deepgram-transscription-enhanced" + ) + MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( + "marketplace-digital-segment-business-info" + ) + MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( + "marketplace-facebook-offline-conversions" + ) + MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" + MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( + "marketplace-ibm-watson-message-insights" + ) + MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( + "marketplace-ibm-watson-message-sentiment" + ) + MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( + "marketplace-ibm-watson-recording-analysis" + ) + MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" + MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" + MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( + "marketplace-infogroup-dataaxle-bizinfo" + ) + MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( + "marketplace-keen-io-contact-center-analytics" + ) + MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" + MARKETPLACE_MARCHEX_RECORDING_ANALYSIS = ( + "marketplace-marchex-recording-analysis" + ) + MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( + "marketplace-marchex-sentiment-analysis-for-sms" + ) + MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( + "marketplace-marketplace-nextcaller-social-id" + ) + MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( + "marketplace-mobile-commons-opt-out-classifier" + ) + MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( + "marketplace-nexiwave-voicemail-to-text" + ) + MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( + "marketplace-nextcaller-advanced-caller-identification" + ) + MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" + MARKETPLACE_PAY_ADDONS = "marketplace-pay-addons" + MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR = ( + "marketplace-pay-addons-basecommerce-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR = ( + "marketplace-pay-addons-braintree-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR = ( + "marketplace-pay-addons-cardconnect-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR = ( + "marketplace-pay-addons-chase-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplace-pay-addons-shuttle-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplace-pay-addons-stripe-pay-connector" + ) + MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" + MARKETPLACE_POLY_AI_CONNECTOR = "marketplace-poly-ai-connector" + MARKETPLACE_REALPHONEVALIDATION = "marketplace-realphonevalidation" + MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( + "marketplace-remeeting-automatic-speech-recognition" + ) + MARKETPLACE_SPOKE_PHONE_LICENSE_PRO = "marketplace-spoke-phone-license-pro" + MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD = ( + "marketplace-spoke-phone-license-standard" + ) + MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( + "marketplace-tcpa-defense-solutions-blacklist-feed" + ) + MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" + MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION = ( + "marketplace-trestle-solutions-caller-identification" + ) + MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" + MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( + "marketplace-twilio-caller-name-lookup-us" + ) + MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( + "marketplace-twilio-carrier-information-lookup" + ) + MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" + MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" + MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) + MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" + MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( + "marketplace-ytica-contact-center-reporting-analytics" + ) + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplay-pay-addons-shuttle-pay-connector" + ) + MEDIA_COMPOSER_MINUTES = "media-composer-minutes" + MEDIASTORAGE = "mediastorage" + MIN_SPEND_ADJUSTMENTS = "min-spend-adjustments" + MMS = "mms" + MMS_INBOUND = "mms-inbound" + MMS_INBOUND_LONGCODE = "mms-inbound-longcode" + MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" + MMS_INBOUND_TOLL_FREE = "mms-inbound-toll-free" + MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" + MMS_OUTBOUND = "mms-outbound" + MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" + MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" + MMS_OUTBOUND_TOLLFREE = "mms-outbound-tollfree" + MONITOR = "monitor" + MONITOR_READS = "monitor-reads" + MONITOR_STORAGE = "monitor-storage" + MONITOR_WRITES = "monitor-writes" + NOTIFY = "notify" + NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" + NOTIFY_CHANNELS = "notify-channels" + NUMBER_FORMAT_LOOKUPS = "number-format-lookups" + PCHAT = "pchat" + PCHAT_ACTIONS = "pchat-actions" + PCHAT_APS = "pchat-aps" + PCHAT_CONV_MED_STORAGE = "pchat-conv-med-storage" + PCHAT_MESSAGES = "pchat-messages" + PCHAT_NOTIFICATIONS = "pchat-notifications" + PCHAT_READS = "pchat-reads" + PCHAT_USERS = "pchat-users" + PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "peer-to-peer-rooms-participant-minutes" + ) + PFAX = "pfax" + PFAX_MINUTES = "pfax-minutes" + PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" + PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" + PFAX_PAGES = "pfax-pages" + PHONE_QUALITY_SCORE_LOOKUPS = "phone-quality-score-lookups" + PHONENUMBERS = "phonenumbers" + PHONENUMBERS_CPS = "phonenumbers-cps" + PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" + PHONENUMBERS_LOCAL = "phonenumbers-local" + PHONENUMBERS_MOBILE = "phonenumbers-mobile" + PHONENUMBERS_PORTING = "phonenumbers-porting" + PHONENUMBERS_SETUPS = "phonenumbers-setups" + PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" + PREMIUMSUPPORT = "premiumsupport" + PREMIUMSUPPORT_PERCENTAGE_SPEND = "premiumsupport-percentage-spend" + PROGRAMMABLEVOICE_PLATFORM = "programmablevoice-platform" + PROGRAMMABLEVOICECONN_CLIENTSDK = "programmablevoiceconn-clientsdk" + PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND = ( + "programmablevoiceconn-clientsdk-inbound" + ) + PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND = ( + "programmablevoiceconn-clientsdk-outbound" + ) + PROGRAMMABLEVOICECONN_ONNET = "programmablevoiceconn-onnet" + PROGRAMMABLEVOICECONN_ONNET_INBOUND = "programmablevoiceconn-onnet-inbound" + PROGRAMMABLEVOICECONN_ONNET_OUTBOUND = "programmablevoiceconn-onnet-outbound" + PROGRAMMABLEVOICECONN_SIP = "programmablevoiceconn-sip" + PROGRAMMABLEVOICECONN_SIP_INBOUND = "programmablevoiceconn-sip-inbound" + PROGRAMMABLEVOICECONN_SIP_OUTBOUND = "programmablevoiceconn-sip-outbound" + PROGRAMMABLEVOICECONNECTIVITY = "programmablevoiceconnectivity" + PROXY = "proxy" + PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" + PROXY_BUCKET_ADJUSTMENT = "proxy-bucket-adjustment" + PROXY_LICENSES = "proxy-licenses" + PSTNCONNECTIVITY = "pstnconnectivity" + PSTNCONNECTIVITY_INBOUND = "pstnconnectivity-inbound" + PSTNCONNECTIVITY_OUTBOUND = "pstnconnectivity-outbound" + PV = "pv" + PV_BASIC_ROOMS = "pv-basic-rooms" + PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" + PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" + PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" + PV_COMPOSITION_MINUTES = "pv-composition-minutes" + PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" + PV_ROOM_PARTICIPANTS = "pv-room-participants" + PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" + PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" + PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" + PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" + PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" + PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" + PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" + PV_ROOMS = "pv-rooms" + PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" + RCS_MESSAGES = "rcs-messages" + REASSIGNED_NUMBER = "reassigned-number" + RECORDINGS = "recordings" + RECORDINGSTORAGE = "recordingstorage" + SHORTCODES = "shortcodes" + SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" + SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" + SHORTCODES_MPS = "shortcodes-mps" + SHORTCODES_RANDOM = "shortcodes-random" + SHORTCODES_SETUP_FEES = "shortcodes-setup-fees" + SHORTCODES_UK = "shortcodes-uk" + SHORTCODES_VANITY = "shortcodes-vanity" + SIM_SWAP_LOOKUPS = "sim-swap-lookups" + SIP_SECURE_MEDIA = "sip-secure-media" + SMALL_GROUP_ROOMS = "small-group-rooms" + SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" + SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" + SMS = "sms" + SMS_INBOUND = "sms-inbound" + SMS_INBOUND_LONGCODE = "sms-inbound-longcode" + SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" + SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" + SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) + SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" + SMS_OUTBOUND = "sms-outbound" + SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" + SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" + SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" + SPEECH_RECOGNITION = "speech-recognition" + STUDIO_ENGAGEMENTS = "studio-engagements" + SYNC = "sync" + SYNC_ACTIONS = "sync-actions" + SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" + SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" + TASKROUTER_TASKS = "taskrouter-tasks" + TOTALPRICE = "totalprice" + TRANSCRIPTIONS = "transcriptions" + TRUNKING_CPS = "trunking-cps" + TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" + TRUNKING_ORIGINATION = "trunking-origination" + TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" + TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" + TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" + TRUNKING_RECORDINGS = "trunking-recordings" + TRUNKING_SECURE = "trunking-secure" + TRUNKING_TERMINATION = "trunking-termination" + TTS_GOOGLE = "tts-google" + TURNMEGABYTES = "turnmegabytes" + TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" + TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" + TURNMEGABYTES_GERMANY = "turnmegabytes-germany" + TURNMEGABYTES_INDIA = "turnmegabytes-india" + TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" + TURNMEGABYTES_JAPAN = "turnmegabytes-japan" + TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" + TURNMEGABYTES_USEAST = "turnmegabytes-useast" + TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" + TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) + VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" + VOICE_INSIGHTS = "voice-insights" + VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-client-insights-on-demand-minute" + ) + VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-ptsn-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-interface-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-trunking-insights-on-demand-minute" + ) + VOICE_INTELLIGENCE = "voice-intelligence" + VOICE_INTELLIGENCE_EIP_OPERATORS = "voice-intelligence-eip-operators" + VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" + VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" + WDS = "wds" + WIRELESS = "wireless" + WIRELESS_DATA = "wireless-data" + WIRELESS_DATA_PAYG = "wireless-data-payg" + WIRELESS_DATA_PAYG_AFRICA = "wireless-data-payg-africa" + WIRELESS_DATA_PAYG_ASIA = "wireless-data-payg-asia" + WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA = ( + "wireless-data-payg-centralandsouthamerica" + ) + WIRELESS_DATA_PAYG_EUROPE = "wireless-data-payg-europe" + WIRELESS_DATA_PAYG_NORTHAMERICA = "wireless-data-payg-northamerica" + WIRELESS_DATA_PAYG_OCEANIA = "wireless-data-payg-oceania" + WIRELESS_DATA_QUOTA1 = "wireless-data-quota1" + WIRELESS_DATA_QUOTA1_AFRICA = "wireless-data-quota1-africa" + WIRELESS_DATA_QUOTA1_ASIA = "wireless-data-quota1-asia" + WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota1-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA1_EUROPE = "wireless-data-quota1-europe" + WIRELESS_DATA_QUOTA1_NORTHAMERICA = "wireless-data-quota1-northamerica" + WIRELESS_DATA_QUOTA1_OCEANIA = "wireless-data-quota1-oceania" + WIRELESS_DATA_QUOTA10 = "wireless-data-quota10" + WIRELESS_DATA_QUOTA10_AFRICA = "wireless-data-quota10-africa" + WIRELESS_DATA_QUOTA10_ASIA = "wireless-data-quota10-asia" + WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota10-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA10_EUROPE = "wireless-data-quota10-europe" + WIRELESS_DATA_QUOTA10_NORTHAMERICA = "wireless-data-quota10-northamerica" + WIRELESS_DATA_QUOTA10_OCEANIA = "wireless-data-quota10-oceania" + WIRELESS_DATA_QUOTA50 = "wireless-data-quota50" + WIRELESS_DATA_QUOTA50_AFRICA = "wireless-data-quota50-africa" + WIRELESS_DATA_QUOTA50_ASIA = "wireless-data-quota50-asia" + WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota50-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA50_EUROPE = "wireless-data-quota50-europe" + WIRELESS_DATA_QUOTA50_NORTHAMERICA = "wireless-data-quota50-northamerica" + WIRELESS_DATA_QUOTA50_OCEANIA = "wireless-data-quota50-oceania" + WIRELESS_DATA_QUOTACUSTOM = "wireless-data-quotacustom" + WIRELESS_DATA_QUOTACUSTOM_AFRICA = "wireless-data-quotacustom-africa" + WIRELESS_DATA_QUOTACUSTOM_ASIA = "wireless-data-quotacustom-asia" + WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quotacustom-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_EUROPE = "wireless-data-quotacustom-europe" + WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA = ( + "wireless-data-quotacustom-northamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_OCEANIA = "wireless-data-quotacustom-oceania" + WIRELESS_MRC_PAYG = "wireless-mrc-payg" + WIRELESS_MRC_QUOTA1 = "wireless-mrc-quota1" + WIRELESS_MRC_QUOTA10 = "wireless-mrc-quota10" + WIRELESS_MRC_QUOTA50 = "wireless-mrc-quota50" + WIRELESS_MRC_QUOTACUSTOM = "wireless-mrc-quotacustom" + WIRELESS_ORDERS = "wireless-orders" + WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" + WIRELESS_ORDERS_BULK = "wireless-orders-bulk" + WIRELESS_ORDERS_ESIM = "wireless-orders-esim" + WIRELESS_ORDERS_STARTER = "wireless-orders-starter" + WIRELESS_QUOTAS = "wireless-quotas" + WIRELESS_SMS_AFRICA = "wireless-sms-africa" + WIRELESS_SMS_ASIA = "wireless-sms-asia" + WIRELESS_SMS_CENTRALANDSOUTHAMERICA = "wireless-sms-centralandsouthamerica" + WIRELESS_SMS_EUROPE = "wireless-sms-europe" + WIRELESS_SMS_NORTHAMERICA = "wireless-sms-northamerica" + WIRELESS_SMS_OCEANIA = "wireless-sms-oceania" + WIRELESS_SUPER_SIM = "wireless-super-sim" + WIRELESS_SUPER_SIM_DATA = "wireless-super-sim-data" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA = ( + "wireless-super-sim-data-north-america-usa" + ) + WIRELESS_SUPER_SIM_DATA_PAYG = "wireless-super-sim-data-payg" + WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE = "wireless-super-sim-data-payg-europe" + WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA = ( + "wireless-super-sim-data-payg-north-america" + ) + WIRELESS_SUPER_SIM_HARDWARE = "wireless-super-sim-hardware" + WIRELESS_SUPER_SIM_HARDWARE_BULK = "wireless-super-sim-hardware-bulk" + WIRELESS_SUPER_SIM_SMSCOMMANDS = "wireless-super-sim-smscommands" + WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA = "wireless-super-sim-smscommands-africa" + WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA = "wireless-super-sim-smscommands-asia" + WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA = ( + "wireless-super-sim-smscommands-cent-and-south-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE = "wireless-super-sim-smscommands-europe" + WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA = ( + "wireless-super-sim-smscommands-north-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA = ( + "wireless-super-sim-smscommands-oceania" + ) + WIRELESS_SUPER_SIM_SUBSCRIPTION = "wireless-super-sim-subscription" + WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG = "wireless-super-sim-subscription-payg" + WIRELESS_USAGE = "wireless-usage" + WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" + WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" + WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" + WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-commands-centralandsouthamerica" + ) + WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" + WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" + WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" + WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" + WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" + WIRELESS_USAGE_DATA = "wireless-usage-data" + WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" + WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" + WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-data-centralandsouthamerica" + ) + WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( + "wireless-usage-data-custom-additionalmb" + ) + WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" + WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" + WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" + WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( + "wireless-usage-data-individual-additionalgb" + ) + WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( + "wireless-usage-data-individual-firstgb" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( + "wireless-usage-data-international-roaming-canada" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( + "wireless-usage-data-international-roaming-india" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( + "wireless-usage-data-international-roaming-mexico" + ) + WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" + WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" + WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" + WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" + WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" + WIRELESS_USAGE_MRC = "wireless-usage-mrc" + WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" + WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" + WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" + WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" + WIRELESS_USAGE_SMS = "wireless-usage-sms" + WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that accrued the usage. + :ivar api_version: The API version used to create the resource. + :ivar as_of: Usage records up to date as of this timestamp, formatted as YYYY-MM-DDTHH:MM:SS+00:00. All timestamps are in GMT + :ivar category: + :ivar count: The number of usage events, such as the number of calls. + :ivar count_unit: The units in which `count` is measured, such as `calls` for calls or `messages` for SMS. + :ivar description: A plain-language description of the usage category. + :ivar end_date: The last date for which usage is included in the UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar price: The total price of the usage in the currency specified in `price_unit` and associated with the account. + :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format, such as `usd`, `eur`, and `jpy`. + :ivar start_date: The first date for which usage is included in this UsageRecord. The date is specified in GMT and formatted as `YYYY-MM-DD`. + :ivar subresource_uris: A list of related resources identified by their URIs. For more information, see [List Subresources](https://www.twilio.com/docs/usage/api/usage-record#list-subresources). + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage: The amount used to bill usage and measured in units described in `usage_unit`. + :ivar usage_unit: The units in which `usage` is measured, such as `minutes` for calls or `messages` for SMS. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.as_of: Optional[str] = payload.get("as_of") + self.category: Optional["YesterdayInstance.Category"] = payload.get("category") + self.count: Optional[str] = payload.get("count") + self.count_unit: Optional[str] = payload.get("count_unit") + self.description: Optional[str] = payload.get("description") + self.end_date: Optional[date] = deserialize.iso8601_date( + payload.get("end_date") + ) + self.price: Optional[float] = deserialize.decimal(payload.get("price")) + self.price_unit: Optional[str] = payload.get("price_unit") + self.start_date: Optional[date] = deserialize.iso8601_date( + payload.get("start_date") + ) + self.subresource_uris: Optional[Dict[str, object]] = payload.get( + "subresource_uris" + ) + self.uri: Optional[str] = payload.get("uri") + self.usage: Optional[str] = payload.get("usage") + self.usage_unit: Optional[str] = payload.get("usage_unit") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.YesterdayInstance {}>".format(context) + + +class YesterdayPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> YesterdayInstance: + """ + Build an instance of YesterdayInstance + + :param payload: Payload response from the API + """ + return YesterdayInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.YesterdayPage>" + + +class YesterdayList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the YesterdayList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Records/Yesterday.json".format( + **self._solution + ) + + def stream( + self, + category: Union["YesterdayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[YesterdayInstance]: + """ + Streams YesterdayInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "YesterdayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + category: Union["YesterdayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[YesterdayInstance]: + """ + Asynchronously streams YesterdayInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "YesterdayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + category: Union["YesterdayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[YesterdayInstance]: + """ + Lists YesterdayInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "YesterdayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + category: Union["YesterdayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[YesterdayInstance]: + """ + Asynchronously lists YesterdayInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "YesterdayInstance.Category" category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param bool include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + category=category, + start_date=start_date, + end_date=end_date, + include_subaccounts=include_subaccounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + category: Union["YesterdayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> YesterdayPage: + """ + Retrieve a single page of YesterdayInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of YesterdayInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return YesterdayPage(self._version, response, self._solution) + + async def page_async( + self, + category: Union["YesterdayInstance.Category", object] = values.unset, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + include_subaccounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> YesterdayPage: + """ + Asynchronously retrieve a single page of YesterdayInstance records from the API. + Request is executed immediately + + :param category: The [usage category](https://www.twilio.com/docs/usage/api/usage-record#usage-categories) of the UsageRecord resources to read. Only UsageRecord resources in the specified category are retrieved. + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `-30days`, which will set the start date to be 30 days before the current date. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. You can also specify offsets from the current date, such as: `+30days`, which will set the end date to 30 days from the current date. + :param include_subaccounts: Whether to include usage from the master account and all its subaccounts. Can be: `true` (the default) to include usage from the master account and all subaccounts or `false` to retrieve usage from only the specified account. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of YesterdayInstance + """ + data = values.of( + { + "Category": category, + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return YesterdayPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> YesterdayPage: + """ + Retrieve a specific page of YesterdayInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of YesterdayInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return YesterdayPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> YesterdayPage: + """ + Asynchronously retrieve a specific page of YesterdayInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of YesterdayInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return YesterdayPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.YesterdayList>" diff --git a/twilio/rest/api/v2010/account/usage/trigger.py b/twilio/rest/api/v2010/account/usage/trigger.py new file mode 100644 index 0000000000..7f182a01b3 --- /dev/null +++ b/twilio/rest/api/v2010/account/usage/trigger.py @@ -0,0 +1,1611 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TriggerInstance(InstanceResource): + + class Recurring(object): + DAILY = "daily" + MONTHLY = "monthly" + YEARLY = "yearly" + ALLTIME = "alltime" + + class TriggerField(object): + COUNT = "count" + USAGE = "usage" + PRICE = "price" + + class UsageCategory(object): + A2P_10DLC_REGISTRATIONFEES_BRANDREGISTRATION = ( + "a2p-10dlc-registrationfees-brandregistration" + ) + A2P_10DLC_REGISTRATIONFEES_BV = "a2p-10dlc-registrationfees-bv" + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNCHARGES = ( + "a2p-10dlc-registrationfees-campaigncharges" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNREGISTRATION = ( + "a2p-10dlc-registrationfees-campaignregistration" + ) + A2P_10DLC_REGISTRATIONFEES_CAMPAIGNVETTING = ( + "a2p-10dlc-registrationfees-campaignvetting" + ) + A2P_10DLC_REGISTRATIONFEES_MONTHLY = "a2p-10dlc-registrationfees-monthly" + A2P_10DLC_REGISTRATIONFEES_ONETIME = "a2p-10dlc-registrationfees-onetime" + A2P_REGISTRATION_FEES = "a2p-registration-fees" + ACCOUNT_SECURITY = "account-security" + AGENT_CONFERENCE = "agent-conference" + AGENT_COPILOT = "agent-copilot" + AGENT_COPILOT_MESSAGES = "agent-copilot-messages" + AGENT_COPILOT_PARTICIPANT_MINUTES = "agent-copilot-participant-minutes" + AI_ASSISTANTS = "ai-assistants" + AI_ASSISTANTS_VOICE = "ai-assistants-voice" + AMAZON_POLLY = "amazon-polly" + ANSWERING_MACHINE_DETECTION = "answering-machine-detection" + ASSETS = "assets" + AUDIENCE_MINUTES = "audience-minutes" + AUDIENCE_MINUTES_AUDIO = "audience-minutes-audio" + AUTHY_AUTHENTICATIONS = "authy-authentications" + AUTHY_CALLS_OUTBOUND = "authy-calls-outbound" + AUTHY_EMAIL_AUTHENTICATIONS = "authy-email-authentications" + AUTHY_MONTHLY_FEES = "authy-monthly-fees" + AUTHY_OUTBOUND_EMAIL = "authy-outbound-email" + AUTHY_PHONE_INTELLIGENCE = "authy-phone-intelligence" + AUTHY_PHONE_VERIFICATIONS = "authy-phone-verifications" + AUTHY_SMS_OUTBOUND = "authy-sms-outbound" + AUTHY_VERIFY_EMAIL_VERIFICATIONS = "authy-verify-email-verifications" + AUTHY_VERIFY_OUTBOUND_EMAIL = "authy-verify-outbound-email" + AUTOPILOT = "autopilot" + AUTOPILOT_HOME_ASSISTANTS = "autopilot-home-assistants" + AUTOPILOT_MESSAGING = "autopilot-messaging" + AUTOPILOT_OTHER = "autopilot-other" + AUTOPILOT_VOICE = "autopilot-voice" + BASIC_PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "basic-peer-to-peer-rooms-participant-minutes" + ) + BRANDED_CALLING = "branded-calling" + BUNDLE_SMS_BUCKET = "bundle-sms-bucket" + BUNDLE_SUBSCRIPTION_FEES = "bundle-subscription-fees" + CALL_FORWARDING_LOOKUPS = "call-forwarding-lookups" + CALL_PROGESS_EVENTS = "call-progess-events" + CALLERIDLOOKUPS = "calleridlookups" + CALLS = "calls" + CALLS_CLIENT = "calls-client" + CALLS_EMERGENCY = "calls-emergency" + CALLS_GLOBALCONFERENCE = "calls-globalconference" + CALLS_INBOUND = "calls-inbound" + CALLS_INBOUND_LOCAL = "calls-inbound-local" + CALLS_INBOUND_MOBILE = "calls-inbound-mobile" + CALLS_INBOUND_TOLLFREE = "calls-inbound-tollfree" + CALLS_INBOUND_TOLLFREE_LOCAL = "calls-inbound-tollfree-local" + CALLS_INBOUND_TOLLFREE_MOBILE = "calls-inbound-tollfree-mobile" + CALLS_MEDIA_STREAM_MINUTES = "calls-media-stream-minutes" + CALLS_OUTBOUND = "calls-outbound" + CALLS_PAY_VERB_TRANSACTIONS = "calls-pay-verb-transactions" + CALLS_RECORDINGS = "calls-recordings" + CALLS_SIP = "calls-sip" + CALLS_SIP_INBOUND = "calls-sip-inbound" + CALLS_SIP_OUTBOUND = "calls-sip-outbound" + CALLS_TEXT_TO_SPEECH = "calls-text-to-speech" + CALLS_TRANSFERS = "calls-transfers" + CARRIER_LOOKUPS = "carrier-lookups" + CATEGORY = "category" + CHANNELS = "channels" + CHANNELS_MESSAGING = "channels-messaging" + CHANNELS_MESSAGING_INBOUND = "channels-messaging-inbound" + CHANNELS_MESSAGING_OUTBOUND = "channels-messaging-outbound" + CHANNELS_WHATSAPP = "channels-whatsapp" + CHANNELS_WHATSAPP_CONVERSATION_AUTHENTICATION = ( + "channels-whatsapp-conversation-authentication" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE = "channels-whatsapp-conversation-free" + CHANNELS_WHATSAPP_CONVERSATION_MARKETING = ( + "channels-whatsapp-conversation-marketing" + ) + CHANNELS_WHATSAPP_CONVERSATION_SERVICE = ( + "channels-whatsapp-conversation-service" + ) + CHANNELS_WHATSAPP_CONVERSATION_UTILITY = ( + "channels-whatsapp-conversation-utility" + ) + CHANNELS_WHATSAPP_INBOUND = "channels-whatsapp-inbound" + CHANNELS_WHATSAPP_OUTBOUND = "channels-whatsapp-outbound" + CHAT_VIRTUAL_AGENT = "chat-virtual-agent" + CONVERSATION_RELAY = "conversation-relay" + CONVERSATIONS = "conversations" + CONVERSATIONS_API_REQUESTS = "conversations-api-requests" + CONVERSATIONS_CONVERSATION_EVENTS = "conversations-conversation-events" + CONVERSATIONS_ENDPOINT_CONNECTIVITY = "conversations-endpoint-connectivity" + CONVERSATIONS_EVENTS = "conversations-events" + CONVERSATIONS_PARTICIPANT_EVENTS = "conversations-participant-events" + CONVERSATIONS_PARTICIPANTS = "conversations-participants" + CPS = "cps" + CREDIT_TRANSFER = "credit-transfer" + EMAIL = "email" + EMERGING_TECH = "emerging-tech" + ENGAGEMENT_SUITE_PACKAGED_PLANS = "engagement-suite-packaged-plans" + ENHANCED_LINE_TYPE_LOOKUPS = "enhanced-line-type-lookups" + ENTERPRISE = "enterprise" + EVENTS = "events" + EXPERIMENT_FRANCE_SMS = "experiment-france-sms" + EXPERIMENT_INDIA_SMS = "experiment-india-sms" + EXPERIMENT_UK_SMS = "experiment-uk-sms" + FAILED_MESSAGE_PROCESSING_FEE = "failed-message-processing-fee" + FLEX = "flex" + FLEX_ACTIVE_USER_HOURS = "flex-active-user-hours" + FLEX_CONCURRENT_USERS = "flex-concurrent-users" + FLEX_CONVERSATIONAL_INSIGHTS = "flex-conversational-insights" + FLEX_CONVERSATIONAL_INSIGHTS_MESSAGES = "flex-conversational-insights-messages" + FLEX_CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = ( + "flex-conversational-insights-voice-minutes" + ) + FLEX_EMAIL_USAGE = "flex-email-usage" + FLEX_MESSAGING_USAGE = "flex-messaging-usage" + FLEX_PARTNER_SPINSCI = "flex-partner-spinsci" + FLEX_PARTNER_XCELERATE = "flex-partner-xcelerate" + FLEX_RESELLER_ECOSYSTEM = "flex-reseller-ecosystem" + FLEX_UNIQUE_USER = "flex-unique-user" + FLEX_USAGE = "flex-usage" + FLEX_USERS = "flex-users" + FLEX_VOICE_MINUTE = "flex-voice-minute" + FLEX_YTICA = "flex-ytica" + FRAUD_LOOKUPS = "fraud-lookups" + FRONTLINE = "frontline" + FRONTLINE_USERS = "frontline-users" + FUNCTIONS = "functions" + GENERIC_PAY_TRANSACTIONS = "generic-pay-transactions" + GROUP_ROOMS = "group-rooms" + GROUP_ROOMS_DATA_TRACK = "group-rooms-data-track" + GROUP_ROOMS_ENCRYPTED_MEDIA_RECORDED = "group-rooms-encrypted-media-recorded" + GROUP_ROOMS_MEDIA_DOWNLOADED = "group-rooms-media-downloaded" + GROUP_ROOMS_MEDIA_RECORDED = "group-rooms-media-recorded" + GROUP_ROOMS_MEDIA_ROUTED = "group-rooms-media-routed" + GROUP_ROOMS_MEDIA_STORED = "group-rooms-media-stored" + GROUP_ROOMS_PARTICIPANT_MINUTES = "group-rooms-participant-minutes" + GROUP_ROOMS_RECORDED_MINUTES = "group-rooms-recorded-minutes" + IP_MESSAGING = "ip-messaging" + IP_MESSAGING_COMMANDS = "ip-messaging-commands" + IP_MESSAGING_DATA_STORAGE = "ip-messaging-data-storage" + IP_MESSAGING_DATA_TRANSFER = "ip-messaging-data-transfer" + IP_MESSAGING_ENDPOINT_CONNECTIVITY = "ip-messaging-endpoint-connectivity" + IVR_VIRTUAL_AGENT_CUSTOM_VOICES = "ivr-virtual-agent-custom-voices" + IVR_VIRTUAL_AGENT_GENAI = "ivr-virtual-agent-genai" + LINE_STATUS_LOOKUPS = "line-status-lookups" + LIVE_ACTIVITY_LOOKUPS = "live-activity-lookups" + LOOKUP_BUCKET_ADJUSTMENT = "lookup-bucket-adjustment" + LOOKUP_IDENTITY_MATCH = "lookup-identity-match" + LOOKUPS = "lookups" + MARKETPLACE = "marketplace" + MARKETPLACE_ALGORITHMIA_NAMED_ENTITY_RECOGNITION = ( + "marketplace-algorithmia-named-entity-recognition" + ) + MARKETPLACE_CADENCE_TRANSCRIPTION = "marketplace-cadence-transcription" + MARKETPLACE_CADENCE_TRANSLATION = "marketplace-cadence-translation" + MARKETPLACE_CAPIO_SPEECH_TO_TEXT = "marketplace-capio-speech-to-text" + MARKETPLACE_CONVRIZA_ABABA = "marketplace-convriza-ababa" + MARKETPLACE_DEEPGRAM_PHRASE_DETECTOR = "marketplace-deepgram-phrase-detector" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION = "marketplace-deepgram-transcription" + MARKETPLACE_DEEPGRAM_TRANSCRIPTION_BASE = ( + "marketplace-deepgram-transcription-base" + ) + MARKETPLACE_DEEPGRAM_TRANSSCRIPTION_ENHANCED = ( + "marketplace-deepgram-transscription-enhanced" + ) + MARKETPLACE_DIGITAL_SEGMENT_BUSINESS_INFO = ( + "marketplace-digital-segment-business-info" + ) + MARKETPLACE_FACEBOOK_OFFLINE_CONVERSIONS = ( + "marketplace-facebook-offline-conversions" + ) + MARKETPLACE_GOOGLE_SPEECH_TO_TEXT = "marketplace-google-speech-to-text" + MARKETPLACE_IBM_WATSON_MESSAGE_INSIGHTS = ( + "marketplace-ibm-watson-message-insights" + ) + MARKETPLACE_IBM_WATSON_MESSAGE_SENTIMENT = ( + "marketplace-ibm-watson-message-sentiment" + ) + MARKETPLACE_IBM_WATSON_RECORDING_ANALYSIS = ( + "marketplace-ibm-watson-recording-analysis" + ) + MARKETPLACE_IBM_WATSON_TONE_ANALYZER = "marketplace-ibm-watson-tone-analyzer" + MARKETPLACE_ICEHOOK_SYSTEMS_SCOUT = "marketplace-icehook-systems-scout" + MARKETPLACE_INFOGROUP_DATAAXLE_BIZINFO = ( + "marketplace-infogroup-dataaxle-bizinfo" + ) + MARKETPLACE_KEEN_IO_CONTACT_CENTER_ANALYTICS = ( + "marketplace-keen-io-contact-center-analytics" + ) + MARKETPLACE_MARCHEX_CLEANCALL = "marketplace-marchex-cleancall" + MARKETPLACE_MARCHEX_RECORDING_ANALYSIS = ( + "marketplace-marchex-recording-analysis" + ) + MARKETPLACE_MARCHEX_SENTIMENT_ANALYSIS_FOR_SMS = ( + "marketplace-marchex-sentiment-analysis-for-sms" + ) + MARKETPLACE_MARKETPLACE_NEXTCALLER_SOCIAL_ID = ( + "marketplace-marketplace-nextcaller-social-id" + ) + MARKETPLACE_MOBILE_COMMONS_OPT_OUT_CLASSIFIER = ( + "marketplace-mobile-commons-opt-out-classifier" + ) + MARKETPLACE_NEXIWAVE_VOICEMAIL_TO_TEXT = ( + "marketplace-nexiwave-voicemail-to-text" + ) + MARKETPLACE_NEXTCALLER_ADVANCED_CALLER_IDENTIFICATION = ( + "marketplace-nextcaller-advanced-caller-identification" + ) + MARKETPLACE_NOMOROBO_SPAM_SCORE = "marketplace-nomorobo-spam-score" + MARKETPLACE_PAY_ADDONS = "marketplace-pay-addons" + MARKETPLACE_PAY_ADDONS_BASECOMMERCE_PAY_CONNECTOR = ( + "marketplace-pay-addons-basecommerce-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_BRAINTREE_PAY_CONNECTOR = ( + "marketplace-pay-addons-braintree-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CARDCONNECT_PAY_CONNECTOR = ( + "marketplace-pay-addons-cardconnect-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_CHASE_PAY_CONNECTOR = ( + "marketplace-pay-addons-chase-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplace-pay-addons-shuttle-pay-connector" + ) + MARKETPLACE_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplace-pay-addons-stripe-pay-connector" + ) + MARKETPLACE_PAYFONE_TCPA_COMPLIANCE = "marketplace-payfone-tcpa-compliance" + MARKETPLACE_POLY_AI_CONNECTOR = "marketplace-poly-ai-connector" + MARKETPLACE_REALPHONEVALIDATION = "marketplace-realphonevalidation" + MARKETPLACE_REMEETING_AUTOMATIC_SPEECH_RECOGNITION = ( + "marketplace-remeeting-automatic-speech-recognition" + ) + MARKETPLACE_SPOKE_PHONE_LICENSE_PRO = "marketplace-spoke-phone-license-pro" + MARKETPLACE_SPOKE_PHONE_LICENSE_STANDARD = ( + "marketplace-spoke-phone-license-standard" + ) + MARKETPLACE_TCPA_DEFENSE_SOLUTIONS_BLACKLIST_FEED = ( + "marketplace-tcpa-defense-solutions-blacklist-feed" + ) + MARKETPLACE_TELO_OPENCNAM = "marketplace-telo-opencnam" + MARKETPLACE_TRESTLE_SOLUTIONS_CALLER_IDENTIFICATION = ( + "marketplace-trestle-solutions-caller-identification" + ) + MARKETPLACE_TRUECNAM_TRUE_SPAM = "marketplace-truecnam-true-spam" + MARKETPLACE_TWILIO_CALLER_NAME_LOOKUP_US = ( + "marketplace-twilio-caller-name-lookup-us" + ) + MARKETPLACE_TWILIO_CARRIER_INFORMATION_LOOKUP = ( + "marketplace-twilio-carrier-information-lookup" + ) + MARKETPLACE_VOICEBASE_PCI = "marketplace-voicebase-pci" + MARKETPLACE_VOICEBASE_TRANSCRIPTION = "marketplace-voicebase-transcription" + MARKETPLACE_VOICEBASE_TRANSCRIPTION_CUSTOM_VOCABULARY = ( + "marketplace-voicebase-transcription-custom-vocabulary" + ) + MARKETPLACE_WEB_PURIFY_PROFANITY_FILTER = ( + "marketplace-web-purify-profanity-filter" + ) + MARKETPLACE_WHITEPAGES_PRO_CALLER_IDENTIFICATION = ( + "marketplace-whitepages-pro-caller-identification" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_INTELLIGENCE = ( + "marketplace-whitepages-pro-phone-intelligence" + ) + MARKETPLACE_WHITEPAGES_PRO_PHONE_REPUTATION = ( + "marketplace-whitepages-pro-phone-reputation" + ) + MARKETPLACE_WOLFARM_SPOKEN_RESULTS = "marketplace-wolfarm-spoken-results" + MARKETPLACE_WOLFRAM_SHORT_ANSWER = "marketplace-wolfram-short-answer" + MARKETPLACE_YTICA_CONTACT_CENTER_REPORTING_ANALYTICS = ( + "marketplace-ytica-contact-center-reporting-analytics" + ) + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR = ( + "marketplay-pay-addons-shuttle-pay-connector" + ) + MEDIA_COMPOSER_MINUTES = "media-composer-minutes" + MEDIASTORAGE = "mediastorage" + MIN_SPEND_ADJUSTMENTS = "min-spend-adjustments" + MMS = "mms" + MMS_INBOUND = "mms-inbound" + MMS_INBOUND_LONGCODE = "mms-inbound-longcode" + MMS_INBOUND_SHORTCODE = "mms-inbound-shortcode" + MMS_INBOUND_TOLL_FREE = "mms-inbound-toll-free" + MMS_MESSAGES_CARRIERFEES = "mms-messages-carrierfees" + MMS_OUTBOUND = "mms-outbound" + MMS_OUTBOUND_LONGCODE = "mms-outbound-longcode" + MMS_OUTBOUND_SHORTCODE = "mms-outbound-shortcode" + MMS_OUTBOUND_TOLLFREE = "mms-outbound-tollfree" + MONITOR = "monitor" + MONITOR_READS = "monitor-reads" + MONITOR_STORAGE = "monitor-storage" + MONITOR_WRITES = "monitor-writes" + NOTIFY = "notify" + NOTIFY_ACTIONS_ATTEMPTS = "notify-actions-attempts" + NOTIFY_CHANNELS = "notify-channels" + NUMBER_FORMAT_LOOKUPS = "number-format-lookups" + PCHAT = "pchat" + PCHAT_ACTIONS = "pchat-actions" + PCHAT_APS = "pchat-aps" + PCHAT_CONV_MED_STORAGE = "pchat-conv-med-storage" + PCHAT_MESSAGES = "pchat-messages" + PCHAT_NOTIFICATIONS = "pchat-notifications" + PCHAT_READS = "pchat-reads" + PCHAT_USERS = "pchat-users" + PEER_TO_PEER_ROOMS_PARTICIPANT_MINUTES = ( + "peer-to-peer-rooms-participant-minutes" + ) + PFAX = "pfax" + PFAX_MINUTES = "pfax-minutes" + PFAX_MINUTES_INBOUND = "pfax-minutes-inbound" + PFAX_MINUTES_OUTBOUND = "pfax-minutes-outbound" + PFAX_PAGES = "pfax-pages" + PHONE_QUALITY_SCORE_LOOKUPS = "phone-quality-score-lookups" + PHONENUMBERS = "phonenumbers" + PHONENUMBERS_CPS = "phonenumbers-cps" + PHONENUMBERS_EMERGENCY = "phonenumbers-emergency" + PHONENUMBERS_LOCAL = "phonenumbers-local" + PHONENUMBERS_MOBILE = "phonenumbers-mobile" + PHONENUMBERS_PORTING = "phonenumbers-porting" + PHONENUMBERS_SETUPS = "phonenumbers-setups" + PHONENUMBERS_TOLLFREE = "phonenumbers-tollfree" + PREMIUMSUPPORT = "premiumsupport" + PREMIUMSUPPORT_PERCENTAGE_SPEND = "premiumsupport-percentage-spend" + PROGRAMMABLEVOICE_PLATFORM = "programmablevoice-platform" + PROGRAMMABLEVOICECONN_CLIENTSDK = "programmablevoiceconn-clientsdk" + PROGRAMMABLEVOICECONN_CLIENTSDK_INBOUND = ( + "programmablevoiceconn-clientsdk-inbound" + ) + PROGRAMMABLEVOICECONN_CLIENTSDK_OUTBOUND = ( + "programmablevoiceconn-clientsdk-outbound" + ) + PROGRAMMABLEVOICECONN_ONNET = "programmablevoiceconn-onnet" + PROGRAMMABLEVOICECONN_ONNET_INBOUND = "programmablevoiceconn-onnet-inbound" + PROGRAMMABLEVOICECONN_ONNET_OUTBOUND = "programmablevoiceconn-onnet-outbound" + PROGRAMMABLEVOICECONN_SIP = "programmablevoiceconn-sip" + PROGRAMMABLEVOICECONN_SIP_INBOUND = "programmablevoiceconn-sip-inbound" + PROGRAMMABLEVOICECONN_SIP_OUTBOUND = "programmablevoiceconn-sip-outbound" + PROGRAMMABLEVOICECONNECTIVITY = "programmablevoiceconnectivity" + PROXY = "proxy" + PROXY_ACTIVE_SESSIONS = "proxy-active-sessions" + PROXY_BUCKET_ADJUSTMENT = "proxy-bucket-adjustment" + PROXY_LICENSES = "proxy-licenses" + PSTNCONNECTIVITY = "pstnconnectivity" + PSTNCONNECTIVITY_INBOUND = "pstnconnectivity-inbound" + PSTNCONNECTIVITY_OUTBOUND = "pstnconnectivity-outbound" + PV = "pv" + PV_BASIC_ROOMS = "pv-basic-rooms" + PV_COMPOSITION_MEDIA_DOWNLOADED = "pv-composition-media-downloaded" + PV_COMPOSITION_MEDIA_ENCRYPTED = "pv-composition-media-encrypted" + PV_COMPOSITION_MEDIA_STORED = "pv-composition-media-stored" + PV_COMPOSITION_MINUTES = "pv-composition-minutes" + PV_RECORDING_COMPOSITIONS = "pv-recording-compositions" + PV_ROOM_PARTICIPANTS = "pv-room-participants" + PV_ROOM_PARTICIPANTS_AU1 = "pv-room-participants-au1" + PV_ROOM_PARTICIPANTS_BR1 = "pv-room-participants-br1" + PV_ROOM_PARTICIPANTS_IE1 = "pv-room-participants-ie1" + PV_ROOM_PARTICIPANTS_JP1 = "pv-room-participants-jp1" + PV_ROOM_PARTICIPANTS_SG1 = "pv-room-participants-sg1" + PV_ROOM_PARTICIPANTS_US1 = "pv-room-participants-us1" + PV_ROOM_PARTICIPANTS_US2 = "pv-room-participants-us2" + PV_ROOMS = "pv-rooms" + PV_SIP_ENDPOINT_REGISTRATIONS = "pv-sip-endpoint-registrations" + RCS_MESSAGES = "rcs-messages" + REASSIGNED_NUMBER = "reassigned-number" + RECORDINGS = "recordings" + RECORDINGSTORAGE = "recordingstorage" + SHORTCODES = "shortcodes" + SHORTCODES_CUSTOMEROWNED = "shortcodes-customerowned" + SHORTCODES_MMS_ENABLEMENT = "shortcodes-mms-enablement" + SHORTCODES_MPS = "shortcodes-mps" + SHORTCODES_RANDOM = "shortcodes-random" + SHORTCODES_SETUP_FEES = "shortcodes-setup-fees" + SHORTCODES_UK = "shortcodes-uk" + SHORTCODES_VANITY = "shortcodes-vanity" + SIM_SWAP_LOOKUPS = "sim-swap-lookups" + SIP_SECURE_MEDIA = "sip-secure-media" + SMALL_GROUP_ROOMS = "small-group-rooms" + SMALL_GROUP_ROOMS_DATA_TRACK = "small-group-rooms-data-track" + SMALL_GROUP_ROOMS_PARTICIPANT_MINUTES = "small-group-rooms-participant-minutes" + SMS = "sms" + SMS_INBOUND = "sms-inbound" + SMS_INBOUND_LONGCODE = "sms-inbound-longcode" + SMS_INBOUND_SHORTCODE = "sms-inbound-shortcode" + SMS_INBOUND_TOLLFREE = "sms-inbound-tollfree" + SMS_MESSAGES_CARRIERFEES = "sms-messages-carrierfees" + SMS_MESSAGES_FEATURES = "sms-messages-features" + SMS_MESSAGES_FEATURES_ENGAGEMENT_SUITE = ( + "sms-messages-features-engagement-suite" + ) + SMS_MESSAGES_FEATURES_MESSAGE_REDACTION = ( + "sms-messages-features-message-redaction" + ) + SMS_MESSAGES_FEATURES_SENDERID = "sms-messages-features-senderid" + SMS_MPS = "sms-mps" + SMS_MPS_SHORTCODE = "sms-mps-shortcode" + SMS_MPS_TOLLFREE = "sms-mps-tollfree" + SMS_MPS_TOLLFREE_SETUP = "sms-mps-tollfree-setup" + SMS_NATIONAL_REGULATORY_PROTECTION = "sms-national-regulatory-protection" + SMS_OUTBOUND = "sms-outbound" + SMS_OUTBOUND_CONTENT_INSPECTION = "sms-outbound-content-inspection" + SMS_OUTBOUND_LONGCODE = "sms-outbound-longcode" + SMS_OUTBOUND_SHORTCODE = "sms-outbound-shortcode" + SMS_OUTBOUND_TOLLFREE = "sms-outbound-tollfree" + SMS_PUMPING_PROTECTION = "sms-pumping-protection" + SMS_PUMPING_RISK = "sms-pumping-risk" + SMSMESSAGES_BUCKET_ADJUSTMENTS = "smsmessages-bucket-adjustments" + SMSMESSAGES_OUTBOUND_DOMESTIC = "smsmessages-outbound-domestic" + SPEECH_RECOGNITION = "speech-recognition" + STUDIO_ENGAGEMENTS = "studio-engagements" + SYNC = "sync" + SYNC_ACTIONS = "sync-actions" + SYNC_ENDPOINT_HOURS = "sync-endpoint-hours" + SYNC_ENDPOINT_HOURS_ABOVE_DAILY_CAP = "sync-endpoint-hours-above-daily-cap" + TASKROUTER_TASKS = "taskrouter-tasks" + TOTALPRICE = "totalprice" + TRANSCRIPTIONS = "transcriptions" + TRUNKING_CPS = "trunking-cps" + TRUNKING_EMERGENCY_CALLS = "trunking-emergency-calls" + TRUNKING_ORIGINATION = "trunking-origination" + TRUNKING_ORIGINATION_LOCAL = "trunking-origination-local" + TRUNKING_ORIGINATION_MOBILE = "trunking-origination-mobile" + TRUNKING_ORIGINATION_TOLLFREE = "trunking-origination-tollfree" + TRUNKING_RECORDINGS = "trunking-recordings" + TRUNKING_SECURE = "trunking-secure" + TRUNKING_TERMINATION = "trunking-termination" + TTS_GOOGLE = "tts-google" + TURNMEGABYTES = "turnmegabytes" + TURNMEGABYTES_AUSTRALIA = "turnmegabytes-australia" + TURNMEGABYTES_BRASIL = "turnmegabytes-brasil" + TURNMEGABYTES_GERMANY = "turnmegabytes-germany" + TURNMEGABYTES_INDIA = "turnmegabytes-india" + TURNMEGABYTES_IRELAND = "turnmegabytes-ireland" + TURNMEGABYTES_JAPAN = "turnmegabytes-japan" + TURNMEGABYTES_SINGAPORE = "turnmegabytes-singapore" + TURNMEGABYTES_USEAST = "turnmegabytes-useast" + TURNMEGABYTES_USWEST = "turnmegabytes-uswest" + TWILIO_FOR_SALESFORCE = "twilio-for-salesforce" + TWILIO_FOR_SALESFORCE_LICENSES = "twilio-for-salesforce-licenses" + TWILIO_INTERCONNECT = "twilio-interconnect" + TWIML = "twiml" + USAGE_FLEX_VIDEO = "usage-flex-video" + USAGE_FUNCTIONS = "usage-functions" + USAGE_RCS_BASIC_MESSAGES_OUTBOUND = "usage-rcs-basic-messages-outbound" + USAGE_RCS_MESSAGES = "usage-rcs-messages" + USAGE_RCS_MESSAGES_INBOUND = "usage-rcs-messages-inbound" + USAGE_RCS_MESSAGING_CARRIER_FEES = "usage-rcs-messaging-carrier-fees" + USAGE_RCS_SINGLE_MESSAGES_OUTBOUND = "usage-rcs-single-messages-outbound" + VERIFY_PACKAGE_PLANS = "verify-package-plans" + VERIFY_PUSH = "verify-push" + VERIFY_SNA = "verify-sna" + VERIFY_TOTP = "verify-totp" + VERIFY_VOICE_SMS = "verify-voice-sms" + VERIFY_WHATSAPP_CONVERSATIONS_BUSINESS_INITIATED = ( + "verify-whatsapp-conversations-business-initiated" + ) + VIDEO_RECORDINGS = "video-recordings" + VIDEO_ROOMS_TURN_MEGABYTES = "video-rooms-turn-megabytes" + VIRTUAL_AGENT = "virtual-agent" + VOICE_INSIGHTS = "voice-insights" + VOICE_INSIGHTS_CLIENT_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-client-insights-on-demand-minute" + ) + VOICE_INSIGHTS_PTSN_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-ptsn-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_INTERFACE_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-interface-insights-on-demand-minute" + ) + VOICE_INSIGHTS_SIP_TRUNKING_INSIGHTS_ON_DEMAND_MINUTE = ( + "voice-insights-sip-trunking-insights-on-demand-minute" + ) + VOICE_INTELLIGENCE = "voice-intelligence" + VOICE_INTELLIGENCE_EIP_OPERATORS = "voice-intelligence-eip-operators" + VOICE_INTELLIGENCE_OPERATORS = "voice-intelligence-operators" + VOICE_INTELLIGENCE_TRANSCRIPTION = "voice-intelligence-transcription" + WDS = "wds" + WIRELESS = "wireless" + WIRELESS_DATA = "wireless-data" + WIRELESS_DATA_PAYG = "wireless-data-payg" + WIRELESS_DATA_PAYG_AFRICA = "wireless-data-payg-africa" + WIRELESS_DATA_PAYG_ASIA = "wireless-data-payg-asia" + WIRELESS_DATA_PAYG_CENTRALANDSOUTHAMERICA = ( + "wireless-data-payg-centralandsouthamerica" + ) + WIRELESS_DATA_PAYG_EUROPE = "wireless-data-payg-europe" + WIRELESS_DATA_PAYG_NORTHAMERICA = "wireless-data-payg-northamerica" + WIRELESS_DATA_PAYG_OCEANIA = "wireless-data-payg-oceania" + WIRELESS_DATA_QUOTA1 = "wireless-data-quota1" + WIRELESS_DATA_QUOTA1_AFRICA = "wireless-data-quota1-africa" + WIRELESS_DATA_QUOTA1_ASIA = "wireless-data-quota1-asia" + WIRELESS_DATA_QUOTA1_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota1-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA1_EUROPE = "wireless-data-quota1-europe" + WIRELESS_DATA_QUOTA1_NORTHAMERICA = "wireless-data-quota1-northamerica" + WIRELESS_DATA_QUOTA1_OCEANIA = "wireless-data-quota1-oceania" + WIRELESS_DATA_QUOTA10 = "wireless-data-quota10" + WIRELESS_DATA_QUOTA10_AFRICA = "wireless-data-quota10-africa" + WIRELESS_DATA_QUOTA10_ASIA = "wireless-data-quota10-asia" + WIRELESS_DATA_QUOTA10_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota10-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA10_EUROPE = "wireless-data-quota10-europe" + WIRELESS_DATA_QUOTA10_NORTHAMERICA = "wireless-data-quota10-northamerica" + WIRELESS_DATA_QUOTA10_OCEANIA = "wireless-data-quota10-oceania" + WIRELESS_DATA_QUOTA50 = "wireless-data-quota50" + WIRELESS_DATA_QUOTA50_AFRICA = "wireless-data-quota50-africa" + WIRELESS_DATA_QUOTA50_ASIA = "wireless-data-quota50-asia" + WIRELESS_DATA_QUOTA50_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quota50-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTA50_EUROPE = "wireless-data-quota50-europe" + WIRELESS_DATA_QUOTA50_NORTHAMERICA = "wireless-data-quota50-northamerica" + WIRELESS_DATA_QUOTA50_OCEANIA = "wireless-data-quota50-oceania" + WIRELESS_DATA_QUOTACUSTOM = "wireless-data-quotacustom" + WIRELESS_DATA_QUOTACUSTOM_AFRICA = "wireless-data-quotacustom-africa" + WIRELESS_DATA_QUOTACUSTOM_ASIA = "wireless-data-quotacustom-asia" + WIRELESS_DATA_QUOTACUSTOM_CENTRALANDSOUTHAMERICA = ( + "wireless-data-quotacustom-centralandsouthamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_EUROPE = "wireless-data-quotacustom-europe" + WIRELESS_DATA_QUOTACUSTOM_NORTHAMERICA = ( + "wireless-data-quotacustom-northamerica" + ) + WIRELESS_DATA_QUOTACUSTOM_OCEANIA = "wireless-data-quotacustom-oceania" + WIRELESS_MRC_PAYG = "wireless-mrc-payg" + WIRELESS_MRC_QUOTA1 = "wireless-mrc-quota1" + WIRELESS_MRC_QUOTA10 = "wireless-mrc-quota10" + WIRELESS_MRC_QUOTA50 = "wireless-mrc-quota50" + WIRELESS_MRC_QUOTACUSTOM = "wireless-mrc-quotacustom" + WIRELESS_ORDERS = "wireless-orders" + WIRELESS_ORDERS_ARTWORK = "wireless-orders-artwork" + WIRELESS_ORDERS_BULK = "wireless-orders-bulk" + WIRELESS_ORDERS_ESIM = "wireless-orders-esim" + WIRELESS_ORDERS_STARTER = "wireless-orders-starter" + WIRELESS_QUOTAS = "wireless-quotas" + WIRELESS_SMS_AFRICA = "wireless-sms-africa" + WIRELESS_SMS_ASIA = "wireless-sms-asia" + WIRELESS_SMS_CENTRALANDSOUTHAMERICA = "wireless-sms-centralandsouthamerica" + WIRELESS_SMS_EUROPE = "wireless-sms-europe" + WIRELESS_SMS_NORTHAMERICA = "wireless-sms-northamerica" + WIRELESS_SMS_OCEANIA = "wireless-sms-oceania" + WIRELESS_SUPER_SIM = "wireless-super-sim" + WIRELESS_SUPER_SIM_DATA = "wireless-super-sim-data" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA_USA = ( + "wireless-super-sim-data-north-america-usa" + ) + WIRELESS_SUPER_SIM_DATA_PAYG = "wireless-super-sim-data-payg" + WIRELESS_SUPER_SIM_DATA_PAYG_EUROPE = "wireless-super-sim-data-payg-europe" + WIRELESS_SUPER_SIM_DATA_PAYG_NORTH_AMERICA = ( + "wireless-super-sim-data-payg-north-america" + ) + WIRELESS_SUPER_SIM_HARDWARE = "wireless-super-sim-hardware" + WIRELESS_SUPER_SIM_HARDWARE_BULK = "wireless-super-sim-hardware-bulk" + WIRELESS_SUPER_SIM_SMSCOMMANDS = "wireless-super-sim-smscommands" + WIRELESS_SUPER_SIM_SMSCOMMANDS_AFRICA = "wireless-super-sim-smscommands-africa" + WIRELESS_SUPER_SIM_SMSCOMMANDS_ASIA = "wireless-super-sim-smscommands-asia" + WIRELESS_SUPER_SIM_SMSCOMMANDS_CENT_AND_SOUTH_AMERICA = ( + "wireless-super-sim-smscommands-cent-and-south-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_EUROPE = "wireless-super-sim-smscommands-europe" + WIRELESS_SUPER_SIM_SMSCOMMANDS_NORTH_AMERICA = ( + "wireless-super-sim-smscommands-north-america" + ) + WIRELESS_SUPER_SIM_SMSCOMMANDS_OCEANIA = ( + "wireless-super-sim-smscommands-oceania" + ) + WIRELESS_SUPER_SIM_SUBSCRIPTION = "wireless-super-sim-subscription" + WIRELESS_SUPER_SIM_SUBSCRIPTION_PAYG = "wireless-super-sim-subscription-payg" + WIRELESS_USAGE = "wireless-usage" + WIRELESS_USAGE_COMMANDS = "wireless-usage-commands" + WIRELESS_USAGE_COMMANDS_AFRICA = "wireless-usage-commands-africa" + WIRELESS_USAGE_COMMANDS_ASIA = "wireless-usage-commands-asia" + WIRELESS_USAGE_COMMANDS_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-commands-centralandsouthamerica" + ) + WIRELESS_USAGE_COMMANDS_EUROPE = "wireless-usage-commands-europe" + WIRELESS_USAGE_COMMANDS_HOME = "wireless-usage-commands-home" + WIRELESS_USAGE_COMMANDS_NORTHAMERICA = "wireless-usage-commands-northamerica" + WIRELESS_USAGE_COMMANDS_OCEANIA = "wireless-usage-commands-oceania" + WIRELESS_USAGE_COMMANDS_ROAMING = "wireless-usage-commands-roaming" + WIRELESS_USAGE_DATA = "wireless-usage-data" + WIRELESS_USAGE_DATA_AFRICA = "wireless-usage-data-africa" + WIRELESS_USAGE_DATA_ASIA = "wireless-usage-data-asia" + WIRELESS_USAGE_DATA_CENTRALANDSOUTHAMERICA = ( + "wireless-usage-data-centralandsouthamerica" + ) + WIRELESS_USAGE_DATA_CUSTOM_ADDITIONALMB = ( + "wireless-usage-data-custom-additionalmb" + ) + WIRELESS_USAGE_DATA_CUSTOM_FIRST5MB = "wireless-usage-data-custom-first5mb" + WIRELESS_USAGE_DATA_DOMESTIC_ROAMING = "wireless-usage-data-domestic-roaming" + WIRELESS_USAGE_DATA_EUROPE = "wireless-usage-data-europe" + WIRELESS_USAGE_DATA_INDIVIDUAL_ADDITIONALGB = ( + "wireless-usage-data-individual-additionalgb" + ) + WIRELESS_USAGE_DATA_INDIVIDUAL_FIRSTGB = ( + "wireless-usage-data-individual-firstgb" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_CANADA = ( + "wireless-usage-data-international-roaming-canada" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_INDIA = ( + "wireless-usage-data-international-roaming-india" + ) + WIRELESS_USAGE_DATA_INTERNATIONAL_ROAMING_MEXICO = ( + "wireless-usage-data-international-roaming-mexico" + ) + WIRELESS_USAGE_DATA_NORTHAMERICA = "wireless-usage-data-northamerica" + WIRELESS_USAGE_DATA_OCEANIA = "wireless-usage-data-oceania" + WIRELESS_USAGE_DATA_POOLED = "wireless-usage-data-pooled" + WIRELESS_USAGE_DATA_POOLED_DOWNLINK = "wireless-usage-data-pooled-downlink" + WIRELESS_USAGE_DATA_POOLED_UPLINK = "wireless-usage-data-pooled-uplink" + WIRELESS_USAGE_MRC = "wireless-usage-mrc" + WIRELESS_USAGE_MRC_CUSTOM = "wireless-usage-mrc-custom" + WIRELESS_USAGE_MRC_INDIVIDUAL = "wireless-usage-mrc-individual" + WIRELESS_USAGE_MRC_POOLED = "wireless-usage-mrc-pooled" + WIRELESS_USAGE_MRC_SUSPENDED = "wireless-usage-mrc-suspended" + WIRELESS_USAGE_SMS = "wireless-usage-sms" + WIRELESS_USAGE_VOICE = "wireless-usage-voice" + A2P_FAST_TRACK_ONBOARDING = "a2p-fast-track-onboarding" + ADVISORY_SERVICES = "advisory-services" + ADVISORY_SERVICES_BILLED = "advisory-services-billed" + ADVISORY_SERVICES_CALL_TRACKING = "advisory-services-call-tracking" + ADVISORY_SERVICES_DATA_SERVICES = "advisory-services-data-services" + ADVISORY_SERVICES_EXPENSES = "advisory-services-expenses" + ADVISORY_SERVICES_SIP_TRUNKING = "advisory-services-sip-trunking" + ASSETS_REQUESTS = "assets-requests" + AUDIENCE_MINUTES_VIDEO = "audience-minutes-video" + AUTHY_BUCKET_ADJUSTMENT = "authy-bucket-adjustment" + AUTHY_SOFTWARE = "authy-software" + CALLERIDLOOKUPS_API = "calleridlookups-api" + CALLERIDLOOKUPS_PROGRAMMABLEVOICE = "calleridlookups-programmablevoice" + CALLERIDLOOKUPS_TRUNKING = "calleridlookups-trunking" + CALLS_TRUNKING_INBOUND_TOLLFREE_LOCAL = "calls-trunking-inbound-tollfree-local" + CALLS_TRUNKING_INBOUND_TOLLFREE_MOBILE = ( + "calls-trunking-inbound-tollfree-mobile" + ) + CHANNELS_WHATSAPP_CONVERSATION_FREE_1 = "channels-whatsapp-conversation-free-1" + CONFERENCE = "conference" + CONVERSATIONAL_INSIGHTS = "conversational-insights" + CONVERSATIONAL_INSIGHTS_MESSAGES = "conversational-insights-messages" + CONVERSATIONAL_INSIGHTS_VOICE_MINUTES = "conversational-insights-voice-minutes" + DEMO = "demo" + DEMO_UC_SCRIPT_TEST = "demo-uc-script-test" + ELASTIC_SIP_TRUNKING = "elastic-sip-trunking" + ELASTIC_SIP_TRUNKING_CALL_TRANSFERS = "elastic-sip-trunking-call-transfers" + ENTERPRISE_HIPPA = "enterprise-hippa" + FLEX_NAMED_USERS = "flex-named-users" + FLEX_SPINSCI = "flex-spinsci" + FLEX_USERS_1 = "flex-users-1" + FLEX_WFO_PREMIUM_SPEECH_ANALYTICS = "flex-wfo-premium-speech-analytics" + FLEX_XCELERATE = "flex-xcelerate" + FUNCTIONS_ROLLUP = "functions-rollup" + IMP_V1_USAGE = "imp-v1-usage" + IP_MESSAGING_ADDONS = "ip-messaging-addons" + IVR = "ivr" + IVR_CONVERSATIONAL = "ivr-conversational" + IVR_DTMF = "ivr-dtmf" + IVR_VIRTUALAGENT = "ivr-virtualagent" + LIVE = "live" + LIVE_MEDIA_RECORDING_MINUTES = "live-media-recording-minutes" + LONGCODE_MPS = "longcode-mps" + MARKETPLACE_ANALYTICS_ADDONS = "marketplace-analytics-addons" + MARKETPLACE_ISV_ADDONS = "marketplace-isv-addons" + MARKETPLACE_MESSAGING_ADDONS = "marketplace-messaging-addons" + MARKETPLACE_PHONENUMBERS_ADDONS = "marketplace-phonenumbers-addons" + MARKETPLACE_RECORDING_ADDONS = "marketplace-recording-addons" + MARKETPLACE_VIRTUALAGENT_ADDONS = "marketplace-virtualagent-addons" + MARKETPLAY_PAY_ADDONS_SHUTTLE_PAY_CONNECTOR_1 = ( + "marketplay-pay-addons-shuttle-pay-connector-1" + ) + MARKETPLAY_PAY_ADDONS_STRIPE_PAY_CONNECTOR = ( + "marketplay-pay-addons-stripe-pay-connector" + ) + MMS_INBOUND_LONGCODE_CANADA = "mms-inbound-longcode-canada" + MMS_INBOUND_LONGCODE_UNITEDSTATES = "mms-inbound-longcode-unitedstates" + MMS_OUTBOUND_LONGCODE_CANADA = "mms-outbound-longcode-canada" + MMS_OUTBOUND_LONGCODE_UNITEDSTATES = "mms-outbound-longcode-unitedstates" + MMS_OUTBOUND_TOLL_FREE = "mms-outbound-toll-free" + NOTIFY_CHATAPPSANDOTHERCHANNELS = "notify-chatappsandotherchannels" + NOTIFY_NOTIFYSERVICES = "notify-notifyservices" + NOTIFY_PUSHNOTIFICATIONS = "notify-pushnotifications" + PAYMENT_GATEWAY_CONNECTORS = "payment-gateway-connectors" + PAYMENT_SOLUTIONS = "payment-solutions" + PCHAT_BUCKET_ADJUSTMENT = "pchat-bucket-adjustment" + PHONENUMBERS_NUMBERS = "phonenumbers-numbers" + PROG_VOICE_CLIENT_ANDROID = "prog-voice-client-android" + PROG_VOICE_CLIENT_ANDROID_INBOUND = "prog-voice-client-android-inbound" + PROG_VOICE_CLIENT_ANDROID_OUTBOUND = "prog-voice-client-android-outbound" + PROG_VOICE_CLIENT_IOS = "prog-voice-client-ios" + PROG_VOICE_CLIENT_IOS_INBOUND = "prog-voice-client-ios-inbound" + PROG_VOICE_CLIENT_IOS_OUTBOUND = "prog-voice-client-ios-outbound" + PROG_VOICE_CLIENT_SDK = "prog-voice-client-sdk" + PROG_VOICE_CLIENT_WEB = "prog-voice-client-web" + PROG_VOICE_CLIENT_WEB_INBOUND = "prog-voice-client-web-inbound" + PROG_VOICE_CLIENT_WEB_OUTBOUND = "prog-voice-client-web-outbound" + PROGRAMMABLEVOICECONNECTIVITY_MEDIA_STREAMS = ( + "programmablevoiceconnectivity-media-streams" + ) + PSTNCONNECTIVITY_BYOC = "pstnconnectivity-byoc" + PSTNCONNECTIVITY_EMERGENCY = "pstnconnectivity-emergency" + PSTNCONNECTIVITY_MINUTES = "pstnconnectivity-minutes" + PSTNCONNECTIVITY_MINUTES_1 = "pstnconnectivity-minutes-1" + PSTNCONNECTIVITY_MINUTESINBOUNDLOCAL = "pstnconnectivity-minutesinboundlocal" + PSTNCONNECTIVITY_MINUTESINBOUNDMOBILE = "pstnconnectivity-minutesinboundmobile" + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREE = ( + "pstnconnectivity-minutesinboundtollfree" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREELOCAL = ( + "pstnconnectivity-minutesinboundtollfreelocal" + ) + PSTNCONNECTIVITY_MINUTESINBOUNDTOLLFREEMOBILE = ( + "pstnconnectivity-minutesinboundtollfreemobile" + ) + PV_ROOM_HOURS = "pv-room-hours" + PV_ROOM_SIMULTANEOUS_PARTICIPANT_CONNECTIONS = ( + "pv-room-simultaneous-participant-connections" + ) + PVIDEO_ROOM_HOURS_AU1 = "pvideo-room-hours-au1" + PVIDEO_ROOM_HOURS_BR1 = "pvideo-room-hours-br1" + PVIDEO_ROOM_HOURS_IE1 = "pvideo-room-hours-ie1" + PVIDEO_ROOM_HOURS_JP1 = "pvideo-room-hours-jp1" + PVIDEO_ROOM_HOURS_SG1 = "pvideo-room-hours-sg1" + PVIDEO_ROOM_HOURS_US1 = "pvideo-room-hours-us1" + PVIDEO_ROOM_HOURS_US2 = "pvideo-room-hours-us2" + RECORDINGS_ENCRYPTED = "recordings-encrypted" + SHORT_CODE_SETUP_FEES = "short-code-setup-fees" + SHORTCODES_MESSAGES_INBOUND = "shortcodes-messages-inbound" + SHORTCODES_MESSAGES_OUTBOUND = "shortcodes-messages-outbound" + SMS_MESSAGES_REGISTRATIONFEES = "sms-messages-registrationfees" + SMS_MMS_PENALTY_FEES = "sms-mms-penalty-fees" + SMS_MMS_PENALTY_FEES_1 = "sms-mms-penalty-fees-1" + SMS_PUMPING_PROTECTION_NON_USCA = "sms-pumping-protection-non-usca" + SMS_PUMPING_PROTECTION_USCA = "sms-pumping-protection-usca" + STUDIO = "studio" + STUDIO_MONTHLY_FEES = "studio-monthly-fees" + SUPERSIM = "supersim" + TASK_ROUTER = "task-router" + TASK_ROUTER_WORKERS = "task-router-workers" + TEST_QUOTA_BUCKETS = "test-quota-buckets" + TEST_UC_SCRIPT_1 = "test-uc-script-1" + TEST_UC_SCRIPT_DEMO_2 = "test-uc-script-demo-2" + TEXT_TO_SPEECH = "text-to-speech" + TME = "tme" + TTS_BASIC = "tts-basic" + TWILIO_EDITIONS = "twilio-editions" + TWILIO_INTERCONNECT_CALIFORNIA = "twilio-interconnect-california" + TWILIO_INTERCONNECT_CALIFORNIA_MONTHLY = ( + "twilio-interconnect-california-monthly" + ) + TWILIO_INTERCONNECT_CALIFORNIA_SETUP = "twilio-interconnect-california-setup" + TWILIO_INTERCONNECT_FRANKFURT = "twilio-interconnect-frankfurt" + TWILIO_INTERCONNECT_FRANKFURT_MO = "twilio-interconnect-frankfurt-mo" + TWILIO_INTERCONNECT_FRANKFURT_SETUP = "twilio-interconnect-frankfurt-setup" + TWILIO_INTERCONNECT_LONDON = "twilio-interconnect-london" + TWILIO_INTERCONNECT_LONDON_MO = "twilio-interconnect-london-mo" + TWILIO_INTERCONNECT_LONDON_SETUP = "twilio-interconnect-london-setup" + TWILIO_INTERCONNECT_SAO_PAULO = "twilio-interconnect-sao-paulo" + TWILIO_INTERCONNECT_SAO_PAULO_MONTHLY = "twilio-interconnect-sao-paulo-monthly" + TWILIO_INTERCONNECT_SAO_PAULO_SETUP = "twilio-interconnect-sao-paulo-setup" + TWILIO_INTERCONNECT_SINGAPORE = "twilio-interconnect-singapore" + TWILIO_INTERCONNECT_SINGAPORE_MO = "twilio-interconnect-singapore-mo" + TWILIO_INTERCONNECT_SINGAPORE_SETUP = "twilio-interconnect-singapore-setup" + TWILIO_INTERCONNECT_SYDNEY = "twilio-interconnect-sydney" + TWILIO_INTERCONNECT_SYDNEY_MO = "twilio-interconnect-sydney-mo" + TWILIO_INTERCONNECT_SYDNEY_SETUP = "twilio-interconnect-sydney-setup" + TWILIO_INTERCONNECT_TOKYO = "twilio-interconnect-tokyo" + TWILIO_INTERCONNECT_TOKYO_MO = "twilio-interconnect-tokyo-mo" + TWILIO_INTERCONNECT_TOKYO_SETUP = "twilio-interconnect-tokyo-setup" + TWILIO_INTERCONNECT_VA = "twilio-interconnect-va" + TWILIO_INTERCONNECT_VA_MO = "twilio-interconnect-va-mo" + TWILIO_INTERCONNECT_VA_SETUP = "twilio-interconnect-va-setup" + TWIML_VERBS = "twiml-verbs" + TWIML_VERBS_SAY = "twiml-verbs-say" + USAGE_PROGRAMMABLE_MESSAGING_ENGAGEMENT_SUITE = ( + "usage-programmable-messaging-engagement-suite" + ) + USAGE_PROGRAMMABLE_MESSAGING_FEES_SERVICES = ( + "usage-programmable-messaging-fees-services" + ) + VERIFY_OUTBOUND_EMAIL = "verify-outbound-email" + VERIFY_PACKAGED_PLANS = "verify-packaged-plans" + VERIFY_SILENT_NETWORK_AUTH = "verify-silent-network-auth" + VERIFY_VOICE_AND_SMS = "verify-voice-and-sms" + VOICE_INSIGHTS_CLIENT_INSIGHTS_MONTHY_COMMIT = ( + "voice-insights-client-insights-monthy-commit" + ) + WIRELESS_DATA_PAYG_ASIA_AFG = "wireless-data-payg-asia-afg" + WIRELESS_MULTI_IMSI_SIM_COMMANDS = "wireless-multi-imsi-sim-commands" + WIRELESS_MULTI_IMSI_SIM_COMMANDS_USA = "wireless-multi-imsi-sim-commands-usa" + WIRELESS_MULTI_IMSI_SIM_DATA = "wireless-multi-imsi-sim-data" + WIRELESS_MULTI_IMSI_SIM_DATA_EU28 = "wireless-multi-imsi-sim-data-eu28" + WIRELESS_MULTI_IMSI_SIM_DATA_USA = "wireless-multi-imsi-sim-data-usa" + WIRELESS_MULTI_IMSI_SIM_MONTHLY_FEES = "wireless-multi-imsi-sim-monthly-fees" + WIRELESS_MULTI_IMSI_SIM_USAGE = "wireless-multi-imsi-sim-usage" + WIRELESS_SUPER_SIM_DATA_NORTH_AMERICA = "wireless-super-sim-data-north-america" + WIRELESS_SUPER_SIM_USAGE = "wireless-super-sim-usage" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the trigger monitors. + :ivar api_version: The API version used to create the resource. + :ivar callback_method: The HTTP method we use to call `callback_url`. Can be: `GET` or `POST`. + :ivar callback_url: The URL we call using the `callback_method` when the trigger fires. + :ivar current_value: The current value of the field the trigger is watching. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_fired: The date and time in GMT that the trigger was last fired specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the trigger. + :ivar recurring: + :ivar sid: The unique string that that we created to identify the UsageTrigger resource. + :ivar trigger_by: + :ivar trigger_value: The value at which the trigger will fire. Must be a positive, numeric value. + :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. + :ivar usage_category: + :ivar usage_record_uri: The URI of the [UsageRecord](https://www.twilio.com/docs/usage/api/usage-record) resource this trigger watches, relative to `https://api.twilio.com`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.api_version: Optional[str] = payload.get("api_version") + self.callback_method: Optional[str] = payload.get("callback_method") + self.callback_url: Optional[str] = payload.get("callback_url") + self.current_value: Optional[str] = payload.get("current_value") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_fired: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_fired") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.recurring: Optional["TriggerInstance.Recurring"] = payload.get("recurring") + self.sid: Optional[str] = payload.get("sid") + self.trigger_by: Optional["TriggerInstance.TriggerField"] = payload.get( + "trigger_by" + ) + self.trigger_value: Optional[str] = payload.get("trigger_value") + self.uri: Optional[str] = payload.get("uri") + self.usage_category: Optional["TriggerInstance.UsageCategory"] = payload.get( + "usage_category" + ) + self.usage_record_uri: Optional[str] = payload.get("usage_record_uri") + + self._solution = { + "account_sid": account_sid, + "sid": sid or self.sid, + } + self._context: Optional[TriggerContext] = None + + @property + def _proxy(self) -> "TriggerContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TriggerContext for this TriggerInstance + """ + if self._context is None: + self._context = TriggerContext( + self._version, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TriggerInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TriggerInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TriggerInstance": + """ + Fetch the TriggerInstance + + + :returns: The fetched TriggerInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TriggerInstance": + """ + Asynchronous coroutine to fetch the TriggerInstance + + + :returns: The fetched TriggerInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "TriggerInstance": + """ + Update the TriggerInstance + + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. + :param callback_url: The URL we should call using `callback_method` when the trigger fires. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated TriggerInstance + """ + return self._proxy.update( + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + ) + + async def update_async( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "TriggerInstance": + """ + Asynchronous coroutine to update the TriggerInstance + + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. + :param callback_url: The URL we should call using `callback_method` when the trigger fires. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated TriggerInstance + """ + return await self._proxy.update_async( + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.TriggerInstance {}>".format(context) + + +class TriggerContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, sid: str): + """ + Initialize the TriggerContext + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageTrigger resources to update. + :param sid: The Twilio-provided string that uniquely identifies the UsageTrigger resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Triggers/{sid}.json".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the TriggerInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TriggerInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TriggerInstance: + """ + Fetch the TriggerInstance + + + :returns: The fetched TriggerInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TriggerInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TriggerInstance: + """ + Asynchronous coroutine to fetch the TriggerInstance + + + :returns: The fetched TriggerInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TriggerInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> TriggerInstance: + """ + Update the TriggerInstance + + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. + :param callback_url: The URL we should call using `callback_method` when the trigger fires. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated TriggerInstance + """ + + data = values.of( + { + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TriggerInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> TriggerInstance: + """ + Asynchronous coroutine to update the TriggerInstance + + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. + :param callback_url: The URL we should call using `callback_method` when the trigger fires. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The updated TriggerInstance + """ + + data = values.of( + { + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TriggerInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.TriggerContext {}>".format(context) + + +class TriggerPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TriggerInstance: + """ + Build an instance of TriggerInstance + + :param payload: Payload response from the API + """ + return TriggerInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.TriggerPage>" + + +class TriggerList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the TriggerList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageTrigger resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/Usage/Triggers.json".format( + **self._solution + ) + + def create( + self, + callback_url: str, + trigger_value: str, + usage_category: "TriggerInstance.UsageCategory", + callback_method: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + ) -> TriggerInstance: + """ + Create the TriggerInstance + + :param callback_url: The URL we should call using `callback_method` when the trigger fires. + :param trigger_value: The usage value at which the trigger should fire. For convenience, you can use an offset value such as `+30` to specify a trigger_value that is 30 units more than the current usage value. Be sure to urlencode a `+` as `%2B`. + :param usage_category: + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param recurring: + :param trigger_by: + + :returns: The created TriggerInstance + """ + + data = values.of( + { + "CallbackUrl": callback_url, + "TriggerValue": trigger_value, + "UsageCategory": usage_category, + "CallbackMethod": callback_method, + "FriendlyName": friendly_name, + "Recurring": recurring, + "TriggerBy": trigger_by, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TriggerInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + callback_url: str, + trigger_value: str, + usage_category: "TriggerInstance.UsageCategory", + callback_method: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + ) -> TriggerInstance: + """ + Asynchronously create the TriggerInstance + + :param callback_url: The URL we should call using `callback_method` when the trigger fires. + :param trigger_value: The usage value at which the trigger should fire. For convenience, you can use an offset value such as `+30` to specify a trigger_value that is 30 units more than the current usage value. Be sure to urlencode a `+` as `%2B`. + :param usage_category: + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is `POST`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param recurring: + :param trigger_by: + + :returns: The created TriggerInstance + """ + + data = values.of( + { + "CallbackUrl": callback_url, + "TriggerValue": trigger_value, + "UsageCategory": usage_category, + "CallbackMethod": callback_method, + "FriendlyName": friendly_name, + "Recurring": recurring, + "TriggerBy": trigger_by, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TriggerInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def stream( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TriggerInstance]: + """ + Streams TriggerInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "TriggerInstance.Recurring" recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param "TriggerInstance.TriggerField" trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param "TriggerInstance.UsageCategory" usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + recurring=recurring, + trigger_by=trigger_by, + usage_category=usage_category, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TriggerInstance]: + """ + Asynchronously streams TriggerInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "TriggerInstance.Recurring" recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param "TriggerInstance.TriggerField" trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param "TriggerInstance.UsageCategory" usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + recurring=recurring, + trigger_by=trigger_by, + usage_category=usage_category, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TriggerInstance]: + """ + Lists TriggerInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "TriggerInstance.Recurring" recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param "TriggerInstance.TriggerField" trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param "TriggerInstance.UsageCategory" usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + recurring=recurring, + trigger_by=trigger_by, + usage_category=usage_category, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TriggerInstance]: + """ + Asynchronously lists TriggerInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "TriggerInstance.Recurring" recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param "TriggerInstance.TriggerField" trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param "TriggerInstance.UsageCategory" usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + recurring=recurring, + trigger_by=trigger_by, + usage_category=usage_category, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TriggerPage: + """ + Retrieve a single page of TriggerInstance records from the API. + Request is executed immediately + + :param recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TriggerInstance + """ + data = values.of( + { + "Recurring": recurring, + "TriggerBy": trigger_by, + "UsageCategory": usage_category, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TriggerPage(self._version, response, self._solution) + + async def page_async( + self, + recurring: Union["TriggerInstance.Recurring", object] = values.unset, + trigger_by: Union["TriggerInstance.TriggerField", object] = values.unset, + usage_category: Union["TriggerInstance.UsageCategory", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TriggerPage: + """ + Asynchronously retrieve a single page of TriggerInstance records from the API. + Request is executed immediately + + :param recurring: The frequency of recurring UsageTriggers to read. Can be: `daily`, `monthly`, or `yearly` to read recurring UsageTriggers. An empty value or a value of `alltime` reads non-recurring UsageTriggers. + :param trigger_by: The trigger field of the UsageTriggers to read. Can be: `count`, `usage`, or `price` as described in the [UsageRecords documentation](https://www.twilio.com/docs/usage/api/usage-record#usage-count-price). + :param usage_category: The usage category of the UsageTriggers to read. Must be a supported [usage categories](https://www.twilio.com/docs/usage/api/usage-record#usage-categories). + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TriggerInstance + """ + data = values.of( + { + "Recurring": recurring, + "TriggerBy": trigger_by, + "UsageCategory": usage_category, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TriggerPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TriggerPage: + """ + Retrieve a specific page of TriggerInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TriggerInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TriggerPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TriggerPage: + """ + Asynchronously retrieve a specific page of TriggerInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TriggerInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TriggerPage(self._version, response, self._solution) + + def get(self, sid: str) -> TriggerContext: + """ + Constructs a TriggerContext + + :param sid: The Twilio-provided string that uniquely identifies the UsageTrigger resource to update. + """ + return TriggerContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __call__(self, sid: str) -> TriggerContext: + """ + Constructs a TriggerContext + + :param sid: The Twilio-provided string that uniquely identifies the UsageTrigger resource to update. + """ + return TriggerContext( + self._version, account_sid=self._solution["account_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.TriggerList>" diff --git a/twilio/rest/api/v2010/account/validation_request.py b/twilio/rest/api/v2010/account/validation_request.py new file mode 100644 index 0000000000..d92f840e68 --- /dev/null +++ b/twilio/rest/api/v2010/account/validation_request.py @@ -0,0 +1,173 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ValidationRequestInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for the Caller ID. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Caller ID is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar phone_number: The phone number to verify in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar validation_code: The 6 digit validation code that someone must enter to validate the Caller ID when `phone_number` is called. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.phone_number: Optional[str] = payload.get("phone_number") + self.validation_code: Optional[str] = payload.get("validation_code") + + self._solution = { + "account_sid": account_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Api.V2010.ValidationRequestInstance {}>".format(context) + + +class ValidationRequestList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the ValidationRequestList + + :param version: Version that contains the resource + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for the new caller ID resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + } + self._uri = "/Accounts/{account_sid}/OutgoingCallerIds.json".format( + **self._solution + ) + + def create( + self, + phone_number: str, + friendly_name: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + extension: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> ValidationRequestInstance: + """ + Create the ValidationRequestInstance + + :param phone_number: The phone number to verify in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :param friendly_name: A descriptive string that you create to describe the new caller ID resource. It can be up to 64 characters long. The default value is a formatted version of the phone number. + :param call_delay: The number of seconds to delay before initiating the verification call. Can be an integer between `0` and `60`, inclusive. The default is `0`. + :param extension: The digits to dial after connecting the verification call. + :param status_callback: The URL we should call using the `status_callback_method` to send status information about the verification process to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`, and the default is `POST`. + + :returns: The created ValidationRequestInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "FriendlyName": friendly_name, + "CallDelay": call_delay, + "Extension": extension, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ValidationRequestInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + async def create_async( + self, + phone_number: str, + friendly_name: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + extension: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> ValidationRequestInstance: + """ + Asynchronously create the ValidationRequestInstance + + :param phone_number: The phone number to verify in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :param friendly_name: A descriptive string that you create to describe the new caller ID resource. It can be up to 64 characters long. The default value is a formatted version of the phone number. + :param call_delay: The number of seconds to delay before initiating the verification call. Can be an integer between `0` and `60`, inclusive. The default is `0`. + :param extension: The digits to dial after connecting the verification call. + :param status_callback: The URL we should call using the `status_callback_method` to send status information about the verification process to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `GET` or `POST`, and the default is `POST`. + + :returns: The created ValidationRequestInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "FriendlyName": friendly_name, + "CallDelay": call_delay, + "Extension": extension, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ValidationRequestInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Api.V2010.ValidationRequestList>" diff --git a/twilio/rest/assistants/AssistantsBase.py b/twilio/rest/assistants/AssistantsBase.py new file mode 100644 index 0000000000..a9c9e9afcd --- /dev/null +++ b/twilio/rest/assistants/AssistantsBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.assistants.v1 import V1 + + +class AssistantsBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Assistants Domain + + :returns: Domain for Assistants + """ + super().__init__(twilio, "https://assistants.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Assistants + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Assistants>" diff --git a/twilio/rest/assistants/__init__.py b/twilio/rest/assistants/__init__.py new file mode 100644 index 0000000000..889daf9d29 --- /dev/null +++ b/twilio/rest/assistants/__init__.py @@ -0,0 +1,56 @@ +from warnings import warn + +from twilio.rest.assistants.AssistantsBase import AssistantsBase +from twilio.rest.assistants.v1.assistant import AssistantList +from twilio.rest.assistants.v1.knowledge import KnowledgeList +from twilio.rest.assistants.v1.policy import PolicyList +from twilio.rest.assistants.v1.session import SessionList +from twilio.rest.assistants.v1.tool import ToolList + + +class Assistants(AssistantsBase): + + @property + def assistants(self) -> AssistantList: + warn( + "assistants is deprecated. Use v1.assistants instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.assistants + + @property + def knowledge(self) -> KnowledgeList: + warn( + "knowledge is deprecated. Use v1.knowledge instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.knowledge + + @property + def policies(self) -> PolicyList: + warn( + "policies is deprecated. Use v1.policies instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.policies + + @property + def sessions(self) -> SessionList: + warn( + "sessions is deprecated. Use v1.sessions instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.sessions + + @property + def tools(self) -> ToolList: + warn( + "tools is deprecated. Use v1.tools instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.tools diff --git a/twilio/rest/assistants/v1/__init__.py b/twilio/rest/assistants/v1/__init__.py new file mode 100644 index 0000000000..546ad14554 --- /dev/null +++ b/twilio/rest/assistants/v1/__init__.py @@ -0,0 +1,75 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.assistants.v1.assistant import AssistantList +from twilio.rest.assistants.v1.knowledge import KnowledgeList +from twilio.rest.assistants.v1.policy import PolicyList +from twilio.rest.assistants.v1.session import SessionList +from twilio.rest.assistants.v1.tool import ToolList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Assistants + + :param domain: The Twilio.assistants domain + """ + super().__init__(domain, "v1") + self._assistants: Optional[AssistantList] = None + self._knowledge: Optional[KnowledgeList] = None + self._policies: Optional[PolicyList] = None + self._sessions: Optional[SessionList] = None + self._tools: Optional[ToolList] = None + + @property + def assistants(self) -> AssistantList: + if self._assistants is None: + self._assistants = AssistantList(self) + return self._assistants + + @property + def knowledge(self) -> KnowledgeList: + if self._knowledge is None: + self._knowledge = KnowledgeList(self) + return self._knowledge + + @property + def policies(self) -> PolicyList: + if self._policies is None: + self._policies = PolicyList(self) + return self._policies + + @property + def sessions(self) -> SessionList: + if self._sessions is None: + self._sessions = SessionList(self) + return self._sessions + + @property + def tools(self) -> ToolList: + if self._tools is None: + self._tools = ToolList(self) + return self._tools + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1>" diff --git a/twilio/rest/assistants/v1/assistant/__init__.py b/twilio/rest/assistants/v1/assistant/__init__.py new file mode 100644 index 0000000000..8ab22a5dcf --- /dev/null +++ b/twilio/rest/assistants/v1/assistant/__init__.py @@ -0,0 +1,1036 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.assistants.v1.assistant.assistants_knowledge import ( + AssistantsKnowledgeList, +) +from twilio.rest.assistants.v1.assistant.assistants_tool import AssistantsToolList +from twilio.rest.assistants.v1.assistant.feedback import FeedbackList +from twilio.rest.assistants.v1.assistant.message import MessageList + + +class AssistantInstance(InstanceResource): + + class AssistantsV1ServiceCreateAssistantRequest(object): + """ + :ivar customer_ai: + :ivar name: The name of the assistant. + :ivar owner: The owner/company of the assistant. + :ivar personality_prompt: The personality prompt to be used for assistant. + :ivar segment_credential: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_ai: Optional[AssistantList.AssistantsV1ServiceCustomerAi] = ( + payload.get("customer_ai") + ) + self.name: Optional[str] = payload.get("name") + self.owner: Optional[str] = payload.get("owner") + self.personality_prompt: Optional[str] = payload.get("personality_prompt") + self.segment_credential: Optional[ + AssistantList.AssistantsV1ServiceSegmentCredential + ] = payload.get("segment_credential") + + def to_dict(self): + return { + "customer_ai": ( + self.customer_ai.to_dict() if self.customer_ai is not None else None + ), + "name": self.name, + "owner": self.owner, + "personality_prompt": self.personality_prompt, + "segment_credential": ( + self.segment_credential.to_dict() + if self.segment_credential is not None + else None + ), + } + + class AssistantsV1ServiceCustomerAi(object): + """ + :ivar perception_engine_enabled: True if the perception engine is enabled. + :ivar personalization_engine_enabled: True if the personalization engine is enabled. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.perception_engine_enabled: Optional[bool] = payload.get( + "perception_engine_enabled" + ) + self.personalization_engine_enabled: Optional[bool] = payload.get( + "personalization_engine_enabled" + ) + + def to_dict(self): + return { + "perception_engine_enabled": self.perception_engine_enabled, + "personalization_engine_enabled": self.personalization_engine_enabled, + } + + class AssistantsV1ServiceSegmentCredential(object): + """ + :ivar profile_api_key: The profile API key. + :ivar space_id: The space ID. + :ivar write_key: The write key. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.profile_api_key: Optional[str] = payload.get("profile_api_key") + self.space_id: Optional[str] = payload.get("space_id") + self.write_key: Optional[str] = payload.get("write_key") + + def to_dict(self): + return { + "profile_api_key": self.profile_api_key, + "space_id": self.space_id, + "write_key": self.write_key, + } + + class AssistantsV1ServiceUpdateAssistantRequest(object): + """ + :ivar customer_ai: + :ivar name: The name of the assistant. + :ivar owner: The owner/company of the assistant. + :ivar personality_prompt: The personality prompt to be used for assistant. + :ivar segment_credential: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_ai: Optional[AssistantList.AssistantsV1ServiceCustomerAi] = ( + payload.get("customer_ai") + ) + self.name: Optional[str] = payload.get("name") + self.owner: Optional[str] = payload.get("owner") + self.personality_prompt: Optional[str] = payload.get("personality_prompt") + self.segment_credential: Optional[ + AssistantList.AssistantsV1ServiceSegmentCredential + ] = payload.get("segment_credential") + + def to_dict(self): + return { + "customer_ai": ( + self.customer_ai.to_dict() if self.customer_ai is not None else None + ), + "name": self.name, + "owner": self.owner, + "personality_prompt": self.personality_prompt, + "segment_credential": ( + self.segment_credential.to_dict() + if self.segment_credential is not None + else None + ), + } + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Assistant resource. + :ivar customer_ai: The Personalization and Perception Engine settings. + :ivar id: The Assistant ID. + :ivar model: The default model used by the assistant. + :ivar name: The name of the assistant. + :ivar owner: The owner/company of the assistant. + :ivar url: The url of the assistant resource. + :ivar personality_prompt: The personality prompt to be used for assistant. + :ivar date_created: The date and time in GMT when the Assistant was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Assistant was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar knowledge: The list of knowledge sources associated with the assistant. + :ivar tools: The list of tools associated with the assistant. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], id: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.customer_ai: Optional[Dict[str, object]] = payload.get("customer_ai") + self.id: Optional[str] = payload.get("id") + self.model: Optional[str] = payload.get("model") + self.name: Optional[str] = payload.get("name") + self.owner: Optional[str] = payload.get("owner") + self.url: Optional[str] = payload.get("url") + self.personality_prompt: Optional[str] = payload.get("personality_prompt") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.knowledge: Optional[List[str]] = payload.get("knowledge") + self.tools: Optional[List[str]] = payload.get("tools") + + self._solution = { + "id": id or self.id, + } + self._context: Optional[AssistantContext] = None + + @property + def _proxy(self) -> "AssistantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AssistantContext for this AssistantInstance + """ + if self._context is None: + self._context = AssistantContext( + self._version, + id=self._solution["id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AssistantInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssistantInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AssistantInstance": + """ + Fetch the AssistantInstance + + + :returns: The fetched AssistantInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AssistantInstance": + """ + Asynchronous coroutine to fetch the AssistantInstance + + + :returns: The fetched AssistantInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + assistants_v1_service_update_assistant_request: Union[ + AssistantsV1ServiceUpdateAssistantRequest, object + ] = values.unset, + ) -> "AssistantInstance": + """ + Update the AssistantInstance + + :param assistants_v1_service_update_assistant_request: + + :returns: The updated AssistantInstance + """ + return self._proxy.update( + assistants_v1_service_update_assistant_request=assistants_v1_service_update_assistant_request, + ) + + async def update_async( + self, + assistants_v1_service_update_assistant_request: Union[ + AssistantsV1ServiceUpdateAssistantRequest, object + ] = values.unset, + ) -> "AssistantInstance": + """ + Asynchronous coroutine to update the AssistantInstance + + :param assistants_v1_service_update_assistant_request: + + :returns: The updated AssistantInstance + """ + return await self._proxy.update_async( + assistants_v1_service_update_assistant_request=assistants_v1_service_update_assistant_request, + ) + + @property + def assistants_knowledge(self) -> AssistantsKnowledgeList: + """ + Access the assistants_knowledge + """ + return self._proxy.assistants_knowledge + + @property + def assistants_tools(self) -> AssistantsToolList: + """ + Access the assistants_tools + """ + return self._proxy.assistants_tools + + @property + def feedbacks(self) -> FeedbackList: + """ + Access the feedbacks + """ + return self._proxy.feedbacks + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Assistants.V1.AssistantInstance {}>".format(context) + + +class AssistantContext(InstanceContext): + + class AssistantsV1ServiceCreateAssistantRequest(object): + """ + :ivar customer_ai: + :ivar name: The name of the assistant. + :ivar owner: The owner/company of the assistant. + :ivar personality_prompt: The personality prompt to be used for assistant. + :ivar segment_credential: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_ai: Optional[AssistantList.AssistantsV1ServiceCustomerAi] = ( + payload.get("customer_ai") + ) + self.name: Optional[str] = payload.get("name") + self.owner: Optional[str] = payload.get("owner") + self.personality_prompt: Optional[str] = payload.get("personality_prompt") + self.segment_credential: Optional[ + AssistantList.AssistantsV1ServiceSegmentCredential + ] = payload.get("segment_credential") + + def to_dict(self): + return { + "customer_ai": ( + self.customer_ai.to_dict() if self.customer_ai is not None else None + ), + "name": self.name, + "owner": self.owner, + "personality_prompt": self.personality_prompt, + "segment_credential": ( + self.segment_credential.to_dict() + if self.segment_credential is not None + else None + ), + } + + class AssistantsV1ServiceCustomerAi(object): + """ + :ivar perception_engine_enabled: True if the perception engine is enabled. + :ivar personalization_engine_enabled: True if the personalization engine is enabled. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.perception_engine_enabled: Optional[bool] = payload.get( + "perception_engine_enabled" + ) + self.personalization_engine_enabled: Optional[bool] = payload.get( + "personalization_engine_enabled" + ) + + def to_dict(self): + return { + "perception_engine_enabled": self.perception_engine_enabled, + "personalization_engine_enabled": self.personalization_engine_enabled, + } + + class AssistantsV1ServiceSegmentCredential(object): + """ + :ivar profile_api_key: The profile API key. + :ivar space_id: The space ID. + :ivar write_key: The write key. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.profile_api_key: Optional[str] = payload.get("profile_api_key") + self.space_id: Optional[str] = payload.get("space_id") + self.write_key: Optional[str] = payload.get("write_key") + + def to_dict(self): + return { + "profile_api_key": self.profile_api_key, + "space_id": self.space_id, + "write_key": self.write_key, + } + + class AssistantsV1ServiceUpdateAssistantRequest(object): + """ + :ivar customer_ai: + :ivar name: The name of the assistant. + :ivar owner: The owner/company of the assistant. + :ivar personality_prompt: The personality prompt to be used for assistant. + :ivar segment_credential: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_ai: Optional[AssistantList.AssistantsV1ServiceCustomerAi] = ( + payload.get("customer_ai") + ) + self.name: Optional[str] = payload.get("name") + self.owner: Optional[str] = payload.get("owner") + self.personality_prompt: Optional[str] = payload.get("personality_prompt") + self.segment_credential: Optional[ + AssistantList.AssistantsV1ServiceSegmentCredential + ] = payload.get("segment_credential") + + def to_dict(self): + return { + "customer_ai": ( + self.customer_ai.to_dict() if self.customer_ai is not None else None + ), + "name": self.name, + "owner": self.owner, + "personality_prompt": self.personality_prompt, + "segment_credential": ( + self.segment_credential.to_dict() + if self.segment_credential is not None + else None + ), + } + + def __init__(self, version: Version, id: str): + """ + Initialize the AssistantContext + + :param version: Version that contains the resource + :param id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Assistants/{id}".format(**self._solution) + + self._assistants_knowledge: Optional[AssistantsKnowledgeList] = None + self._assistants_tools: Optional[AssistantsToolList] = None + self._feedbacks: Optional[FeedbackList] = None + self._messages: Optional[MessageList] = None + + def delete(self) -> bool: + """ + Deletes the AssistantInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssistantInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AssistantInstance: + """ + Fetch the AssistantInstance + + + :returns: The fetched AssistantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AssistantInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_async(self) -> AssistantInstance: + """ + Asynchronous coroutine to fetch the AssistantInstance + + + :returns: The fetched AssistantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AssistantInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def update( + self, + assistants_v1_service_update_assistant_request: Union[ + AssistantsV1ServiceUpdateAssistantRequest, object + ] = values.unset, + ) -> AssistantInstance: + """ + Update the AssistantInstance + + :param assistants_v1_service_update_assistant_request: + + :returns: The updated AssistantInstance + """ + data = assistants_v1_service_update_assistant_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + return AssistantInstance(self._version, payload, id=self._solution["id"]) + + async def update_async( + self, + assistants_v1_service_update_assistant_request: Union[ + AssistantsV1ServiceUpdateAssistantRequest, object + ] = values.unset, + ) -> AssistantInstance: + """ + Asynchronous coroutine to update the AssistantInstance + + :param assistants_v1_service_update_assistant_request: + + :returns: The updated AssistantInstance + """ + data = assistants_v1_service_update_assistant_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + return AssistantInstance(self._version, payload, id=self._solution["id"]) + + @property + def assistants_knowledge(self) -> AssistantsKnowledgeList: + """ + Access the assistants_knowledge + """ + if self._assistants_knowledge is None: + self._assistants_knowledge = AssistantsKnowledgeList( + self._version, + self._solution["id"], + ) + return self._assistants_knowledge + + @property + def assistants_tools(self) -> AssistantsToolList: + """ + Access the assistants_tools + """ + if self._assistants_tools is None: + self._assistants_tools = AssistantsToolList( + self._version, + self._solution["id"], + ) + return self._assistants_tools + + @property + def feedbacks(self) -> FeedbackList: + """ + Access the feedbacks + """ + if self._feedbacks is None: + self._feedbacks = FeedbackList( + self._version, + self._solution["id"], + ) + return self._feedbacks + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["id"], + ) + return self._messages + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Assistants.V1.AssistantContext {}>".format(context) + + +class AssistantPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AssistantInstance: + """ + Build an instance of AssistantInstance + + :param payload: Payload response from the API + """ + return AssistantInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.AssistantPage>" + + +class AssistantList(ListResource): + + class AssistantsV1ServiceCreateAssistantRequest(object): + """ + :ivar customer_ai: + :ivar name: The name of the assistant. + :ivar owner: The owner/company of the assistant. + :ivar personality_prompt: The personality prompt to be used for assistant. + :ivar segment_credential: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_ai: Optional[AssistantList.AssistantsV1ServiceCustomerAi] = ( + payload.get("customer_ai") + ) + self.name: Optional[str] = payload.get("name") + self.owner: Optional[str] = payload.get("owner") + self.personality_prompt: Optional[str] = payload.get("personality_prompt") + self.segment_credential: Optional[ + AssistantList.AssistantsV1ServiceSegmentCredential + ] = payload.get("segment_credential") + + def to_dict(self): + return { + "customer_ai": ( + self.customer_ai.to_dict() if self.customer_ai is not None else None + ), + "name": self.name, + "owner": self.owner, + "personality_prompt": self.personality_prompt, + "segment_credential": ( + self.segment_credential.to_dict() + if self.segment_credential is not None + else None + ), + } + + class AssistantsV1ServiceCustomerAi(object): + """ + :ivar perception_engine_enabled: True if the perception engine is enabled. + :ivar personalization_engine_enabled: True if the personalization engine is enabled. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.perception_engine_enabled: Optional[bool] = payload.get( + "perception_engine_enabled" + ) + self.personalization_engine_enabled: Optional[bool] = payload.get( + "personalization_engine_enabled" + ) + + def to_dict(self): + return { + "perception_engine_enabled": self.perception_engine_enabled, + "personalization_engine_enabled": self.personalization_engine_enabled, + } + + class AssistantsV1ServiceSegmentCredential(object): + """ + :ivar profile_api_key: The profile API key. + :ivar space_id: The space ID. + :ivar write_key: The write key. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.profile_api_key: Optional[str] = payload.get("profile_api_key") + self.space_id: Optional[str] = payload.get("space_id") + self.write_key: Optional[str] = payload.get("write_key") + + def to_dict(self): + return { + "profile_api_key": self.profile_api_key, + "space_id": self.space_id, + "write_key": self.write_key, + } + + class AssistantsV1ServiceUpdateAssistantRequest(object): + """ + :ivar customer_ai: + :ivar name: The name of the assistant. + :ivar owner: The owner/company of the assistant. + :ivar personality_prompt: The personality prompt to be used for assistant. + :ivar segment_credential: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.customer_ai: Optional[AssistantList.AssistantsV1ServiceCustomerAi] = ( + payload.get("customer_ai") + ) + self.name: Optional[str] = payload.get("name") + self.owner: Optional[str] = payload.get("owner") + self.personality_prompt: Optional[str] = payload.get("personality_prompt") + self.segment_credential: Optional[ + AssistantList.AssistantsV1ServiceSegmentCredential + ] = payload.get("segment_credential") + + def to_dict(self): + return { + "customer_ai": ( + self.customer_ai.to_dict() if self.customer_ai is not None else None + ), + "name": self.name, + "owner": self.owner, + "personality_prompt": self.personality_prompt, + "segment_credential": ( + self.segment_credential.to_dict() + if self.segment_credential is not None + else None + ), + } + + def __init__(self, version: Version): + """ + Initialize the AssistantList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Assistants" + + def create( + self, + assistants_v1_service_create_assistant_request: AssistantsV1ServiceCreateAssistantRequest, + ) -> AssistantInstance: + """ + Create the AssistantInstance + + :param assistants_v1_service_create_assistant_request: + + :returns: The created AssistantInstance + """ + data = assistants_v1_service_create_assistant_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssistantInstance(self._version, payload) + + async def create_async( + self, + assistants_v1_service_create_assistant_request: AssistantsV1ServiceCreateAssistantRequest, + ) -> AssistantInstance: + """ + Asynchronously create the AssistantInstance + + :param assistants_v1_service_create_assistant_request: + + :returns: The created AssistantInstance + """ + data = assistants_v1_service_create_assistant_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssistantInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssistantInstance]: + """ + Streams AssistantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AssistantInstance]: + """ + Asynchronously streams AssistantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssistantInstance]: + """ + Lists AssistantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssistantInstance]: + """ + Asynchronously lists AssistantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssistantPage: + """ + Retrieve a single page of AssistantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssistantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssistantPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssistantPage: + """ + Asynchronously retrieve a single page of AssistantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssistantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssistantPage(self._version, response) + + def get_page(self, target_url: str) -> AssistantPage: + """ + Retrieve a specific page of AssistantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssistantInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AssistantPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AssistantPage: + """ + Asynchronously retrieve a specific page of AssistantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssistantInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssistantPage(self._version, response) + + def get(self, id: str) -> AssistantContext: + """ + Constructs a AssistantContext + + :param id: + """ + return AssistantContext(self._version, id=id) + + def __call__(self, id: str) -> AssistantContext: + """ + Constructs a AssistantContext + + :param id: + """ + return AssistantContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.AssistantList>" diff --git a/twilio/rest/assistants/v1/assistant/assistants_knowledge.py b/twilio/rest/assistants/v1/assistant/assistants_knowledge.py new file mode 100644 index 0000000000..681d71789b --- /dev/null +++ b/twilio/rest/assistants/v1/assistant/assistants_knowledge.py @@ -0,0 +1,520 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AssistantsKnowledgeInstance(InstanceResource): + """ + :ivar description: The type of knowledge source. + :ivar id: The description of knowledge. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. + :ivar knowledge_source_details: The details of the knowledge source based on the type. + :ivar name: The name of the knowledge source. + :ivar status: The status of processing the knowledge source ('QUEUED', 'PROCESSING', 'COMPLETED', 'FAILED') + :ivar type: The type of knowledge source ('Web', 'Database', 'Text', 'File') + :ivar url: The url of the knowledge resource. + :ivar embedding_model: The embedding model to be used for the knowledge source. + :ivar date_created: The date and time in GMT when the Knowledge was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Knowledge was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + assistant_id: str, + id: Optional[str] = None, + ): + super().__init__(version) + + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.account_sid: Optional[str] = payload.get("account_sid") + self.knowledge_source_details: Optional[Dict[str, object]] = payload.get( + "knowledge_source_details" + ) + self.name: Optional[str] = payload.get("name") + self.status: Optional[str] = payload.get("status") + self.type: Optional[str] = payload.get("type") + self.url: Optional[str] = payload.get("url") + self.embedding_model: Optional[str] = payload.get("embedding_model") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "assistant_id": assistant_id, + "id": id or self.id, + } + self._context: Optional[AssistantsKnowledgeContext] = None + + @property + def _proxy(self) -> "AssistantsKnowledgeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AssistantsKnowledgeContext for this AssistantsKnowledgeInstance + """ + if self._context is None: + self._context = AssistantsKnowledgeContext( + self._version, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + return self._context + + def create(self) -> "AssistantsKnowledgeInstance": + """ + Create the AssistantsKnowledgeInstance + + + :returns: The created AssistantsKnowledgeInstance + """ + return self._proxy.create() + + async def create_async(self) -> "AssistantsKnowledgeInstance": + """ + Asynchronous coroutine to create the AssistantsKnowledgeInstance + + + :returns: The created AssistantsKnowledgeInstance + """ + return await self._proxy.create_async() + + def delete(self) -> bool: + """ + Deletes the AssistantsKnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssistantsKnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Assistants.V1.AssistantsKnowledgeInstance {}>".format(context) + + +class AssistantsKnowledgeContext(InstanceContext): + + def __init__(self, version: Version, assistant_id: str, id: str): + """ + Initialize the AssistantsKnowledgeContext + + :param version: Version that contains the resource + :param assistant_id: The assistant ID. + :param id: The knowledge ID. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "assistant_id": assistant_id, + "id": id, + } + self._uri = "/Assistants/{assistant_id}/Knowledge/{id}".format(**self._solution) + + def create(self) -> AssistantsKnowledgeInstance: + """ + Create the AssistantsKnowledgeInstance + + + :returns: The created AssistantsKnowledgeInstance + """ + data = values.of({}) + + payload = self._version.create(method="POST", uri=self._uri, data=data) + + return AssistantsKnowledgeInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + + async def create_async(self) -> AssistantsKnowledgeInstance: + """ + Asynchronous coroutine to create the AssistantsKnowledgeInstance + + + :returns: The created AssistantsKnowledgeInstance + """ + data = values.of({}) + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data + ) + + return AssistantsKnowledgeInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + + def delete(self) -> bool: + """ + Deletes the AssistantsKnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssistantsKnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Assistants.V1.AssistantsKnowledgeContext {}>".format(context) + + +class AssistantsKnowledgePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AssistantsKnowledgeInstance: + """ + Build an instance of AssistantsKnowledgeInstance + + :param payload: Payload response from the API + """ + return AssistantsKnowledgeInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.AssistantsKnowledgePage>" + + +class AssistantsKnowledgeList(ListResource): + + def __init__(self, version: Version, assistant_id: str): + """ + Initialize the AssistantsKnowledgeList + + :param version: Version that contains the resource + :param assistant_id: The assistant ID. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "assistant_id": assistant_id, + } + self._uri = "/Assistants/{assistant_id}/Knowledge".format(**self._solution) + + def create(self) -> AssistantsKnowledgeInstance: + """ + Create the AssistantsKnowledgeInstance + + + :returns: The created AssistantsKnowledgeInstance + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + payload = self._version.create(method="POST", uri=self._uri, headers=headers) + + return AssistantsKnowledgeInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + + async def create_async(self) -> AssistantsKnowledgeInstance: + """ + Asynchronously create the AssistantsKnowledgeInstance + + + :returns: The created AssistantsKnowledgeInstance + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + payload = await self._version.create_async( + method="POST", uri=self._uri, headers=headers + ) + + return AssistantsKnowledgeInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssistantsKnowledgeInstance]: + """ + Streams AssistantsKnowledgeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AssistantsKnowledgeInstance]: + """ + Asynchronously streams AssistantsKnowledgeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssistantsKnowledgeInstance]: + """ + Lists AssistantsKnowledgeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssistantsKnowledgeInstance]: + """ + Asynchronously lists AssistantsKnowledgeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssistantsKnowledgePage: + """ + Retrieve a single page of AssistantsKnowledgeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssistantsKnowledgeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssistantsKnowledgePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssistantsKnowledgePage: + """ + Asynchronously retrieve a single page of AssistantsKnowledgeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssistantsKnowledgeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssistantsKnowledgePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AssistantsKnowledgePage: + """ + Retrieve a specific page of AssistantsKnowledgeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssistantsKnowledgeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AssistantsKnowledgePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AssistantsKnowledgePage: + """ + Asynchronously retrieve a specific page of AssistantsKnowledgeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssistantsKnowledgeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssistantsKnowledgePage(self._version, response, self._solution) + + def get(self, id: str) -> AssistantsKnowledgeContext: + """ + Constructs a AssistantsKnowledgeContext + + :param id: The knowledge ID. + """ + return AssistantsKnowledgeContext( + self._version, assistant_id=self._solution["assistant_id"], id=id + ) + + def __call__(self, id: str) -> AssistantsKnowledgeContext: + """ + Constructs a AssistantsKnowledgeContext + + :param id: The knowledge ID. + """ + return AssistantsKnowledgeContext( + self._version, assistant_id=self._solution["assistant_id"], id=id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.AssistantsKnowledgeList>" diff --git a/twilio/rest/assistants/v1/assistant/assistants_tool.py b/twilio/rest/assistants/v1/assistant/assistants_tool.py new file mode 100644 index 0000000000..ed02410d3c --- /dev/null +++ b/twilio/rest/assistants/v1/assistant/assistants_tool.py @@ -0,0 +1,518 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AssistantsToolInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Tool resource. + :ivar description: The description of the tool. + :ivar enabled: True if the tool is enabled. + :ivar id: The tool ID. + :ivar meta: The metadata related to method, url, input_schema to used with the Tool. + :ivar name: The name of the tool. + :ivar requires_auth: The authentication requirement for the tool. + :ivar type: The type of the tool. ('WEBHOOK') + :ivar url: The url of the tool resource. + :ivar date_created: The date and time in GMT when the Tool was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Tool was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + assistant_id: str, + id: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.description: Optional[str] = payload.get("description") + self.enabled: Optional[bool] = payload.get("enabled") + self.id: Optional[str] = payload.get("id") + self.meta: Optional[Dict[str, object]] = payload.get("meta") + self.name: Optional[str] = payload.get("name") + self.requires_auth: Optional[bool] = payload.get("requires_auth") + self.type: Optional[str] = payload.get("type") + self.url: Optional[str] = payload.get("url") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "assistant_id": assistant_id, + "id": id or self.id, + } + self._context: Optional[AssistantsToolContext] = None + + @property + def _proxy(self) -> "AssistantsToolContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AssistantsToolContext for this AssistantsToolInstance + """ + if self._context is None: + self._context = AssistantsToolContext( + self._version, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + return self._context + + def create(self) -> "AssistantsToolInstance": + """ + Create the AssistantsToolInstance + + + :returns: The created AssistantsToolInstance + """ + return self._proxy.create() + + async def create_async(self) -> "AssistantsToolInstance": + """ + Asynchronous coroutine to create the AssistantsToolInstance + + + :returns: The created AssistantsToolInstance + """ + return await self._proxy.create_async() + + def delete(self) -> bool: + """ + Deletes the AssistantsToolInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssistantsToolInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Assistants.V1.AssistantsToolInstance {}>".format(context) + + +class AssistantsToolContext(InstanceContext): + + def __init__(self, version: Version, assistant_id: str, id: str): + """ + Initialize the AssistantsToolContext + + :param version: Version that contains the resource + :param assistant_id: The assistant ID. + :param id: The tool ID. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "assistant_id": assistant_id, + "id": id, + } + self._uri = "/Assistants/{assistant_id}/Tools/{id}".format(**self._solution) + + def create(self) -> AssistantsToolInstance: + """ + Create the AssistantsToolInstance + + + :returns: The created AssistantsToolInstance + """ + data = values.of({}) + + payload = self._version.create(method="POST", uri=self._uri, data=data) + + return AssistantsToolInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + + async def create_async(self) -> AssistantsToolInstance: + """ + Asynchronous coroutine to create the AssistantsToolInstance + + + :returns: The created AssistantsToolInstance + """ + data = values.of({}) + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data + ) + + return AssistantsToolInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + + def delete(self) -> bool: + """ + Deletes the AssistantsToolInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssistantsToolInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Assistants.V1.AssistantsToolContext {}>".format(context) + + +class AssistantsToolPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AssistantsToolInstance: + """ + Build an instance of AssistantsToolInstance + + :param payload: Payload response from the API + """ + return AssistantsToolInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.AssistantsToolPage>" + + +class AssistantsToolList(ListResource): + + def __init__(self, version: Version, assistant_id: str): + """ + Initialize the AssistantsToolList + + :param version: Version that contains the resource + :param assistant_id: The assistant ID. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "assistant_id": assistant_id, + } + self._uri = "/Assistants/{assistant_id}/Tools".format(**self._solution) + + def create(self) -> AssistantsToolInstance: + """ + Create the AssistantsToolInstance + + + :returns: The created AssistantsToolInstance + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + payload = self._version.create(method="POST", uri=self._uri, headers=headers) + + return AssistantsToolInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + + async def create_async(self) -> AssistantsToolInstance: + """ + Asynchronously create the AssistantsToolInstance + + + :returns: The created AssistantsToolInstance + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + payload = await self._version.create_async( + method="POST", uri=self._uri, headers=headers + ) + + return AssistantsToolInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssistantsToolInstance]: + """ + Streams AssistantsToolInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AssistantsToolInstance]: + """ + Asynchronously streams AssistantsToolInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssistantsToolInstance]: + """ + Lists AssistantsToolInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssistantsToolInstance]: + """ + Asynchronously lists AssistantsToolInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssistantsToolPage: + """ + Retrieve a single page of AssistantsToolInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssistantsToolInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssistantsToolPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssistantsToolPage: + """ + Asynchronously retrieve a single page of AssistantsToolInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssistantsToolInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssistantsToolPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AssistantsToolPage: + """ + Retrieve a specific page of AssistantsToolInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssistantsToolInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AssistantsToolPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AssistantsToolPage: + """ + Asynchronously retrieve a specific page of AssistantsToolInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssistantsToolInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssistantsToolPage(self._version, response, self._solution) + + def get(self, id: str) -> AssistantsToolContext: + """ + Constructs a AssistantsToolContext + + :param id: The tool ID. + """ + return AssistantsToolContext( + self._version, assistant_id=self._solution["assistant_id"], id=id + ) + + def __call__(self, id: str) -> AssistantsToolContext: + """ + Constructs a AssistantsToolContext + + :param id: The tool ID. + """ + return AssistantsToolContext( + self._version, assistant_id=self._solution["assistant_id"], id=id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.AssistantsToolList>" diff --git a/twilio/rest/assistants/v1/assistant/feedback.py b/twilio/rest/assistants/v1/assistant/feedback.py new file mode 100644 index 0000000000..77c6d405f4 --- /dev/null +++ b/twilio/rest/assistants/v1/assistant/feedback.py @@ -0,0 +1,404 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class FeedbackInstance(InstanceResource): + + class AssistantsV1ServiceCreateFeedbackRequest(object): + """ + :ivar message_id: The message ID. + :ivar score: The score to be given(0-1). + :ivar session_id: The Session ID. + :ivar text: The text to be given as feedback. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.message_id: Optional[str] = payload.get("message_id") + self.score: Optional[float] = payload.get("score") + self.session_id: Optional[str] = payload.get("session_id") + self.text: Optional[str] = payload.get("text") + + def to_dict(self): + return { + "message_id": self.message_id, + "score": self.score, + "session_id": self.session_id, + "text": self.text, + } + + """ + :ivar assistant_id: The Assistant ID. + :ivar id: The Feedback ID. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Feedback. + :ivar user_sid: The SID of the User created the Feedback. + :ivar message_id: The Message ID. + :ivar score: The Score to provide as Feedback (0-1) + :ivar session_id: The Session ID. + :ivar text: The text to be given as feedback. + :ivar date_created: The date and time in GMT when the Feedback was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Feedback was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], id: str): + super().__init__(version) + + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.id: Optional[str] = payload.get("id") + self.account_sid: Optional[str] = payload.get("account_sid") + self.user_sid: Optional[str] = payload.get("user_sid") + self.message_id: Optional[str] = payload.get("message_id") + self.score: Optional[float] = payload.get("score") + self.session_id: Optional[str] = payload.get("session_id") + self.text: Optional[str] = payload.get("text") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "id": id, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Assistants.V1.FeedbackInstance {}>".format(context) + + +class FeedbackPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FeedbackInstance: + """ + Build an instance of FeedbackInstance + + :param payload: Payload response from the API + """ + return FeedbackInstance(self._version, payload, id=self._solution["id"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.FeedbackPage>" + + +class FeedbackList(ListResource): + + class AssistantsV1ServiceCreateFeedbackRequest(object): + """ + :ivar message_id: The message ID. + :ivar score: The score to be given(0-1). + :ivar session_id: The Session ID. + :ivar text: The text to be given as feedback. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.message_id: Optional[str] = payload.get("message_id") + self.score: Optional[float] = payload.get("score") + self.session_id: Optional[str] = payload.get("session_id") + self.text: Optional[str] = payload.get("text") + + def to_dict(self): + return { + "message_id": self.message_id, + "score": self.score, + "session_id": self.session_id, + "text": self.text, + } + + def __init__(self, version: Version, id: str): + """ + Initialize the FeedbackList + + :param version: Version that contains the resource + :param id: The assistant ID. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Assistants/{id}/Feedbacks".format(**self._solution) + + def create( + self, + assistants_v1_service_create_feedback_request: AssistantsV1ServiceCreateFeedbackRequest, + ) -> FeedbackInstance: + """ + Create the FeedbackInstance + + :param assistants_v1_service_create_feedback_request: + + :returns: The created FeedbackInstance + """ + data = assistants_v1_service_create_feedback_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FeedbackInstance(self._version, payload, id=self._solution["id"]) + + async def create_async( + self, + assistants_v1_service_create_feedback_request: AssistantsV1ServiceCreateFeedbackRequest, + ) -> FeedbackInstance: + """ + Asynchronously create the FeedbackInstance + + :param assistants_v1_service_create_feedback_request: + + :returns: The created FeedbackInstance + """ + data = assistants_v1_service_create_feedback_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FeedbackInstance(self._version, payload, id=self._solution["id"]) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FeedbackInstance]: + """ + Streams FeedbackInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FeedbackInstance]: + """ + Asynchronously streams FeedbackInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FeedbackInstance]: + """ + Lists FeedbackInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FeedbackInstance]: + """ + Asynchronously lists FeedbackInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FeedbackPage: + """ + Retrieve a single page of FeedbackInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FeedbackInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FeedbackPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FeedbackPage: + """ + Asynchronously retrieve a single page of FeedbackInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FeedbackInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FeedbackPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> FeedbackPage: + """ + Retrieve a specific page of FeedbackInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FeedbackInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FeedbackPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> FeedbackPage: + """ + Asynchronously retrieve a specific page of FeedbackInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FeedbackInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FeedbackPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.FeedbackList>" diff --git a/twilio/rest/assistants/v1/assistant/message.py b/twilio/rest/assistants/v1/assistant/message.py new file mode 100644 index 0000000000..11d73776b7 --- /dev/null +++ b/twilio/rest/assistants/v1/assistant/message.py @@ -0,0 +1,186 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class MessageInstance(InstanceResource): + + class AssistantsV1ServiceAssistantSendMessageRequest(object): + """ + :ivar identity: The unique identity of user for the session. + :ivar session_id: The unique name for the session. + :ivar body: The query to ask the assistant. + :ivar webhook: The webhook url to call after the assistant has generated a response or report an error. + :ivar mode: one of the modes 'chat', 'email' or 'voice' + """ + + def __init__(self, payload: Dict[str, Any]): + + self.identity: Optional[str] = payload.get("identity") + self.session_id: Optional[str] = payload.get("session_id") + self.body: Optional[str] = payload.get("body") + self.webhook: Optional[str] = payload.get("webhook") + self.mode: Optional[str] = payload.get("mode") + + def to_dict(self): + return { + "identity": self.identity, + "session_id": self.session_id, + "body": self.body, + "webhook": self.webhook, + "mode": self.mode, + } + + """ + :ivar status: success or failure based on whether the request successfully generated a response. + :ivar flagged: If successful, this property will denote whether the response was flagged or not. + :ivar aborted: This property will denote whether the request was aborted or not. + :ivar session_id: The unique name for the session. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that sent the Message. + :ivar body: If successful, the body of the generated response + :ivar error: The error message if generation was not successful + """ + + def __init__(self, version: Version, payload: Dict[str, Any], id: str): + super().__init__(version) + + self.status: Optional[str] = payload.get("status") + self.flagged: Optional[bool] = payload.get("flagged") + self.aborted: Optional[bool] = payload.get("aborted") + self.session_id: Optional[str] = payload.get("session_id") + self.account_sid: Optional[str] = payload.get("account_sid") + self.body: Optional[str] = payload.get("body") + self.error: Optional[str] = payload.get("error") + + self._solution = { + "id": id, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Assistants.V1.MessageInstance {}>".format(context) + + +class MessageList(ListResource): + + class AssistantsV1ServiceAssistantSendMessageRequest(object): + """ + :ivar identity: The unique identity of user for the session. + :ivar session_id: The unique name for the session. + :ivar body: The query to ask the assistant. + :ivar webhook: The webhook url to call after the assistant has generated a response or report an error. + :ivar mode: one of the modes 'chat', 'email' or 'voice' + """ + + def __init__(self, payload: Dict[str, Any]): + + self.identity: Optional[str] = payload.get("identity") + self.session_id: Optional[str] = payload.get("session_id") + self.body: Optional[str] = payload.get("body") + self.webhook: Optional[str] = payload.get("webhook") + self.mode: Optional[str] = payload.get("mode") + + def to_dict(self): + return { + "identity": self.identity, + "session_id": self.session_id, + "body": self.body, + "webhook": self.webhook, + "mode": self.mode, + } + + def __init__(self, version: Version, id: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param id: the Assistant ID. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Assistants/{id}/Messages".format(**self._solution) + + def create( + self, + assistants_v1_service_assistant_send_message_request: AssistantsV1ServiceAssistantSendMessageRequest, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param assistants_v1_service_assistant_send_message_request: + + :returns: The created MessageInstance + """ + data = assistants_v1_service_assistant_send_message_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance(self._version, payload, id=self._solution["id"]) + + async def create_async( + self, + assistants_v1_service_assistant_send_message_request: AssistantsV1ServiceAssistantSendMessageRequest, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param assistants_v1_service_assistant_send_message_request: + + :returns: The created MessageInstance + """ + data = assistants_v1_service_assistant_send_message_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance(self._version, payload, id=self._solution["id"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.MessageList>" diff --git a/twilio/rest/assistants/v1/knowledge/__init__.py b/twilio/rest/assistants/v1/knowledge/__init__.py new file mode 100644 index 0000000000..7d616f8682 --- /dev/null +++ b/twilio/rest/assistants/v1/knowledge/__init__.py @@ -0,0 +1,962 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.assistants.v1.knowledge.chunk import ChunkList +from twilio.rest.assistants.v1.knowledge.knowledge_status import KnowledgeStatusList + + +class KnowledgeInstance(InstanceResource): + + class AssistantsV1ServiceCreateKnowledgeRequest(object): + """ + :ivar assistant_id: The Assistant ID. + :ivar description: The description of the knowledge source. + :ivar knowledge_source_details: The details of the knowledge source based on the type. + :ivar name: The name of the tool. + :ivar policy: + :ivar type: The type of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's required for 'Database' type but disallowed for other types. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.description: Optional[str] = payload.get("description") + self.knowledge_source_details: Optional[Dict[str, object]] = payload.get( + "knowledge_source_details" + ) + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ + KnowledgeList.AssistantsV1ServiceCreatePolicyRequest + ] = payload.get("policy") + self.type: Optional[str] = payload.get("type") + self.embedding_model: Optional[str] = payload.get("embedding_model") + + def to_dict(self): + return { + "assistant_id": self.assistant_id, + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + class AssistantsV1ServiceCreatePolicyRequest(object): + """ + :ivar description: The description of the policy. + :ivar id: The Policy ID. + :ivar name: The name of the policy. + :ivar policy_details: + :ivar type: The description of the policy. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.policy_details: Optional[Dict[str, object]] = payload.get( + "policy_details" + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "description": self.description, + "id": self.id, + "name": self.name, + "policy_details": self.policy_details, + "type": self.type, + } + + class AssistantsV1ServiceUpdateKnowledgeRequest(object): + """ + :ivar description: The description of the knowledge source. + :ivar knowledge_source_details: The details of the knowledge source based on the type. + :ivar name: The name of the knowledge source. + :ivar policy: + :ivar type: The description of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's only applicable to 'Database' type. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.knowledge_source_details: Optional[Dict[str, object]] = payload.get( + "knowledge_source_details" + ) + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ + KnowledgeList.AssistantsV1ServiceCreatePolicyRequest + ] = payload.get("policy") + self.type: Optional[str] = payload.get("type") + self.embedding_model: Optional[str] = payload.get("embedding_model") + + def to_dict(self): + return { + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + """ + :ivar description: The type of knowledge source. + :ivar id: The description of knowledge. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. + :ivar knowledge_source_details: The details of the knowledge source based on the type. + :ivar name: The name of the knowledge source. + :ivar status: The status of processing the knowledge source ('QUEUED', 'PROCESSING', 'COMPLETED', 'FAILED') + :ivar type: The type of knowledge source ('Web', 'Database', 'Text', 'File') + :ivar url: The url of the knowledge resource. + :ivar embedding_model: The embedding model to be used for the knowledge source. + :ivar date_created: The date and time in GMT when the Knowledge was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Knowledge was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], id: Optional[str] = None + ): + super().__init__(version) + + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.account_sid: Optional[str] = payload.get("account_sid") + self.knowledge_source_details: Optional[Dict[str, object]] = payload.get( + "knowledge_source_details" + ) + self.name: Optional[str] = payload.get("name") + self.status: Optional[str] = payload.get("status") + self.type: Optional[str] = payload.get("type") + self.url: Optional[str] = payload.get("url") + self.embedding_model: Optional[str] = payload.get("embedding_model") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "id": id or self.id, + } + self._context: Optional[KnowledgeContext] = None + + @property + def _proxy(self) -> "KnowledgeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: KnowledgeContext for this KnowledgeInstance + """ + if self._context is None: + self._context = KnowledgeContext( + self._version, + id=self._solution["id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the KnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the KnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "KnowledgeInstance": + """ + Fetch the KnowledgeInstance + + + :returns: The fetched KnowledgeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "KnowledgeInstance": + """ + Asynchronous coroutine to fetch the KnowledgeInstance + + + :returns: The fetched KnowledgeInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> "KnowledgeInstance": + """ + Update the KnowledgeInstance + + :param assistants_v1_service_update_knowledge_request: + + :returns: The updated KnowledgeInstance + """ + return self._proxy.update( + assistants_v1_service_update_knowledge_request=assistants_v1_service_update_knowledge_request, + ) + + async def update_async( + self, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> "KnowledgeInstance": + """ + Asynchronous coroutine to update the KnowledgeInstance + + :param assistants_v1_service_update_knowledge_request: + + :returns: The updated KnowledgeInstance + """ + return await self._proxy.update_async( + assistants_v1_service_update_knowledge_request=assistants_v1_service_update_knowledge_request, + ) + + @property + def chunks(self) -> ChunkList: + """ + Access the chunks + """ + return self._proxy.chunks + + @property + def knowledge_status(self) -> KnowledgeStatusList: + """ + Access the knowledge_status + """ + return self._proxy.knowledge_status + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Assistants.V1.KnowledgeInstance {}>".format(context) + + +class KnowledgeContext(InstanceContext): + + class AssistantsV1ServiceCreateKnowledgeRequest(object): + """ + :ivar assistant_id: The Assistant ID. + :ivar description: The description of the knowledge source. + :ivar knowledge_source_details: The details of the knowledge source based on the type. + :ivar name: The name of the tool. + :ivar policy: + :ivar type: The type of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's required for 'Database' type but disallowed for other types. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.description: Optional[str] = payload.get("description") + self.knowledge_source_details: Optional[Dict[str, object]] = payload.get( + "knowledge_source_details" + ) + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ + KnowledgeList.AssistantsV1ServiceCreatePolicyRequest + ] = payload.get("policy") + self.type: Optional[str] = payload.get("type") + self.embedding_model: Optional[str] = payload.get("embedding_model") + + def to_dict(self): + return { + "assistant_id": self.assistant_id, + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + class AssistantsV1ServiceCreatePolicyRequest(object): + """ + :ivar description: The description of the policy. + :ivar id: The Policy ID. + :ivar name: The name of the policy. + :ivar policy_details: + :ivar type: The description of the policy. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.policy_details: Optional[Dict[str, object]] = payload.get( + "policy_details" + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "description": self.description, + "id": self.id, + "name": self.name, + "policy_details": self.policy_details, + "type": self.type, + } + + class AssistantsV1ServiceUpdateKnowledgeRequest(object): + """ + :ivar description: The description of the knowledge source. + :ivar knowledge_source_details: The details of the knowledge source based on the type. + :ivar name: The name of the knowledge source. + :ivar policy: + :ivar type: The description of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's only applicable to 'Database' type. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.knowledge_source_details: Optional[Dict[str, object]] = payload.get( + "knowledge_source_details" + ) + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ + KnowledgeList.AssistantsV1ServiceCreatePolicyRequest + ] = payload.get("policy") + self.type: Optional[str] = payload.get("type") + self.embedding_model: Optional[str] = payload.get("embedding_model") + + def to_dict(self): + return { + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + def __init__(self, version: Version, id: str): + """ + Initialize the KnowledgeContext + + :param version: Version that contains the resource + :param id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Knowledge/{id}".format(**self._solution) + + self._chunks: Optional[ChunkList] = None + self._knowledge_status: Optional[KnowledgeStatusList] = None + + def delete(self) -> bool: + """ + Deletes the KnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the KnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> KnowledgeInstance: + """ + Fetch the KnowledgeInstance + + + :returns: The fetched KnowledgeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return KnowledgeInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_async(self) -> KnowledgeInstance: + """ + Asynchronous coroutine to fetch the KnowledgeInstance + + + :returns: The fetched KnowledgeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return KnowledgeInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def update( + self, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> KnowledgeInstance: + """ + Update the KnowledgeInstance + + :param assistants_v1_service_update_knowledge_request: + + :returns: The updated KnowledgeInstance + """ + data = assistants_v1_service_update_knowledge_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + return KnowledgeInstance(self._version, payload, id=self._solution["id"]) + + async def update_async( + self, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> KnowledgeInstance: + """ + Asynchronous coroutine to update the KnowledgeInstance + + :param assistants_v1_service_update_knowledge_request: + + :returns: The updated KnowledgeInstance + """ + data = assistants_v1_service_update_knowledge_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + return KnowledgeInstance(self._version, payload, id=self._solution["id"]) + + @property + def chunks(self) -> ChunkList: + """ + Access the chunks + """ + if self._chunks is None: + self._chunks = ChunkList( + self._version, + self._solution["id"], + ) + return self._chunks + + @property + def knowledge_status(self) -> KnowledgeStatusList: + """ + Access the knowledge_status + """ + if self._knowledge_status is None: + self._knowledge_status = KnowledgeStatusList( + self._version, + self._solution["id"], + ) + return self._knowledge_status + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Assistants.V1.KnowledgeContext {}>".format(context) + + +class KnowledgePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> KnowledgeInstance: + """ + Build an instance of KnowledgeInstance + + :param payload: Payload response from the API + """ + return KnowledgeInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.KnowledgePage>" + + +class KnowledgeList(ListResource): + + class AssistantsV1ServiceCreateKnowledgeRequest(object): + """ + :ivar assistant_id: The Assistant ID. + :ivar description: The description of the knowledge source. + :ivar knowledge_source_details: The details of the knowledge source based on the type. + :ivar name: The name of the tool. + :ivar policy: + :ivar type: The type of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's required for 'Database' type but disallowed for other types. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.description: Optional[str] = payload.get("description") + self.knowledge_source_details: Optional[Dict[str, object]] = payload.get( + "knowledge_source_details" + ) + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ + KnowledgeList.AssistantsV1ServiceCreatePolicyRequest + ] = payload.get("policy") + self.type: Optional[str] = payload.get("type") + self.embedding_model: Optional[str] = payload.get("embedding_model") + + def to_dict(self): + return { + "assistant_id": self.assistant_id, + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + class AssistantsV1ServiceCreatePolicyRequest(object): + """ + :ivar description: The description of the policy. + :ivar id: The Policy ID. + :ivar name: The name of the policy. + :ivar policy_details: + :ivar type: The description of the policy. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.policy_details: Optional[Dict[str, object]] = payload.get( + "policy_details" + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "description": self.description, + "id": self.id, + "name": self.name, + "policy_details": self.policy_details, + "type": self.type, + } + + class AssistantsV1ServiceUpdateKnowledgeRequest(object): + """ + :ivar description: The description of the knowledge source. + :ivar knowledge_source_details: The details of the knowledge source based on the type. + :ivar name: The name of the knowledge source. + :ivar policy: + :ivar type: The description of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's only applicable to 'Database' type. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.knowledge_source_details: Optional[Dict[str, object]] = payload.get( + "knowledge_source_details" + ) + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ + KnowledgeList.AssistantsV1ServiceCreatePolicyRequest + ] = payload.get("policy") + self.type: Optional[str] = payload.get("type") + self.embedding_model: Optional[str] = payload.get("embedding_model") + + def to_dict(self): + return { + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + def __init__(self, version: Version): + """ + Initialize the KnowledgeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Knowledge" + + def create( + self, + assistants_v1_service_create_knowledge_request: AssistantsV1ServiceCreateKnowledgeRequest, + ) -> KnowledgeInstance: + """ + Create the KnowledgeInstance + + :param assistants_v1_service_create_knowledge_request: + + :returns: The created KnowledgeInstance + """ + data = assistants_v1_service_create_knowledge_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return KnowledgeInstance(self._version, payload) + + async def create_async( + self, + assistants_v1_service_create_knowledge_request: AssistantsV1ServiceCreateKnowledgeRequest, + ) -> KnowledgeInstance: + """ + Asynchronously create the KnowledgeInstance + + :param assistants_v1_service_create_knowledge_request: + + :returns: The created KnowledgeInstance + """ + data = assistants_v1_service_create_knowledge_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return KnowledgeInstance(self._version, payload) + + def stream( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[KnowledgeInstance]: + """ + Streams KnowledgeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str assistant_id: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(assistant_id=assistant_id, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[KnowledgeInstance]: + """ + Asynchronously streams KnowledgeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str assistant_id: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + assistant_id=assistant_id, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[KnowledgeInstance]: + """ + Lists KnowledgeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str assistant_id: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + assistant_id=assistant_id, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[KnowledgeInstance]: + """ + Asynchronously lists KnowledgeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str assistant_id: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + assistant_id=assistant_id, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + assistant_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> KnowledgePage: + """ + Retrieve a single page of KnowledgeInstance records from the API. + Request is executed immediately + + :param assistant_id: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of KnowledgeInstance + """ + data = values.of( + { + "AssistantId": assistant_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return KnowledgePage(self._version, response) + + async def page_async( + self, + assistant_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> KnowledgePage: + """ + Asynchronously retrieve a single page of KnowledgeInstance records from the API. + Request is executed immediately + + :param assistant_id: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of KnowledgeInstance + """ + data = values.of( + { + "AssistantId": assistant_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return KnowledgePage(self._version, response) + + def get_page(self, target_url: str) -> KnowledgePage: + """ + Retrieve a specific page of KnowledgeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of KnowledgeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return KnowledgePage(self._version, response) + + async def get_page_async(self, target_url: str) -> KnowledgePage: + """ + Asynchronously retrieve a specific page of KnowledgeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of KnowledgeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return KnowledgePage(self._version, response) + + def get(self, id: str) -> KnowledgeContext: + """ + Constructs a KnowledgeContext + + :param id: + """ + return KnowledgeContext(self._version, id=id) + + def __call__(self, id: str) -> KnowledgeContext: + """ + Constructs a KnowledgeContext + + :param id: + """ + return KnowledgeContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.KnowledgeList>" diff --git a/twilio/rest/assistants/v1/knowledge/chunk.py b/twilio/rest/assistants/v1/knowledge/chunk.py new file mode 100644 index 0000000000..be90a7626e --- /dev/null +++ b/twilio/rest/assistants/v1/knowledge/chunk.py @@ -0,0 +1,297 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ChunkInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. + :ivar content: The chunk content. + :ivar metadata: The metadata of the chunk. + :ivar date_created: The date and time in GMT when the Chunk was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Chunk was updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], id: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.content: Optional[str] = payload.get("content") + self.metadata: Optional[Dict[str, object]] = payload.get("metadata") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "id": id, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Assistants.V1.ChunkInstance {}>".format(context) + + +class ChunkPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChunkInstance: + """ + Build an instance of ChunkInstance + + :param payload: Payload response from the API + """ + return ChunkInstance(self._version, payload, id=self._solution["id"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.ChunkPage>" + + +class ChunkList(ListResource): + + def __init__(self, version: Version, id: str): + """ + Initialize the ChunkList + + :param version: Version that contains the resource + :param id: The knowledge ID. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Knowledge/{id}/Chunks".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChunkInstance]: + """ + Streams ChunkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChunkInstance]: + """ + Asynchronously streams ChunkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChunkInstance]: + """ + Lists ChunkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChunkInstance]: + """ + Asynchronously lists ChunkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChunkPage: + """ + Retrieve a single page of ChunkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChunkInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChunkPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChunkPage: + """ + Asynchronously retrieve a single page of ChunkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChunkInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChunkPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ChunkPage: + """ + Retrieve a specific page of ChunkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChunkInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChunkPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ChunkPage: + """ + Asynchronously retrieve a specific page of ChunkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChunkInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChunkPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.ChunkList>" diff --git a/twilio/rest/assistants/v1/knowledge/knowledge_status.py b/twilio/rest/assistants/v1/knowledge/knowledge_status.py new file mode 100644 index 0000000000..fedbcaad25 --- /dev/null +++ b/twilio/rest/assistants/v1/knowledge/knowledge_status.py @@ -0,0 +1,196 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class KnowledgeStatusInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. + :ivar status: The status of processing the knowledge source ('QUEUED', 'PROCESSING', 'COMPLETED', 'FAILED') + :ivar last_status: The last status of processing the knowledge source ('QUEUED', 'PROCESSING', 'COMPLETED', 'FAILED') + :ivar date_updated: The date and time in GMT when the Knowledge was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], id: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.status: Optional[str] = payload.get("status") + self.last_status: Optional[str] = payload.get("last_status") + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "id": id, + } + self._context: Optional[KnowledgeStatusContext] = None + + @property + def _proxy(self) -> "KnowledgeStatusContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: KnowledgeStatusContext for this KnowledgeStatusInstance + """ + if self._context is None: + self._context = KnowledgeStatusContext( + self._version, + id=self._solution["id"], + ) + return self._context + + def fetch(self) -> "KnowledgeStatusInstance": + """ + Fetch the KnowledgeStatusInstance + + + :returns: The fetched KnowledgeStatusInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "KnowledgeStatusInstance": + """ + Asynchronous coroutine to fetch the KnowledgeStatusInstance + + + :returns: The fetched KnowledgeStatusInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Assistants.V1.KnowledgeStatusInstance {}>".format(context) + + +class KnowledgeStatusContext(InstanceContext): + + def __init__(self, version: Version, id: str): + """ + Initialize the KnowledgeStatusContext + + :param version: Version that contains the resource + :param id: the Knowledge ID. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Knowledge/{id}/Status".format(**self._solution) + + def fetch(self) -> KnowledgeStatusInstance: + """ + Fetch the KnowledgeStatusInstance + + + :returns: The fetched KnowledgeStatusInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return KnowledgeStatusInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_async(self) -> KnowledgeStatusInstance: + """ + Asynchronous coroutine to fetch the KnowledgeStatusInstance + + + :returns: The fetched KnowledgeStatusInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return KnowledgeStatusInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Assistants.V1.KnowledgeStatusContext {}>".format(context) + + +class KnowledgeStatusList(ListResource): + + def __init__(self, version: Version, id: str): + """ + Initialize the KnowledgeStatusList + + :param version: Version that contains the resource + :param id: the Knowledge ID. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + + def get(self) -> KnowledgeStatusContext: + """ + Constructs a KnowledgeStatusContext + + """ + return KnowledgeStatusContext(self._version, id=self._solution["id"]) + + def __call__(self) -> KnowledgeStatusContext: + """ + Constructs a KnowledgeStatusContext + + """ + return KnowledgeStatusContext(self._version, id=self._solution["id"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.KnowledgeStatusList>" diff --git a/twilio/rest/assistants/v1/policy.py b/twilio/rest/assistants/v1/policy.py new file mode 100644 index 0000000000..63854fb82b --- /dev/null +++ b/twilio/rest/assistants/v1/policy.py @@ -0,0 +1,332 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PolicyInstance(InstanceResource): + """ + :ivar id: The Policy ID. + :ivar name: The name of the policy. + :ivar description: The description of the policy. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Policy resource. + :ivar user_sid: The SID of the User that created the Policy resource. + :ivar type: The type of the policy. + :ivar policy_details: The details of the policy based on the type. + :ivar date_created: The date and time in GMT when the Policy was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Policy was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.description: Optional[str] = payload.get("description") + self.account_sid: Optional[str] = payload.get("account_sid") + self.user_sid: Optional[str] = payload.get("user_sid") + self.type: Optional[str] = payload.get("type") + self.policy_details: Optional[Dict[str, object]] = payload.get("policy_details") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Assistants.V1.PolicyInstance>" + + +class PolicyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PolicyInstance: + """ + Build an instance of PolicyInstance + + :param payload: Payload response from the API + """ + return PolicyInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.PolicyPage>" + + +class PolicyList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PolicyList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Policies" + + def stream( + self, + tool_id: Union[str, object] = values.unset, + knowledge_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PolicyInstance]: + """ + Streams PolicyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str tool_id: The tool ID. + :param str knowledge_id: The knowledge ID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + tool_id=tool_id, knowledge_id=knowledge_id, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + tool_id: Union[str, object] = values.unset, + knowledge_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PolicyInstance]: + """ + Asynchronously streams PolicyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str tool_id: The tool ID. + :param str knowledge_id: The knowledge ID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + tool_id=tool_id, knowledge_id=knowledge_id, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + tool_id: Union[str, object] = values.unset, + knowledge_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PolicyInstance]: + """ + Lists PolicyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str tool_id: The tool ID. + :param str knowledge_id: The knowledge ID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + tool_id=tool_id, + knowledge_id=knowledge_id, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + tool_id: Union[str, object] = values.unset, + knowledge_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PolicyInstance]: + """ + Asynchronously lists PolicyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str tool_id: The tool ID. + :param str knowledge_id: The knowledge ID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + tool_id=tool_id, + knowledge_id=knowledge_id, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + tool_id: Union[str, object] = values.unset, + knowledge_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PolicyPage: + """ + Retrieve a single page of PolicyInstance records from the API. + Request is executed immediately + + :param tool_id: The tool ID. + :param knowledge_id: The knowledge ID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PolicyInstance + """ + data = values.of( + { + "ToolId": tool_id, + "KnowledgeId": knowledge_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PolicyPage(self._version, response) + + async def page_async( + self, + tool_id: Union[str, object] = values.unset, + knowledge_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PolicyPage: + """ + Asynchronously retrieve a single page of PolicyInstance records from the API. + Request is executed immediately + + :param tool_id: The tool ID. + :param knowledge_id: The knowledge ID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PolicyInstance + """ + data = values.of( + { + "ToolId": tool_id, + "KnowledgeId": knowledge_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PolicyPage(self._version, response) + + def get_page(self, target_url: str) -> PolicyPage: + """ + Retrieve a specific page of PolicyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PolicyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PolicyPage(self._version, response) + + async def get_page_async(self, target_url: str) -> PolicyPage: + """ + Asynchronously retrieve a specific page of PolicyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PolicyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PolicyPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.PolicyList>" diff --git a/twilio/rest/assistants/v1/session/__init__.py b/twilio/rest/assistants/v1/session/__init__.py new file mode 100644 index 0000000000..3f0054ea55 --- /dev/null +++ b/twilio/rest/assistants/v1/session/__init__.py @@ -0,0 +1,439 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.assistants.v1.session.message import MessageList + + +class SessionInstance(InstanceResource): + """ + :ivar id: The Session ID. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Session resource. + :ivar assistant_id: The Assistant ID. + :ivar verified: True if the session is verified. + :ivar identity: The unique identity of user for the session. + :ivar date_created: The date and time in GMT when the Session was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Session was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], id: Optional[str] = None + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.account_sid: Optional[str] = payload.get("account_sid") + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.verified: Optional[bool] = payload.get("verified") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "id": id or self.id, + } + self._context: Optional[SessionContext] = None + + @property + def _proxy(self) -> "SessionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SessionContext for this SessionInstance + """ + if self._context is None: + self._context = SessionContext( + self._version, + id=self._solution["id"], + ) + return self._context + + def fetch(self) -> "SessionInstance": + """ + Fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SessionInstance": + """ + Asynchronous coroutine to fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + return await self._proxy.fetch_async() + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Assistants.V1.SessionInstance {}>".format(context) + + +class SessionContext(InstanceContext): + + def __init__(self, version: Version, id: str): + """ + Initialize the SessionContext + + :param version: Version that contains the resource + :param id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Sessions/{id}".format(**self._solution) + + self._messages: Optional[MessageList] = None + + def fetch(self) -> SessionInstance: + """ + Fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SessionInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_async(self) -> SessionInstance: + """ + Asynchronous coroutine to fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SessionInstance( + self._version, + payload, + id=self._solution["id"], + ) + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["id"], + ) + return self._messages + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Assistants.V1.SessionContext {}>".format(context) + + +class SessionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SessionInstance: + """ + Build an instance of SessionInstance + + :param payload: Payload response from the API + """ + return SessionInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.SessionPage>" + + +class SessionList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SessionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Sessions" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SessionInstance]: + """ + Streams SessionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SessionInstance]: + """ + Asynchronously streams SessionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SessionInstance]: + """ + Lists SessionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SessionInstance]: + """ + Asynchronously lists SessionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SessionPage: + """ + Retrieve a single page of SessionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SessionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SessionPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SessionPage: + """ + Asynchronously retrieve a single page of SessionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SessionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SessionPage(self._version, response) + + def get_page(self, target_url: str) -> SessionPage: + """ + Retrieve a specific page of SessionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SessionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SessionPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SessionPage: + """ + Asynchronously retrieve a specific page of SessionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SessionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SessionPage(self._version, response) + + def get(self, id: str) -> SessionContext: + """ + Constructs a SessionContext + + :param id: + """ + return SessionContext(self._version, id=id) + + def __call__(self, id: str) -> SessionContext: + """ + Constructs a SessionContext + + :param id: + """ + return SessionContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.SessionList>" diff --git a/twilio/rest/assistants/v1/session/message.py b/twilio/rest/assistants/v1/session/message.py new file mode 100644 index 0000000000..a7ea5ca213 --- /dev/null +++ b/twilio/rest/assistants/v1/session/message.py @@ -0,0 +1,309 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MessageInstance(InstanceResource): + """ + :ivar id: The message ID. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Message resource. + :ivar assistant_id: The Assistant ID. + :ivar session_id: The Session ID. + :ivar identity: The identity of the user. + :ivar role: The role of the user associated with the message. + :ivar content: The content of the message. + :ivar meta: The metadata of the message. + :ivar date_created: The date and time in GMT when the Message was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Message was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], session_id: str): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.account_sid: Optional[str] = payload.get("account_sid") + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.session_id: Optional[str] = payload.get("session_id") + self.identity: Optional[str] = payload.get("identity") + self.role: Optional[str] = payload.get("role") + self.content: Optional[Dict[str, object]] = payload.get("content") + self.meta: Optional[Dict[str, object]] = payload.get("meta") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "session_id": session_id, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Assistants.V1.MessageInstance {}>".format(context) + + +class MessagePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance + + :param payload: Payload response from the API + """ + return MessageInstance( + self._version, payload, session_id=self._solution["session_id"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.MessagePage>" + + +class MessageList(ListResource): + + def __init__(self, version: Version, session_id: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param session_id: Session id or name + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "session_id": session_id, + } + self._uri = "/Sessions/{session_id}/Messages".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: + """ + Streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInstance]: + """ + Asynchronously streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Asynchronously lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MessagePage: + """ + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MessagePage: + """ + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.MessageList>" diff --git a/twilio/rest/assistants/v1/tool.py b/twilio/rest/assistants/v1/tool.py new file mode 100644 index 0000000000..648faca599 --- /dev/null +++ b/twilio/rest/assistants/v1/tool.py @@ -0,0 +1,916 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Assistants + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ToolInstance(InstanceResource): + + class AssistantsV1ServiceCreatePolicyRequest(object): + """ + :ivar description: The description of the policy. + :ivar id: The Policy ID. + :ivar name: The name of the policy. + :ivar policy_details: + :ivar type: The description of the policy. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.policy_details: Optional[Dict[str, object]] = payload.get( + "policy_details" + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "description": self.description, + "id": self.id, + "name": self.name, + "policy_details": self.policy_details, + "type": self.type, + } + + class AssistantsV1ServiceCreateToolRequest(object): + """ + :ivar assistant_id: The Assistant ID. + :ivar description: The description of the tool. + :ivar enabled: True if the tool is enabled. + :ivar meta: The metadata related to method, url, input_schema to used with the Tool. + :ivar name: The name of the tool. + :ivar policy: + :ivar type: The description of the tool. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.description: Optional[str] = payload.get("description") + self.enabled: Optional[bool] = payload.get("enabled") + self.meta: Optional[Dict[str, object]] = payload.get("meta") + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ToolList.AssistantsV1ServiceCreatePolicyRequest] = ( + payload.get("policy") + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "assistant_id": self.assistant_id, + "description": self.description, + "enabled": self.enabled, + "meta": self.meta, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + } + + class AssistantsV1ServiceUpdateToolRequest(object): + """ + :ivar assistant_id: The Assistant ID. + :ivar description: The description of the tool. + :ivar enabled: True if the tool is enabled. + :ivar meta: The metadata related to method, url, input_schema to used with the Tool. + :ivar name: The name of the tool. + :ivar policy: + :ivar type: The type of the tool. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.description: Optional[str] = payload.get("description") + self.enabled: Optional[bool] = payload.get("enabled") + self.meta: Optional[Dict[str, object]] = payload.get("meta") + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ToolList.AssistantsV1ServiceCreatePolicyRequest] = ( + payload.get("policy") + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "assistant_id": self.assistant_id, + "description": self.description, + "enabled": self.enabled, + "meta": self.meta, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + } + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Tool resource. + :ivar description: The description of the tool. + :ivar enabled: True if the tool is enabled. + :ivar id: The tool ID. + :ivar meta: The metadata related to method, url, input_schema to used with the Tool. + :ivar name: The name of the tool. + :ivar requires_auth: The authentication requirement for the tool. + :ivar type: The type of the tool. ('WEBHOOK') + :ivar url: The url of the tool resource. + :ivar date_created: The date and time in GMT when the Tool was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Tool was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar policies: The Policies associated with the tool. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], id: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.description: Optional[str] = payload.get("description") + self.enabled: Optional[bool] = payload.get("enabled") + self.id: Optional[str] = payload.get("id") + self.meta: Optional[Dict[str, object]] = payload.get("meta") + self.name: Optional[str] = payload.get("name") + self.requires_auth: Optional[bool] = payload.get("requires_auth") + self.type: Optional[str] = payload.get("type") + self.url: Optional[str] = payload.get("url") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.policies: Optional[List[str]] = payload.get("policies") + + self._solution = { + "id": id or self.id, + } + self._context: Optional[ToolContext] = None + + @property + def _proxy(self) -> "ToolContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ToolContext for this ToolInstance + """ + if self._context is None: + self._context = ToolContext( + self._version, + id=self._solution["id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ToolInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ToolInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ToolInstance": + """ + Fetch the ToolInstance + + + :returns: The fetched ToolInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ToolInstance": + """ + Asynchronous coroutine to fetch the ToolInstance + + + :returns: The fetched ToolInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + assistants_v1_service_update_tool_request: Union[ + AssistantsV1ServiceUpdateToolRequest, object + ] = values.unset, + ) -> "ToolInstance": + """ + Update the ToolInstance + + :param assistants_v1_service_update_tool_request: + + :returns: The updated ToolInstance + """ + return self._proxy.update( + assistants_v1_service_update_tool_request=assistants_v1_service_update_tool_request, + ) + + async def update_async( + self, + assistants_v1_service_update_tool_request: Union[ + AssistantsV1ServiceUpdateToolRequest, object + ] = values.unset, + ) -> "ToolInstance": + """ + Asynchronous coroutine to update the ToolInstance + + :param assistants_v1_service_update_tool_request: + + :returns: The updated ToolInstance + """ + return await self._proxy.update_async( + assistants_v1_service_update_tool_request=assistants_v1_service_update_tool_request, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Assistants.V1.ToolInstance {}>".format(context) + + +class ToolContext(InstanceContext): + + class AssistantsV1ServiceCreatePolicyRequest(object): + """ + :ivar description: The description of the policy. + :ivar id: The Policy ID. + :ivar name: The name of the policy. + :ivar policy_details: + :ivar type: The description of the policy. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.policy_details: Optional[Dict[str, object]] = payload.get( + "policy_details" + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "description": self.description, + "id": self.id, + "name": self.name, + "policy_details": self.policy_details, + "type": self.type, + } + + class AssistantsV1ServiceCreateToolRequest(object): + """ + :ivar assistant_id: The Assistant ID. + :ivar description: The description of the tool. + :ivar enabled: True if the tool is enabled. + :ivar meta: The metadata related to method, url, input_schema to used with the Tool. + :ivar name: The name of the tool. + :ivar policy: + :ivar type: The description of the tool. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.description: Optional[str] = payload.get("description") + self.enabled: Optional[bool] = payload.get("enabled") + self.meta: Optional[Dict[str, object]] = payload.get("meta") + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ToolList.AssistantsV1ServiceCreatePolicyRequest] = ( + payload.get("policy") + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "assistant_id": self.assistant_id, + "description": self.description, + "enabled": self.enabled, + "meta": self.meta, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + } + + class AssistantsV1ServiceUpdateToolRequest(object): + """ + :ivar assistant_id: The Assistant ID. + :ivar description: The description of the tool. + :ivar enabled: True if the tool is enabled. + :ivar meta: The metadata related to method, url, input_schema to used with the Tool. + :ivar name: The name of the tool. + :ivar policy: + :ivar type: The type of the tool. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.description: Optional[str] = payload.get("description") + self.enabled: Optional[bool] = payload.get("enabled") + self.meta: Optional[Dict[str, object]] = payload.get("meta") + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ToolList.AssistantsV1ServiceCreatePolicyRequest] = ( + payload.get("policy") + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "assistant_id": self.assistant_id, + "description": self.description, + "enabled": self.enabled, + "meta": self.meta, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + } + + def __init__(self, version: Version, id: str): + """ + Initialize the ToolContext + + :param version: Version that contains the resource + :param id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Tools/{id}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the ToolInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ToolInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ToolInstance: + """ + Fetch the ToolInstance + + + :returns: The fetched ToolInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ToolInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_async(self) -> ToolInstance: + """ + Asynchronous coroutine to fetch the ToolInstance + + + :returns: The fetched ToolInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ToolInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def update( + self, + assistants_v1_service_update_tool_request: Union[ + AssistantsV1ServiceUpdateToolRequest, object + ] = values.unset, + ) -> ToolInstance: + """ + Update the ToolInstance + + :param assistants_v1_service_update_tool_request: + + :returns: The updated ToolInstance + """ + data = assistants_v1_service_update_tool_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + return ToolInstance(self._version, payload, id=self._solution["id"]) + + async def update_async( + self, + assistants_v1_service_update_tool_request: Union[ + AssistantsV1ServiceUpdateToolRequest, object + ] = values.unset, + ) -> ToolInstance: + """ + Asynchronous coroutine to update the ToolInstance + + :param assistants_v1_service_update_tool_request: + + :returns: The updated ToolInstance + """ + data = assistants_v1_service_update_tool_request.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + return ToolInstance(self._version, payload, id=self._solution["id"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Assistants.V1.ToolContext {}>".format(context) + + +class ToolPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ToolInstance: + """ + Build an instance of ToolInstance + + :param payload: Payload response from the API + """ + return ToolInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.ToolPage>" + + +class ToolList(ListResource): + + class AssistantsV1ServiceCreatePolicyRequest(object): + """ + :ivar description: The description of the policy. + :ivar id: The Policy ID. + :ivar name: The name of the policy. + :ivar policy_details: + :ivar type: The description of the policy. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.description: Optional[str] = payload.get("description") + self.id: Optional[str] = payload.get("id") + self.name: Optional[str] = payload.get("name") + self.policy_details: Optional[Dict[str, object]] = payload.get( + "policy_details" + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "description": self.description, + "id": self.id, + "name": self.name, + "policy_details": self.policy_details, + "type": self.type, + } + + class AssistantsV1ServiceCreateToolRequest(object): + """ + :ivar assistant_id: The Assistant ID. + :ivar description: The description of the tool. + :ivar enabled: True if the tool is enabled. + :ivar meta: The metadata related to method, url, input_schema to used with the Tool. + :ivar name: The name of the tool. + :ivar policy: + :ivar type: The description of the tool. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.description: Optional[str] = payload.get("description") + self.enabled: Optional[bool] = payload.get("enabled") + self.meta: Optional[Dict[str, object]] = payload.get("meta") + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ToolList.AssistantsV1ServiceCreatePolicyRequest] = ( + payload.get("policy") + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "assistant_id": self.assistant_id, + "description": self.description, + "enabled": self.enabled, + "meta": self.meta, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + } + + class AssistantsV1ServiceUpdateToolRequest(object): + """ + :ivar assistant_id: The Assistant ID. + :ivar description: The description of the tool. + :ivar enabled: True if the tool is enabled. + :ivar meta: The metadata related to method, url, input_schema to used with the Tool. + :ivar name: The name of the tool. + :ivar policy: + :ivar type: The type of the tool. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.assistant_id: Optional[str] = payload.get("assistant_id") + self.description: Optional[str] = payload.get("description") + self.enabled: Optional[bool] = payload.get("enabled") + self.meta: Optional[Dict[str, object]] = payload.get("meta") + self.name: Optional[str] = payload.get("name") + self.policy: Optional[ToolList.AssistantsV1ServiceCreatePolicyRequest] = ( + payload.get("policy") + ) + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "assistant_id": self.assistant_id, + "description": self.description, + "enabled": self.enabled, + "meta": self.meta, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + } + + def __init__(self, version: Version): + """ + Initialize the ToolList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Tools" + + def create( + self, + assistants_v1_service_create_tool_request: AssistantsV1ServiceCreateToolRequest, + ) -> ToolInstance: + """ + Create the ToolInstance + + :param assistants_v1_service_create_tool_request: + + :returns: The created ToolInstance + """ + data = assistants_v1_service_create_tool_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ToolInstance(self._version, payload) + + async def create_async( + self, + assistants_v1_service_create_tool_request: AssistantsV1ServiceCreateToolRequest, + ) -> ToolInstance: + """ + Asynchronously create the ToolInstance + + :param assistants_v1_service_create_tool_request: + + :returns: The created ToolInstance + """ + data = assistants_v1_service_create_tool_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ToolInstance(self._version, payload) + + def stream( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ToolInstance]: + """ + Streams ToolInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str assistant_id: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(assistant_id=assistant_id, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ToolInstance]: + """ + Asynchronously streams ToolInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str assistant_id: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + assistant_id=assistant_id, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ToolInstance]: + """ + Lists ToolInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str assistant_id: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + assistant_id=assistant_id, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ToolInstance]: + """ + Asynchronously lists ToolInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str assistant_id: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + assistant_id=assistant_id, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + assistant_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ToolPage: + """ + Retrieve a single page of ToolInstance records from the API. + Request is executed immediately + + :param assistant_id: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ToolInstance + """ + data = values.of( + { + "AssistantId": assistant_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ToolPage(self._version, response) + + async def page_async( + self, + assistant_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ToolPage: + """ + Asynchronously retrieve a single page of ToolInstance records from the API. + Request is executed immediately + + :param assistant_id: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ToolInstance + """ + data = values.of( + { + "AssistantId": assistant_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ToolPage(self._version, response) + + def get_page(self, target_url: str) -> ToolPage: + """ + Retrieve a specific page of ToolInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ToolInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ToolPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ToolPage: + """ + Asynchronously retrieve a specific page of ToolInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ToolInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ToolPage(self._version, response) + + def get(self, id: str) -> ToolContext: + """ + Constructs a ToolContext + + :param id: + """ + return ToolContext(self._version, id=id) + + def __call__(self, id: str) -> ToolContext: + """ + Constructs a ToolContext + + :param id: + """ + return ToolContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Assistants.V1.ToolList>" diff --git a/twilio/rest/bulkexports/BulkexportsBase.py b/twilio/rest/bulkexports/BulkexportsBase.py new file mode 100644 index 0000000000..cbca4c53e4 --- /dev/null +++ b/twilio/rest/bulkexports/BulkexportsBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.bulkexports.v1 import V1 + + +class BulkexportsBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Bulkexports Domain + + :returns: Domain for Bulkexports + """ + super().__init__(twilio, "https://bulkexports.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Bulkexports + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Bulkexports>" diff --git a/twilio/rest/bulkexports/__init__.py b/twilio/rest/bulkexports/__init__.py new file mode 100644 index 0000000000..3a28fb5744 --- /dev/null +++ b/twilio/rest/bulkexports/__init__.py @@ -0,0 +1,25 @@ +from warnings import warn + +from twilio.rest.bulkexports.BulkexportsBase import BulkexportsBase +from twilio.rest.bulkexports.v1.export import ExportList +from twilio.rest.bulkexports.v1.export_configuration import ExportConfigurationList + + +class Bulkexports(BulkexportsBase): + @property + def exports(self) -> ExportList: + warn( + "exports is deprecated. Use v1.exports instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.exports + + @property + def export_configuration(self) -> ExportConfigurationList: + warn( + "export_configuration is deprecated. Use v1.export_configuration instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.export_configuration diff --git a/twilio/rest/bulkexports/v1/__init__.py b/twilio/rest/bulkexports/v1/__init__.py new file mode 100644 index 0000000000..a888fb484f --- /dev/null +++ b/twilio/rest/bulkexports/v1/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Bulkexports + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.bulkexports.v1.export import ExportList +from twilio.rest.bulkexports.v1.export_configuration import ExportConfigurationList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Bulkexports + + :param domain: The Twilio.bulkexports domain + """ + super().__init__(domain, "v1") + self._exports: Optional[ExportList] = None + self._export_configuration: Optional[ExportConfigurationList] = None + + @property + def exports(self) -> ExportList: + if self._exports is None: + self._exports = ExportList(self) + return self._exports + + @property + def export_configuration(self) -> ExportConfigurationList: + if self._export_configuration is None: + self._export_configuration = ExportConfigurationList(self) + return self._export_configuration + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Bulkexports.V1>" diff --git a/twilio/rest/bulkexports/v1/export/__init__.py b/twilio/rest/bulkexports/v1/export/__init__.py new file mode 100644 index 0000000000..0ebf3a451b --- /dev/null +++ b/twilio/rest/bulkexports/v1/export/__init__.py @@ -0,0 +1,250 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Bulkexports + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.bulkexports.v1.export.day import DayList +from twilio.rest.bulkexports.v1.export.export_custom_job import ExportCustomJobList +from twilio.rest.bulkexports.v1.export.job import JobList + + +class ExportInstance(InstanceResource): + """ + :ivar resource_type: The type of communication – Messages, Calls, Conferences, and Participants + :ivar url: The URL of this resource. + :ivar links: Contains a dictionary of URL links to nested resources of this Export. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + resource_type: Optional[str] = None, + ): + super().__init__(version) + + self.resource_type: Optional[str] = payload.get("resource_type") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "resource_type": resource_type or self.resource_type, + } + self._context: Optional[ExportContext] = None + + @property + def _proxy(self) -> "ExportContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ExportContext for this ExportInstance + """ + if self._context is None: + self._context = ExportContext( + self._version, + resource_type=self._solution["resource_type"], + ) + return self._context + + def fetch(self) -> "ExportInstance": + """ + Fetch the ExportInstance + + + :returns: The fetched ExportInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExportInstance": + """ + Asynchronous coroutine to fetch the ExportInstance + + + :returns: The fetched ExportInstance + """ + return await self._proxy.fetch_async() + + @property + def days(self) -> DayList: + """ + Access the days + """ + return self._proxy.days + + @property + def export_custom_jobs(self) -> ExportCustomJobList: + """ + Access the export_custom_jobs + """ + return self._proxy.export_custom_jobs + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Bulkexports.V1.ExportInstance {}>".format(context) + + +class ExportContext(InstanceContext): + + def __init__(self, version: Version, resource_type: str): + """ + Initialize the ExportContext + + :param version: Version that contains the resource + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants + """ + super().__init__(version) + + # Path Solution + self._solution = { + "resource_type": resource_type, + } + self._uri = "/Exports/{resource_type}".format(**self._solution) + + self._days: Optional[DayList] = None + self._export_custom_jobs: Optional[ExportCustomJobList] = None + + def fetch(self) -> ExportInstance: + """ + Fetch the ExportInstance + + + :returns: The fetched ExportInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExportInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + ) + + async def fetch_async(self) -> ExportInstance: + """ + Asynchronous coroutine to fetch the ExportInstance + + + :returns: The fetched ExportInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExportInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + ) + + @property + def days(self) -> DayList: + """ + Access the days + """ + if self._days is None: + self._days = DayList( + self._version, + self._solution["resource_type"], + ) + return self._days + + @property + def export_custom_jobs(self) -> ExportCustomJobList: + """ + Access the export_custom_jobs + """ + if self._export_custom_jobs is None: + self._export_custom_jobs = ExportCustomJobList( + self._version, + self._solution["resource_type"], + ) + return self._export_custom_jobs + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Bulkexports.V1.ExportContext {}>".format(context) + + +class ExportList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ExportList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Exports" + + self._jobs: Optional[JobList] = None + + @property + def jobs(self) -> JobList: + """ + Access the jobs + """ + if self._jobs is None: + self._jobs = JobList(self._version) + return self._jobs + + def get(self, resource_type: str) -> ExportContext: + """ + Constructs a ExportContext + + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants + """ + return ExportContext(self._version, resource_type=resource_type) + + def __call__(self, resource_type: str) -> ExportContext: + """ + Constructs a ExportContext + + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants + """ + return ExportContext(self._version, resource_type=resource_type) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Bulkexports.V1.ExportList>" diff --git a/twilio/rest/bulkexports/v1/export/day.py b/twilio/rest/bulkexports/v1/export/day.py new file mode 100644 index 0000000000..f4b2a0650f --- /dev/null +++ b/twilio/rest/bulkexports/v1/export/day.py @@ -0,0 +1,431 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Bulkexports + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DayInstance(InstanceResource): + """ + :ivar redirect_to: + :ivar day: The ISO 8601 format date of the resources in the file, for a UTC day + :ivar size: The size of the day's data file in bytes + :ivar create_date: The ISO 8601 format date when resources is created + :ivar friendly_name: The friendly name specified when creating the job + :ivar resource_type: The type of communication – Messages, Calls, Conferences, and Participants + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + resource_type: str, + day: Optional[str] = None, + ): + super().__init__(version) + + self.redirect_to: Optional[str] = payload.get("redirect_to") + self.day: Optional[str] = payload.get("day") + self.size: Optional[int] = deserialize.integer(payload.get("size")) + self.create_date: Optional[str] = payload.get("create_date") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.resource_type: Optional[str] = payload.get("resource_type") + + self._solution = { + "resource_type": resource_type, + "day": day or self.day, + } + self._context: Optional[DayContext] = None + + @property + def _proxy(self) -> "DayContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DayContext for this DayInstance + """ + if self._context is None: + self._context = DayContext( + self._version, + resource_type=self._solution["resource_type"], + day=self._solution["day"], + ) + return self._context + + def fetch(self) -> "DayInstance": + """ + Fetch the DayInstance + + + :returns: The fetched DayInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DayInstance": + """ + Asynchronous coroutine to fetch the DayInstance + + + :returns: The fetched DayInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Bulkexports.V1.DayInstance {}>".format(context) + + +class DayContext(InstanceContext): + + def __init__(self, version: Version, resource_type: str, day: str): + """ + Initialize the DayContext + + :param version: Version that contains the resource + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants + :param day: The ISO 8601 format date of the resources in the file, for a UTC day + """ + super().__init__(version) + + # Path Solution + self._solution = { + "resource_type": resource_type, + "day": day, + } + self._uri = "/Exports/{resource_type}/Days/{day}".format(**self._solution) + + def fetch(self) -> DayInstance: + """ + Fetch the DayInstance + + + :returns: The fetched DayInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DayInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + day=self._solution["day"], + ) + + async def fetch_async(self) -> DayInstance: + """ + Asynchronous coroutine to fetch the DayInstance + + + :returns: The fetched DayInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DayInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + day=self._solution["day"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Bulkexports.V1.DayContext {}>".format(context) + + +class DayPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DayInstance: + """ + Build an instance of DayInstance + + :param payload: Payload response from the API + """ + return DayInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Bulkexports.V1.DayPage>" + + +class DayList(ListResource): + + def __init__(self, version: Version, resource_type: str): + """ + Initialize the DayList + + :param version: Version that contains the resource + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "resource_type": resource_type, + } + self._uri = "/Exports/{resource_type}/Days".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DayInstance]: + """ + Streams DayInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DayInstance]: + """ + Asynchronously streams DayInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DayInstance]: + """ + Lists DayInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DayInstance]: + """ + Asynchronously lists DayInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DayPage: + """ + Retrieve a single page of DayInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DayInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DayPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DayPage: + """ + Asynchronously retrieve a single page of DayInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DayInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DayPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DayPage: + """ + Retrieve a specific page of DayInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DayInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DayPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DayPage: + """ + Asynchronously retrieve a specific page of DayInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DayInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DayPage(self._version, response, self._solution) + + def get(self, day: str) -> DayContext: + """ + Constructs a DayContext + + :param day: The ISO 8601 format date of the resources in the file, for a UTC day + """ + return DayContext( + self._version, resource_type=self._solution["resource_type"], day=day + ) + + def __call__(self, day: str) -> DayContext: + """ + Constructs a DayContext + + :param day: The ISO 8601 format date of the resources in the file, for a UTC day + """ + return DayContext( + self._version, resource_type=self._solution["resource_type"], day=day + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Bulkexports.V1.DayList>" diff --git a/twilio/rest/bulkexports/v1/export/export_custom_job.py b/twilio/rest/bulkexports/v1/export/export_custom_job.py new file mode 100644 index 0000000000..72d0e9b328 --- /dev/null +++ b/twilio/rest/bulkexports/v1/export/export_custom_job.py @@ -0,0 +1,400 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Bulkexports + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ExportCustomJobInstance(InstanceResource): + """ + :ivar friendly_name: The friendly name specified when creating the job + :ivar resource_type: The type of communication – Messages, Calls, Conferences, and Participants + :ivar start_day: The start day for the custom export specified when creating the job + :ivar end_day: The end day for the export specified when creating the job + :ivar webhook_url: The optional webhook url called on completion of the job. If this is supplied, `WebhookMethod` must also be supplied. + :ivar webhook_method: This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. + :ivar email: The optional email to send the completion notification to + :ivar job_sid: The unique job_sid returned when the custom export was created + :ivar details: The details of a job which is an object that contains an array of status grouped by `status` state. Each `status` object has a `status` string, a count which is the number of days in that `status`, and list of days in that `status`. The day strings are in the format yyyy-MM-dd. As an example, a currently running job may have a status object for COMPLETED and a `status` object for SUBMITTED each with its own count and list of days. + :ivar job_queue_position: This is the job position from the 1st in line. Your queue position will never increase. As jobs ahead of yours in the queue are processed, the queue position number will decrease + :ivar estimated_completion_time: this is the time estimated until your job is complete. This is calculated each time you request the job list. The time is calculated based on the current rate of job completion (which may vary) and your job queue position + """ + + def __init__(self, version: Version, payload: Dict[str, Any], resource_type: str): + super().__init__(version) + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.resource_type: Optional[str] = payload.get("resource_type") + self.start_day: Optional[str] = payload.get("start_day") + self.end_day: Optional[str] = payload.get("end_day") + self.webhook_url: Optional[str] = payload.get("webhook_url") + self.webhook_method: Optional[str] = payload.get("webhook_method") + self.email: Optional[str] = payload.get("email") + self.job_sid: Optional[str] = payload.get("job_sid") + self.details: Optional[Dict[str, object]] = payload.get("details") + self.job_queue_position: Optional[str] = payload.get("job_queue_position") + self.estimated_completion_time: Optional[str] = payload.get( + "estimated_completion_time" + ) + + self._solution = { + "resource_type": resource_type, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Bulkexports.V1.ExportCustomJobInstance {}>".format(context) + + +class ExportCustomJobPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ExportCustomJobInstance: + """ + Build an instance of ExportCustomJobInstance + + :param payload: Payload response from the API + """ + return ExportCustomJobInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Bulkexports.V1.ExportCustomJobPage>" + + +class ExportCustomJobList(ListResource): + + def __init__(self, version: Version, resource_type: str): + """ + Initialize the ExportCustomJobList + + :param version: Version that contains the resource + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "resource_type": resource_type, + } + self._uri = "/Exports/{resource_type}/Jobs".format(**self._solution) + + def create( + self, + start_day: str, + end_day: str, + friendly_name: str, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ExportCustomJobInstance: + """ + Create the ExportCustomJobInstance + + :param start_day: The start day for the custom export specified as a string in the format of yyyy-mm-dd + :param end_day: The end day for the custom export specified as a string in the format of yyyy-mm-dd. End day is inclusive and must be 2 days earlier than the current UTC day. + :param friendly_name: The friendly name specified when creating the job + :param webhook_url: The optional webhook url called on completion of the job. If this is supplied, `WebhookMethod` must also be supplied. If you set neither webhook nor email, you will have to check your job's status manually. + :param webhook_method: This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. + :param email: The optional email to send the completion notification to. You can set both webhook, and email, or one or the other. If you set neither, the job will run but you will have to query to determine your job's status. + + :returns: The created ExportCustomJobInstance + """ + + data = values.of( + { + "StartDay": start_day, + "EndDay": end_day, + "FriendlyName": friendly_name, + "WebhookUrl": webhook_url, + "WebhookMethod": webhook_method, + "Email": email, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExportCustomJobInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + + async def create_async( + self, + start_day: str, + end_day: str, + friendly_name: str, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> ExportCustomJobInstance: + """ + Asynchronously create the ExportCustomJobInstance + + :param start_day: The start day for the custom export specified as a string in the format of yyyy-mm-dd + :param end_day: The end day for the custom export specified as a string in the format of yyyy-mm-dd. End day is inclusive and must be 2 days earlier than the current UTC day. + :param friendly_name: The friendly name specified when creating the job + :param webhook_url: The optional webhook url called on completion of the job. If this is supplied, `WebhookMethod` must also be supplied. If you set neither webhook nor email, you will have to check your job's status manually. + :param webhook_method: This is the method used to call the webhook on completion of the job. If this is supplied, `WebhookUrl` must also be supplied. + :param email: The optional email to send the completion notification to. You can set both webhook, and email, or one or the other. If you set neither, the job will run but you will have to query to determine your job's status. + + :returns: The created ExportCustomJobInstance + """ + + data = values.of( + { + "StartDay": start_day, + "EndDay": end_day, + "FriendlyName": friendly_name, + "WebhookUrl": webhook_url, + "WebhookMethod": webhook_method, + "Email": email, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExportCustomJobInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ExportCustomJobInstance]: + """ + Streams ExportCustomJobInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ExportCustomJobInstance]: + """ + Asynchronously streams ExportCustomJobInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExportCustomJobInstance]: + """ + Lists ExportCustomJobInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExportCustomJobInstance]: + """ + Asynchronously lists ExportCustomJobInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExportCustomJobPage: + """ + Retrieve a single page of ExportCustomJobInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExportCustomJobInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExportCustomJobPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExportCustomJobPage: + """ + Asynchronously retrieve a single page of ExportCustomJobInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExportCustomJobInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExportCustomJobPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ExportCustomJobPage: + """ + Retrieve a specific page of ExportCustomJobInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExportCustomJobInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ExportCustomJobPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ExportCustomJobPage: + """ + Asynchronously retrieve a specific page of ExportCustomJobInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExportCustomJobInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ExportCustomJobPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Bulkexports.V1.ExportCustomJobList>" diff --git a/twilio/rest/bulkexports/v1/export/job.py b/twilio/rest/bulkexports/v1/export/job.py new file mode 100644 index 0000000000..5358ffa83a --- /dev/null +++ b/twilio/rest/bulkexports/v1/export/job.py @@ -0,0 +1,253 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Bulkexports + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class JobInstance(InstanceResource): + """ + :ivar resource_type: The type of communication – Messages, Calls, Conferences, and Participants + :ivar friendly_name: The friendly name specified when creating the job + :ivar details: The details of a job which is an object that contains an array of status grouped by `status` state. Each `status` object has a `status` string, a count which is the number of days in that `status`, and list of days in that `status`. The day strings are in the format yyyy-MM-dd. As an example, a currently running job may have a status object for COMPLETED and a `status` object for SUBMITTED each with its own count and list of days. + :ivar start_day: The start time for the export specified when creating the job + :ivar end_day: The end time for the export specified when creating the job + :ivar job_sid: The job_sid returned when the export was created + :ivar webhook_url: The optional webhook url called on completion + :ivar webhook_method: This is the method used to call the webhook + :ivar email: The optional email to send the completion notification to + :ivar url: + :ivar job_queue_position: This is the job position from the 1st in line. Your queue position will never increase. As jobs ahead of yours in the queue are processed, the queue position number will decrease + :ivar estimated_completion_time: this is the time estimated until your job is complete. This is calculated each time you request the job list. The time is calculated based on the current rate of job completion (which may vary) and your job queue position + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], job_sid: Optional[str] = None + ): + super().__init__(version) + + self.resource_type: Optional[str] = payload.get("resource_type") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.details: Optional[Dict[str, object]] = payload.get("details") + self.start_day: Optional[str] = payload.get("start_day") + self.end_day: Optional[str] = payload.get("end_day") + self.job_sid: Optional[str] = payload.get("job_sid") + self.webhook_url: Optional[str] = payload.get("webhook_url") + self.webhook_method: Optional[str] = payload.get("webhook_method") + self.email: Optional[str] = payload.get("email") + self.url: Optional[str] = payload.get("url") + self.job_queue_position: Optional[str] = payload.get("job_queue_position") + self.estimated_completion_time: Optional[str] = payload.get( + "estimated_completion_time" + ) + + self._solution = { + "job_sid": job_sid or self.job_sid, + } + self._context: Optional[JobContext] = None + + @property + def _proxy(self) -> "JobContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: JobContext for this JobInstance + """ + if self._context is None: + self._context = JobContext( + self._version, + job_sid=self._solution["job_sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the JobInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the JobInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "JobInstance": + """ + Fetch the JobInstance + + + :returns: The fetched JobInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "JobInstance": + """ + Asynchronous coroutine to fetch the JobInstance + + + :returns: The fetched JobInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Bulkexports.V1.JobInstance {}>".format(context) + + +class JobContext(InstanceContext): + + def __init__(self, version: Version, job_sid: str): + """ + Initialize the JobContext + + :param version: Version that contains the resource + :param job_sid: The unique string that that we created to identify the Bulk Export job + """ + super().__init__(version) + + # Path Solution + self._solution = { + "job_sid": job_sid, + } + self._uri = "/Exports/Jobs/{job_sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the JobInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the JobInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> JobInstance: + """ + Fetch the JobInstance + + + :returns: The fetched JobInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return JobInstance( + self._version, + payload, + job_sid=self._solution["job_sid"], + ) + + async def fetch_async(self) -> JobInstance: + """ + Asynchronous coroutine to fetch the JobInstance + + + :returns: The fetched JobInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return JobInstance( + self._version, + payload, + job_sid=self._solution["job_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Bulkexports.V1.JobContext {}>".format(context) + + +class JobList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the JobList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, job_sid: str) -> JobContext: + """ + Constructs a JobContext + + :param job_sid: The unique string that that we created to identify the Bulk Export job + """ + return JobContext(self._version, job_sid=job_sid) + + def __call__(self, job_sid: str) -> JobContext: + """ + Constructs a JobContext + + :param job_sid: The unique string that that we created to identify the Bulk Export job + """ + return JobContext(self._version, job_sid=job_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Bulkexports.V1.JobList>" diff --git a/twilio/rest/bulkexports/v1/export_configuration.py b/twilio/rest/bulkexports/v1/export_configuration.py new file mode 100644 index 0000000000..207642769b --- /dev/null +++ b/twilio/rest/bulkexports/v1/export_configuration.py @@ -0,0 +1,312 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Bulkexports + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ExportConfigurationInstance(InstanceResource): + """ + :ivar enabled: If true, Twilio will automatically generate every day's file when the day is over. + :ivar webhook_url: Stores the URL destination for the method specified in webhook_method. + :ivar webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url + :ivar resource_type: The type of communication – Messages, Calls, Conferences, and Participants + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + resource_type: Optional[str] = None, + ): + super().__init__(version) + + self.enabled: Optional[bool] = payload.get("enabled") + self.webhook_url: Optional[str] = payload.get("webhook_url") + self.webhook_method: Optional[str] = payload.get("webhook_method") + self.resource_type: Optional[str] = payload.get("resource_type") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "resource_type": resource_type or self.resource_type, + } + self._context: Optional[ExportConfigurationContext] = None + + @property + def _proxy(self) -> "ExportConfigurationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ExportConfigurationContext for this ExportConfigurationInstance + """ + if self._context is None: + self._context = ExportConfigurationContext( + self._version, + resource_type=self._solution["resource_type"], + ) + return self._context + + def fetch(self) -> "ExportConfigurationInstance": + """ + Fetch the ExportConfigurationInstance + + + :returns: The fetched ExportConfigurationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExportConfigurationInstance": + """ + Asynchronous coroutine to fetch the ExportConfigurationInstance + + + :returns: The fetched ExportConfigurationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> "ExportConfigurationInstance": + """ + Update the ExportConfigurationInstance + + :param enabled: If true, Twilio will automatically generate every day's file when the day is over. + :param webhook_url: Stores the URL destination for the method specified in webhook_method. + :param webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url + + :returns: The updated ExportConfigurationInstance + """ + return self._proxy.update( + enabled=enabled, + webhook_url=webhook_url, + webhook_method=webhook_method, + ) + + async def update_async( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> "ExportConfigurationInstance": + """ + Asynchronous coroutine to update the ExportConfigurationInstance + + :param enabled: If true, Twilio will automatically generate every day's file when the day is over. + :param webhook_url: Stores the URL destination for the method specified in webhook_method. + :param webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url + + :returns: The updated ExportConfigurationInstance + """ + return await self._proxy.update_async( + enabled=enabled, + webhook_url=webhook_url, + webhook_method=webhook_method, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Bulkexports.V1.ExportConfigurationInstance {}>".format(context) + + +class ExportConfigurationContext(InstanceContext): + + def __init__(self, version: Version, resource_type: str): + """ + Initialize the ExportConfigurationContext + + :param version: Version that contains the resource + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants + """ + super().__init__(version) + + # Path Solution + self._solution = { + "resource_type": resource_type, + } + self._uri = "/Exports/{resource_type}/Configuration".format(**self._solution) + + def fetch(self) -> ExportConfigurationInstance: + """ + Fetch the ExportConfigurationInstance + + + :returns: The fetched ExportConfigurationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExportConfigurationInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + ) + + async def fetch_async(self) -> ExportConfigurationInstance: + """ + Asynchronous coroutine to fetch the ExportConfigurationInstance + + + :returns: The fetched ExportConfigurationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExportConfigurationInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + ) + + def update( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> ExportConfigurationInstance: + """ + Update the ExportConfigurationInstance + + :param enabled: If true, Twilio will automatically generate every day's file when the day is over. + :param webhook_url: Stores the URL destination for the method specified in webhook_method. + :param webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url + + :returns: The updated ExportConfigurationInstance + """ + + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + "WebhookUrl": webhook_url, + "WebhookMethod": webhook_method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExportConfigurationInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + + async def update_async( + self, + enabled: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + ) -> ExportConfigurationInstance: + """ + Asynchronous coroutine to update the ExportConfigurationInstance + + :param enabled: If true, Twilio will automatically generate every day's file when the day is over. + :param webhook_url: Stores the URL destination for the method specified in webhook_method. + :param webhook_method: Sets whether Twilio should call a webhook URL when the automatic generation is complete, using GET or POST. The actual destination is set in the webhook_url + + :returns: The updated ExportConfigurationInstance + """ + + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + "WebhookUrl": webhook_url, + "WebhookMethod": webhook_method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExportConfigurationInstance( + self._version, payload, resource_type=self._solution["resource_type"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Bulkexports.V1.ExportConfigurationContext {}>".format(context) + + +class ExportConfigurationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ExportConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, resource_type: str) -> ExportConfigurationContext: + """ + Constructs a ExportConfigurationContext + + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants + """ + return ExportConfigurationContext(self._version, resource_type=resource_type) + + def __call__(self, resource_type: str) -> ExportConfigurationContext: + """ + Constructs a ExportConfigurationContext + + :param resource_type: The type of communication – Messages, Calls, Conferences, and Participants + """ + return ExportConfigurationContext(self._version, resource_type=resource_type) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Bulkexports.V1.ExportConfigurationList>" diff --git a/twilio/rest/chat/ChatBase.py b/twilio/rest/chat/ChatBase.py new file mode 100644 index 0000000000..6d8656da17 --- /dev/null +++ b/twilio/rest/chat/ChatBase.py @@ -0,0 +1,66 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.chat.v1 import V1 +from twilio.rest.chat.v2 import V2 +from twilio.rest.chat.v3 import V3 + + +class ChatBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Chat Domain + + :returns: Domain for Chat + """ + super().__init__(twilio, "https://chat.twilio.com") + self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + self._v3: Optional[V3] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Chat + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Chat + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + @property + def v3(self) -> V3: + """ + :returns: Versions v3 of Chat + """ + if self._v3 is None: + self._v3 = V3(self) + return self._v3 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Chat>" diff --git a/twilio/rest/chat/__init__.py b/twilio/rest/chat/__init__.py new file mode 100644 index 0000000000..9608a0fd87 --- /dev/null +++ b/twilio/rest/chat/__init__.py @@ -0,0 +1,35 @@ +from warnings import warn + +from twilio.rest.chat.ChatBase import ChatBase +from twilio.rest.chat.v2.credential import CredentialList +from twilio.rest.chat.v2.service import ServiceList +from twilio.rest.chat.v3.channel import ChannelList + + +class Chat(ChatBase): + @property + def credentials(self) -> CredentialList: + warn( + "credentials is deprecated. Use v2.credentials instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.credentials + + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v2.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.services + + @property + def channels(self) -> ChannelList: + warn( + "channels is deprecated. Use v3.channels instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v3.channels diff --git a/twilio/rest/chat/v1/__init__.py b/twilio/rest/chat/v1/__init__.py new file mode 100644 index 0000000000..d0ade9eed5 --- /dev/null +++ b/twilio/rest/chat/v1/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.chat.v1.credential import CredentialList +from twilio.rest.chat.v1.service import ServiceList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Chat + + :param domain: The Twilio.chat domain + """ + super().__init__(domain, "v1") + self._credentials: Optional[CredentialList] = None + self._services: Optional[ServiceList] = None + + @property + def credentials(self) -> CredentialList: + if self._credentials is None: + self._credentials = CredentialList(self) + return self._credentials + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V1>" diff --git a/twilio/rest/chat/v1/credential.py b/twilio/rest/chat/v1/credential.py new file mode 100644 index 0000000000..3bd48b1144 --- /dev/null +++ b/twilio/rest/chat/v1/credential.py @@ -0,0 +1,711 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CredentialInstance(InstanceResource): + + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: The unique string that we created to identify the Credential resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Credential resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the Credential resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushService"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None + + @property + def _proxy(self) -> "CredentialContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CredentialInstance": + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialInstance": + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V1.CredentialInstance {}>".format(context) + + +class CredentialContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CredentialContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V1.CredentialContext {}>".format(context) + + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance + + :param payload: Payload response from the API + """ + return CredentialInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V1.CredentialPage>" + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Credentials" + + def create( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + async def create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR. -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialInstance]: + """ + Streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: + """ + Asynchronously streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Asynchronously lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Asynchronously retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + def get_page(self, target_url: str) -> CredentialPage: + """ + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CredentialPage: + """ + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) + + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. + """ + return CredentialContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. + """ + return CredentialContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V1.CredentialList>" diff --git a/twilio/rest/chat/v1/service/__init__.py b/twilio/rest/chat/v1/service/__init__.py new file mode 100644 index 0000000000..26fde4025b --- /dev/null +++ b/twilio/rest/chat/v1/service/__init__.py @@ -0,0 +1,1359 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.chat.v1.service.channel import ChannelList +from twilio.rest.chat.v1.service.role import RoleList +from twilio.rest.chat.v1.service.user import UserList + + +class ServiceInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Service resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Service resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar default_service_role_sid: The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :ivar default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :ivar default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :ivar read_status_enabled: Whether the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature is enabled. The default is `true`. + :ivar reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) is enabled for this Service instance. The default is `false`. + :ivar typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :ivar consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :ivar limits: An object that describes the limits of the service instance. The `limits` object contains `channel_members` to describe the members/channel limit and `user_channels` to describe the channels/user limit. `channel_members` can be 1,000 or less, with a default of 250. `user_channels` can be 1,000 or less, with a default value of 100. + :ivar webhooks: An object that contains information about the webhooks configured for this service. + :ivar pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :ivar post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :ivar webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :ivar webhook_filters: The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :ivar notifications: The notification configuration for the Service instance. See [Push Notification Configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more information. + :ivar url: The absolute URL of the Service resource. + :ivar links: The absolute URLs of the Service's [Channels](https://www.twilio.com/docs/chat/api/channels), [Roles](https://www.twilio.com/docs/chat/api/roles), and [Users](https://www.twilio.com/docs/chat/api/users). + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.default_service_role_sid: Optional[str] = payload.get( + "default_service_role_sid" + ) + self.default_channel_role_sid: Optional[str] = payload.get( + "default_channel_role_sid" + ) + self.default_channel_creator_role_sid: Optional[str] = payload.get( + "default_channel_creator_role_sid" + ) + self.read_status_enabled: Optional[bool] = payload.get("read_status_enabled") + self.reachability_enabled: Optional[bool] = payload.get("reachability_enabled") + self.typing_indicator_timeout: Optional[int] = deserialize.integer( + payload.get("typing_indicator_timeout") + ) + self.consumption_report_interval: Optional[int] = deserialize.integer( + payload.get("consumption_report_interval") + ) + self.limits: Optional[Dict[str, object]] = payload.get("limits") + self.webhooks: Optional[Dict[str, object]] = payload.get("webhooks") + self.pre_webhook_url: Optional[str] = payload.get("pre_webhook_url") + self.post_webhook_url: Optional[str] = payload.get("post_webhook_url") + self.webhook_method: Optional[str] = payload.get("webhook_method") + self.webhook_filters: Optional[List[str]] = payload.get("webhook_filters") + self.notifications: Optional[Dict[str, object]] = payload.get("notifications") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhooks_on_message_send_url: The URL of the webhook to call in response to the `on_message_send` event using the `webhooks.on_message_send.method` HTTP method. + :param webhooks_on_message_send_method: The HTTP method to use when calling the `webhooks.on_message_send.url`. + :param webhooks_on_message_update_url: The URL of the webhook to call in response to the `on_message_update` event using the `webhooks.on_message_update.method` HTTP method. + :param webhooks_on_message_update_method: The HTTP method to use when calling the `webhooks.on_message_update.url`. + :param webhooks_on_message_remove_url: The URL of the webhook to call in response to the `on_message_remove` event using the `webhooks.on_message_remove.method` HTTP method. + :param webhooks_on_message_remove_method: The HTTP method to use when calling the `webhooks.on_message_remove.url`. + :param webhooks_on_channel_add_url: The URL of the webhook to call in response to the `on_channel_add` event using the `webhooks.on_channel_add.method` HTTP method. + :param webhooks_on_channel_add_method: The HTTP method to use when calling the `webhooks.on_channel_add.url`. + :param webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the `on_channel_destroy` event using the `webhooks.on_channel_destroy.method` HTTP method. + :param webhooks_on_channel_destroy_method: The HTTP method to use when calling the `webhooks.on_channel_destroy.url`. + :param webhooks_on_channel_update_url: The URL of the webhook to call in response to the `on_channel_update` event using the `webhooks.on_channel_update.method` HTTP method. + :param webhooks_on_channel_update_method: The HTTP method to use when calling the `webhooks.on_channel_update.url`. + :param webhooks_on_member_add_url: The URL of the webhook to call in response to the `on_member_add` event using the `webhooks.on_member_add.method` HTTP method. + :param webhooks_on_member_add_method: The HTTP method to use when calling the `webhooks.on_member_add.url`. + :param webhooks_on_member_remove_url: The URL of the webhook to call in response to the `on_member_remove` event using the `webhooks.on_member_remove.method` HTTP method. + :param webhooks_on_member_remove_method: The HTTP method to use when calling the `webhooks.on_member_remove.url`. + :param webhooks_on_message_sent_url: The URL of the webhook to call in response to the `on_message_sent` event using the `webhooks.on_message_sent.method` HTTP method. + :param webhooks_on_message_sent_method: The URL of the webhook to call in response to the `on_message_sent` event`. + :param webhooks_on_message_updated_url: The URL of the webhook to call in response to the `on_message_updated` event using the `webhooks.on_message_updated.method` HTTP method. + :param webhooks_on_message_updated_method: The HTTP method to use when calling the `webhooks.on_message_updated.url`. + :param webhooks_on_message_removed_url: The URL of the webhook to call in response to the `on_message_removed` event using the `webhooks.on_message_removed.method` HTTP method. + :param webhooks_on_message_removed_method: The HTTP method to use when calling the `webhooks.on_message_removed.url`. + :param webhooks_on_channel_added_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_added.method` HTTP method. + :param webhooks_on_channel_added_method: The URL of the webhook to call in response to the `on_channel_added` event`. + :param webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_destroyed.method` HTTP method. + :param webhooks_on_channel_destroyed_method: The HTTP method to use when calling the `webhooks.on_channel_destroyed.url`. + :param webhooks_on_channel_updated_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_channel_updated_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_added_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_member_added_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_removed_url: The URL of the webhook to call in response to the `on_member_removed` event using the `webhooks.on_member_removed.method` HTTP method. + :param webhooks_on_member_removed_method: The HTTP method to use when calling the `webhooks.on_member_removed.url`. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhooks_on_message_send_url: The URL of the webhook to call in response to the `on_message_send` event using the `webhooks.on_message_send.method` HTTP method. + :param webhooks_on_message_send_method: The HTTP method to use when calling the `webhooks.on_message_send.url`. + :param webhooks_on_message_update_url: The URL of the webhook to call in response to the `on_message_update` event using the `webhooks.on_message_update.method` HTTP method. + :param webhooks_on_message_update_method: The HTTP method to use when calling the `webhooks.on_message_update.url`. + :param webhooks_on_message_remove_url: The URL of the webhook to call in response to the `on_message_remove` event using the `webhooks.on_message_remove.method` HTTP method. + :param webhooks_on_message_remove_method: The HTTP method to use when calling the `webhooks.on_message_remove.url`. + :param webhooks_on_channel_add_url: The URL of the webhook to call in response to the `on_channel_add` event using the `webhooks.on_channel_add.method` HTTP method. + :param webhooks_on_channel_add_method: The HTTP method to use when calling the `webhooks.on_channel_add.url`. + :param webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the `on_channel_destroy` event using the `webhooks.on_channel_destroy.method` HTTP method. + :param webhooks_on_channel_destroy_method: The HTTP method to use when calling the `webhooks.on_channel_destroy.url`. + :param webhooks_on_channel_update_url: The URL of the webhook to call in response to the `on_channel_update` event using the `webhooks.on_channel_update.method` HTTP method. + :param webhooks_on_channel_update_method: The HTTP method to use when calling the `webhooks.on_channel_update.url`. + :param webhooks_on_member_add_url: The URL of the webhook to call in response to the `on_member_add` event using the `webhooks.on_member_add.method` HTTP method. + :param webhooks_on_member_add_method: The HTTP method to use when calling the `webhooks.on_member_add.url`. + :param webhooks_on_member_remove_url: The URL of the webhook to call in response to the `on_member_remove` event using the `webhooks.on_member_remove.method` HTTP method. + :param webhooks_on_member_remove_method: The HTTP method to use when calling the `webhooks.on_member_remove.url`. + :param webhooks_on_message_sent_url: The URL of the webhook to call in response to the `on_message_sent` event using the `webhooks.on_message_sent.method` HTTP method. + :param webhooks_on_message_sent_method: The URL of the webhook to call in response to the `on_message_sent` event`. + :param webhooks_on_message_updated_url: The URL of the webhook to call in response to the `on_message_updated` event using the `webhooks.on_message_updated.method` HTTP method. + :param webhooks_on_message_updated_method: The HTTP method to use when calling the `webhooks.on_message_updated.url`. + :param webhooks_on_message_removed_url: The URL of the webhook to call in response to the `on_message_removed` event using the `webhooks.on_message_removed.method` HTTP method. + :param webhooks_on_message_removed_method: The HTTP method to use when calling the `webhooks.on_message_removed.url`. + :param webhooks_on_channel_added_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_added.method` HTTP method. + :param webhooks_on_channel_added_method: The URL of the webhook to call in response to the `on_channel_added` event`. + :param webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_destroyed.method` HTTP method. + :param webhooks_on_channel_destroyed_method: The HTTP method to use when calling the `webhooks.on_channel_destroyed.url`. + :param webhooks_on_channel_updated_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_channel_updated_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_added_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_member_added_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_removed_url: The URL of the webhook to call in response to the `on_member_removed` event using the `webhooks.on_member_removed.method` HTTP method. + :param webhooks_on_member_removed_method: The HTTP method to use when calling the `webhooks.on_member_removed.url`. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + return self._proxy.channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + return self._proxy.users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V1.ServiceInstance {}>".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._channels: Optional[ChannelList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhooks_on_message_send_url: The URL of the webhook to call in response to the `on_message_send` event using the `webhooks.on_message_send.method` HTTP method. + :param webhooks_on_message_send_method: The HTTP method to use when calling the `webhooks.on_message_send.url`. + :param webhooks_on_message_update_url: The URL of the webhook to call in response to the `on_message_update` event using the `webhooks.on_message_update.method` HTTP method. + :param webhooks_on_message_update_method: The HTTP method to use when calling the `webhooks.on_message_update.url`. + :param webhooks_on_message_remove_url: The URL of the webhook to call in response to the `on_message_remove` event using the `webhooks.on_message_remove.method` HTTP method. + :param webhooks_on_message_remove_method: The HTTP method to use when calling the `webhooks.on_message_remove.url`. + :param webhooks_on_channel_add_url: The URL of the webhook to call in response to the `on_channel_add` event using the `webhooks.on_channel_add.method` HTTP method. + :param webhooks_on_channel_add_method: The HTTP method to use when calling the `webhooks.on_channel_add.url`. + :param webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the `on_channel_destroy` event using the `webhooks.on_channel_destroy.method` HTTP method. + :param webhooks_on_channel_destroy_method: The HTTP method to use when calling the `webhooks.on_channel_destroy.url`. + :param webhooks_on_channel_update_url: The URL of the webhook to call in response to the `on_channel_update` event using the `webhooks.on_channel_update.method` HTTP method. + :param webhooks_on_channel_update_method: The HTTP method to use when calling the `webhooks.on_channel_update.url`. + :param webhooks_on_member_add_url: The URL of the webhook to call in response to the `on_member_add` event using the `webhooks.on_member_add.method` HTTP method. + :param webhooks_on_member_add_method: The HTTP method to use when calling the `webhooks.on_member_add.url`. + :param webhooks_on_member_remove_url: The URL of the webhook to call in response to the `on_member_remove` event using the `webhooks.on_member_remove.method` HTTP method. + :param webhooks_on_member_remove_method: The HTTP method to use when calling the `webhooks.on_member_remove.url`. + :param webhooks_on_message_sent_url: The URL of the webhook to call in response to the `on_message_sent` event using the `webhooks.on_message_sent.method` HTTP method. + :param webhooks_on_message_sent_method: The URL of the webhook to call in response to the `on_message_sent` event`. + :param webhooks_on_message_updated_url: The URL of the webhook to call in response to the `on_message_updated` event using the `webhooks.on_message_updated.method` HTTP method. + :param webhooks_on_message_updated_method: The HTTP method to use when calling the `webhooks.on_message_updated.url`. + :param webhooks_on_message_removed_url: The URL of the webhook to call in response to the `on_message_removed` event using the `webhooks.on_message_removed.method` HTTP method. + :param webhooks_on_message_removed_method: The HTTP method to use when calling the `webhooks.on_message_removed.url`. + :param webhooks_on_channel_added_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_added.method` HTTP method. + :param webhooks_on_channel_added_method: The URL of the webhook to call in response to the `on_channel_added` event`. + :param webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_destroyed.method` HTTP method. + :param webhooks_on_channel_destroyed_method: The HTTP method to use when calling the `webhooks.on_channel_destroyed.url`. + :param webhooks_on_channel_updated_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_channel_updated_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_added_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_member_added_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_removed_url: The URL of the webhook to call in response to the `on_member_removed` event using the `webhooks.on_member_removed.method` HTTP method. + :param webhooks_on_member_removed_method: The HTTP method to use when calling the `webhooks.on_member_removed.url`. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, + "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, + "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, + "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, + "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, + "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, + "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, + "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, + "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, + "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, + "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, + "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, + "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, + "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, + "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, + "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, + "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, + "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, + "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, + "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, + "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, + "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, + "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, + "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, + "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, + "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, + "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, + "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, + "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, + "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, + "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, + "Webhooks.OnMemberRemoved.Method": webhooks_on_member_removed_method, + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Roles endpoint](https://www.twilio.com/docs/chat/api/roles) for more details. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. Can be: `true` or `false` and the default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/api/chat/webhooks) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of WebHook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhooks_on_message_send_url: The URL of the webhook to call in response to the `on_message_send` event using the `webhooks.on_message_send.method` HTTP method. + :param webhooks_on_message_send_method: The HTTP method to use when calling the `webhooks.on_message_send.url`. + :param webhooks_on_message_update_url: The URL of the webhook to call in response to the `on_message_update` event using the `webhooks.on_message_update.method` HTTP method. + :param webhooks_on_message_update_method: The HTTP method to use when calling the `webhooks.on_message_update.url`. + :param webhooks_on_message_remove_url: The URL of the webhook to call in response to the `on_message_remove` event using the `webhooks.on_message_remove.method` HTTP method. + :param webhooks_on_message_remove_method: The HTTP method to use when calling the `webhooks.on_message_remove.url`. + :param webhooks_on_channel_add_url: The URL of the webhook to call in response to the `on_channel_add` event using the `webhooks.on_channel_add.method` HTTP method. + :param webhooks_on_channel_add_method: The HTTP method to use when calling the `webhooks.on_channel_add.url`. + :param webhooks_on_channel_destroy_url: The URL of the webhook to call in response to the `on_channel_destroy` event using the `webhooks.on_channel_destroy.method` HTTP method. + :param webhooks_on_channel_destroy_method: The HTTP method to use when calling the `webhooks.on_channel_destroy.url`. + :param webhooks_on_channel_update_url: The URL of the webhook to call in response to the `on_channel_update` event using the `webhooks.on_channel_update.method` HTTP method. + :param webhooks_on_channel_update_method: The HTTP method to use when calling the `webhooks.on_channel_update.url`. + :param webhooks_on_member_add_url: The URL of the webhook to call in response to the `on_member_add` event using the `webhooks.on_member_add.method` HTTP method. + :param webhooks_on_member_add_method: The HTTP method to use when calling the `webhooks.on_member_add.url`. + :param webhooks_on_member_remove_url: The URL of the webhook to call in response to the `on_member_remove` event using the `webhooks.on_member_remove.method` HTTP method. + :param webhooks_on_member_remove_method: The HTTP method to use when calling the `webhooks.on_member_remove.url`. + :param webhooks_on_message_sent_url: The URL of the webhook to call in response to the `on_message_sent` event using the `webhooks.on_message_sent.method` HTTP method. + :param webhooks_on_message_sent_method: The URL of the webhook to call in response to the `on_message_sent` event`. + :param webhooks_on_message_updated_url: The URL of the webhook to call in response to the `on_message_updated` event using the `webhooks.on_message_updated.method` HTTP method. + :param webhooks_on_message_updated_method: The HTTP method to use when calling the `webhooks.on_message_updated.url`. + :param webhooks_on_message_removed_url: The URL of the webhook to call in response to the `on_message_removed` event using the `webhooks.on_message_removed.method` HTTP method. + :param webhooks_on_message_removed_method: The HTTP method to use when calling the `webhooks.on_message_removed.url`. + :param webhooks_on_channel_added_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_added.method` HTTP method. + :param webhooks_on_channel_added_method: The URL of the webhook to call in response to the `on_channel_added` event`. + :param webhooks_on_channel_destroyed_url: The URL of the webhook to call in response to the `on_channel_added` event using the `webhooks.on_channel_destroyed.method` HTTP method. + :param webhooks_on_channel_destroyed_method: The HTTP method to use when calling the `webhooks.on_channel_destroyed.url`. + :param webhooks_on_channel_updated_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_channel_updated_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_added_url: The URL of the webhook to call in response to the `on_channel_updated` event using the `webhooks.on_channel_updated.method` HTTP method. + :param webhooks_on_member_added_method: The HTTP method to use when calling the `webhooks.on_channel_updated.url`. + :param webhooks_on_member_removed_url: The URL of the webhook to call in response to the `on_member_removed` event using the `webhooks.on_member_removed.method` HTTP method. + :param webhooks_on_member_removed_method: The HTTP method to use when calling the `webhooks.on_member_removed.url`. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, + "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, + "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, + "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, + "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, + "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, + "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, + "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, + "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, + "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, + "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, + "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, + "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, + "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, + "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, + "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, + "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, + "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, + "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, + "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, + "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, + "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, + "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, + "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, + "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, + "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, + "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, + "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, + "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, + "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, + "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, + "Webhooks.OnMemberRemoved.Method": webhooks_on_member_removed_method, + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + if self._channels is None: + self._channels = ChannelList( + self._version, + self._solution["sid"], + ) + return self._channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + if self._roles is None: + self._roles = RoleList( + self._version, + self._solution["sid"], + ) + return self._roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + if self._users is None: + self._users = UserList( + self._version, + self._solution["sid"], + ) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V1.ServiceContext {}>".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V1.ServicePage>" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create(self, friendly_name: str) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async(self, friendly_name: str) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V1.ServiceList>" diff --git a/twilio/rest/chat/v1/service/channel/__init__.py b/twilio/rest/chat/v1/service/channel/__init__.py new file mode 100644 index 0000000000..ffe42c0b5d --- /dev/null +++ b/twilio/rest/chat/v1/service/channel/__init__.py @@ -0,0 +1,790 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.chat.v1.service.channel.invite import InviteList +from twilio.rest.chat.v1.service.channel.member import MemberList +from twilio.rest.chat.v1.service.channel.message import MessageList + + +class ChannelInstance(InstanceResource): + + class ChannelType(object): + PUBLIC = "public" + PRIVATE = "private" + + """ + :ivar sid: The unique string that we created to identify the Channel resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Channel resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :ivar attributes: The JSON string that stores application-specific data. **Note** If this property has been assigned a value, it's only displayed in a FETCH action that returns a single resource; otherwise, it's null. If the attributes have not been set, `{}` is returned. + :ivar type: + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar created_by: The `identity` of the User that created the channel. If the Channel was created by using the API, the value is `system`. + :ivar members_count: The number of Members in the Channel. + :ivar messages_count: The number of Messages in the Channel. + :ivar url: The absolute URL of the Channel resource. + :ivar links: The absolute URLs of the [Members](https://www.twilio.com/docs/chat/api/members), [Messages](https://www.twilio.com/docs/chat/api/messages) , [Invites](https://www.twilio.com/docs/chat/api/invites) and, if it exists, the last [Message](https://www.twilio.com/docs/chat/api/messages) for the Channel. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.type: Optional["ChannelInstance.ChannelType"] = payload.get("type") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + self.members_count: Optional[int] = deserialize.integer( + payload.get("members_count") + ) + self.messages_count: Optional[int] = deserialize.integer( + payload.get("messages_count") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None + + @property + def _proxy(self) -> "ChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ChannelContext for this ChannelInstance + """ + if self._context is None: + self._context = ChannelContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ChannelInstance": + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ChannelInstance": + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Update the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated ChannelInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Asynchronous coroutine to update the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated ChannelInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) + + @property + def invites(self) -> InviteList: + """ + Access the invites + """ + return self._proxy.invites + + @property + def members(self) -> MemberList: + """ + Access the members + """ + return self._proxy.members + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V1.ChannelInstance {}>".format(context) + + +class ChannelContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the ChannelContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to update the resource from. + :param sid: The Twilio-provided string that uniquely identifies the Channel resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Channels/{sid}".format(**self._solution) + + self._invites: Optional[InviteList] = None + self._members: Optional[MemberList] = None + self._messages: Optional[MessageList] = None + + def delete(self) -> bool: + """ + Deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelInstance: + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ChannelInstance: + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Update the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronous coroutine to update the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def invites(self) -> InviteList: + """ + Access the invites + """ + if self._invites is None: + self._invites = InviteList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._invites + + @property + def members(self) -> MemberList: + """ + Access the members + """ + if self._members is None: + self._members = MemberList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._members + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._messages + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V1.ChannelContext {}>".format(context) + + +class ChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: + """ + Build an instance of ChannelInstance + + :param payload: Payload response from the API + """ + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V1.ChannelPage>" + + +class ChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ChannelList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Channels".format(**self._solution) + + def create( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> ChannelInstance: + """ + Create the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + + :returns: The created ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "Type": type, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronously create the ChannelInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + + :returns: The created ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "Type": type, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelInstance]: + """ + Streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(type=type, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChannelInstance]: + """ + Asynchronously streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(type=type, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + type=type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Asynchronously lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + type=type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) + + async def page_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Asynchronously retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ChannelPage: + """ + Retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ChannelPage: + """ + Asynchronously retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelPage(self._version, response, self._solution) + + def get(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: The Twilio-provided string that uniquely identifies the Channel resource to update. + """ + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: The Twilio-provided string that uniquely identifies the Channel resource to update. + """ + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V1.ChannelList>" diff --git a/twilio/rest/chat/v1/service/channel/invite.py b/twilio/rest/chat/v1/service/channel/invite.py new file mode 100644 index 0000000000..e5cd4ebe36 --- /dev/null +++ b/twilio/rest/chat/v1/service/channel/invite.py @@ -0,0 +1,598 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InviteInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Invite resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Invite resource. + :ivar channel_sid: The SID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the resource belongs to. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + :ivar identity: The application-defined string that uniquely identifies the resource's [User](https://www.twilio.com/docs/api/chat/rest/users) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the resource. + :ivar created_by: The `identity` of the User that created the invite. + :ivar url: The absolute URL of the Invite resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.created_by: Optional[str] = payload.get("created_by") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[InviteContext] = None + + @property + def _proxy(self) -> "InviteContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InviteContext for this InviteInstance + """ + if self._context is None: + self._context = InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "InviteInstance": + """ + Fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InviteInstance": + """ + Asynchronous coroutine to fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V1.InviteInstance {}>".format(context) + + +class InviteContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the InviteContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to fetch the resource from. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the resource to fetch belongs to. + :param sid: The Twilio-provided string that uniquely identifies the Invite resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Invites/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> InviteInstance: + """ + Fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InviteInstance: + """ + Asynchronous coroutine to fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V1.InviteContext {}>".format(context) + + +class InvitePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: + """ + Build an instance of InviteInstance + + :param payload: Payload response from the API + """ + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V1.InvitePage>" + + +class InviteList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the InviteList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to read the resources from. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the resources to read belong to. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Invites".format( + **self._solution + ) + + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Create the InviteInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new member. + + :returns: The created InviteInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Asynchronously create the InviteInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new member. + + :returns: The created InviteInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InviteInstance]: + """ + Streams InviteInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InviteInstance]: + """ + Asynchronously streams InviteInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: + """ + Lists InviteInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: + """ + Asynchronously lists InviteInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InvitePage: + """ + Retrieve a single page of InviteInstance records from the API. + Request is executed immediately + + :param identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InviteInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InvitePage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InvitePage: + """ + Asynchronously retrieve a single page of InviteInstance records from the API. + Request is executed immediately + + :param identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InviteInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InvitePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> InvitePage: + """ + Retrieve a specific page of InviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InviteInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InvitePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> InvitePage: + """ + Asynchronously retrieve a specific page of InviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InviteInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InvitePage(self._version, response, self._solution) + + def get(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: The Twilio-provided string that uniquely identifies the Invite resource to fetch. + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: The Twilio-provided string that uniquely identifies the Invite resource to fetch. + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V1.InviteList>" diff --git a/twilio/rest/chat/v1/service/channel/member.py b/twilio/rest/chat/v1/service/channel/member.py new file mode 100644 index 0000000000..1262703ddc --- /dev/null +++ b/twilio/rest/chat/v1/service/channel/member.py @@ -0,0 +1,716 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MemberInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Member resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Member resource. + :ivar channel_sid: The unique ID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) for the member. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + :ivar identity: The application-defined string that uniquely identifies the resource's [User](https://www.twilio.com/docs/api/chat/rest/users) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the member. + :ivar last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) in the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) that the Member has read. + :ivar last_consumption_timestamp: The ISO 8601 timestamp string that represents the date-time of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) read event for the Member within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). + :ivar url: The absolute URL of the Member resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.last_consumption_timestamp: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("last_consumption_timestamp")) + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[MemberContext] = None + + @property + def _proxy(self) -> "MemberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MemberContext for this MemberInstance + """ + if self._context is None: + self._context = MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the MemberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "MemberInstance": + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MemberInstance": + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> "MemberInstance": + """ + Update the MemberInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) that the Member has read within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). + + :returns: The updated MemberInstance + """ + return self._proxy.update( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) + + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> "MemberInstance": + """ + Asynchronous coroutine to update the MemberInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) that the Member has read within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). + + :returns: The updated MemberInstance + """ + return await self._proxy.update_async( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V1.MemberInstance {}>".format(context) + + +class MemberContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the MemberContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to update the resource from. + :param channel_sid: The unique ID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the member to update belongs to. Can be the Channel resource's `sid` or `unique_name`. + :param sid: The Twilio-provided string that uniquely identifies the Member resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Members/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the MemberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MemberInstance: + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> MemberInstance: + """ + Update the MemberInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) that the Member has read within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). + + :returns: The updated MemberInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> MemberInstance: + """ + Asynchronous coroutine to update the MemberInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) that the Member has read within the [Channel](https://www.twilio.com/docs/api/chat/rest/channels). + + :returns: The updated MemberInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V1.MemberContext {}>".format(context) + + +class MemberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: + """ + Build an instance of MemberInstance + + :param payload: Payload response from the API + """ + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V1.MemberPage>" + + +class MemberList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MemberList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to read the resources from. + :param channel_sid: The unique ID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the members to read belong to. Can be the Channel resource's `sid` or `unique_name` value. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Members".format( + **self._solution + ) + + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> MemberInstance: + """ + Create the MemberInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + + :returns: The created MemberInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> MemberInstance: + """ + Asynchronously create the MemberInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/services). See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/api/services). + + :returns: The created MemberInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MemberInstance]: + """ + Streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MemberInstance]: + """ + Asynchronously streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Asynchronously lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Asynchronously retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: The [User](https://www.twilio.com/docs/api/chat/rest/v1/user)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MemberPage: + """ + Retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MemberPage: + """ + Asynchronously retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MemberPage(self._version, response, self._solution) + + def get(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param sid: The Twilio-provided string that uniquely identifies the Member resource to update. + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param sid: The Twilio-provided string that uniquely identifies the Member resource to update. + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V1.MemberList>" diff --git a/twilio/rest/chat/v1/service/channel/message.py b/twilio/rest/chat/v1/service/channel/message.py new file mode 100644 index 0000000000..e7cfc9217d --- /dev/null +++ b/twilio/rest/chat/v1/service/channel/message.py @@ -0,0 +1,731 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MessageInstance(InstanceResource): + + class OrderType(object): + ASC = "asc" + DESC = "desc" + + """ + :ivar sid: The unique string that we created to identify the Message resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Message resource. + :ivar attributes: The JSON string that stores application-specific data. **Note** If this property has been assigned a value, it's only displayed in a FETCH action that returns a single resource; otherwise, it's null. If the attributes have not been set, `{}` is returned. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + :ivar to: The SID of the [Channel](https://www.twilio.com/docs/chat/api/channels) that the message was sent to. + :ivar channel_sid: The unique ID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the Message resource belongs to. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar was_edited: Whether the message has been edited since it was created. + :ivar _from: The [identity](https://www.twilio.com/docs/api/chat/guides/identity) of the message's author. The default value is `system`. + :ivar body: The content of the message. + :ivar index: The index of the message within the [Channel](https://www.twilio.com/docs/chat/api/channels). + :ivar url: The absolute URL of the Message resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.service_sid: Optional[str] = payload.get("service_sid") + self.to: Optional[str] = payload.get("to") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.was_edited: Optional[bool] = payload.get("was_edited") + self._from: Optional[str] = payload.get("from") + self.body: Optional[str] = payload.get("body") + self.index: Optional[int] = deserialize.integer(payload.get("index")) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[MessageContext] = None + + @property + def _proxy(self) -> "MessageContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Update the MessageInstance + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MessageInstance + """ + return self._proxy.update( + body=body, + attributes=attributes, + ) + + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Asynchronous coroutine to update the MessageInstance + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MessageInstance + """ + return await self._proxy.update_async( + body=body, + attributes=attributes, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V1.MessageInstance {}>".format(context) + + +class MessageContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the MessageContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to update the resource from. + :param channel_sid: The unique ID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the message belongs to. Can be the Channel's `sid` or `unique_name`. + :param sid: The Twilio-provided string that uniquely identifies the Message resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Messages/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Update the MessageInstance + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V1.MessageContext {}>".format(context) + + +class MessagePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance + + :param payload: Payload response from the API + """ + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V1.MessagePage>" + + +class MessageList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to read the resources from. + :param channel_sid: The unique ID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the message to read belongs to. Can be the Channel's `sid` or `unique_name`. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Messages".format( + **self._solution + ) + + def create( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param from_: The [identity](https://www.twilio.com/docs/api/chat/guides/identity) of the new message's author. The default value is `system`. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The created MessageInstance + """ + + data = values.of( + { + "Body": body, + "From": from_, + "Attributes": attributes, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param body: The message to send to the channel. Can also be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param from_: The [identity](https://www.twilio.com/docs/api/chat/guides/identity) of the new message's author. The default value is `system`. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The created MessageInstance + """ + + data = values.of( + { + "Body": body, + "From": from_, + "Attributes": attributes, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: + """ + Streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(order=order, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInstance]: + """ + Asynchronously streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(order=order, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + order=order, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Asynchronously lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + order=order, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + async def page_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MessagePage: + """ + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MessagePage: + """ + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) + + def get(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: The Twilio-provided string that uniquely identifies the Message resource to update. + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: The Twilio-provided string that uniquely identifies the Message resource to update. + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V1.MessageList>" diff --git a/twilio/rest/chat/v1/service/role.py b/twilio/rest/chat/v1/service/role.py new file mode 100644 index 0000000000..d81cbd55ac --- /dev/null +++ b/twilio/rest/chat/v1/service/role.py @@ -0,0 +1,645 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RoleInstance(InstanceResource): + + class RoleType(object): + CHANNEL = "channel" + DEPLOYMENT = "deployment" + + """ + :ivar sid: The unique string that we created to identify the Role resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Role resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar permissions: An array of the permissions the role has been granted, formatted as a JSON string. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the Role resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["RoleInstance.RoleType"] = payload.get("type") + self.permissions: Optional[List[str]] = payload.get("permissions") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[RoleContext] = None + + @property + def _proxy(self) -> "RoleContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoleContext for this RoleInstance + """ + if self._context is None: + self._context = RoleContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RoleInstance": + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RoleInstance": + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return await self._proxy.fetch_async() + + def update(self, permission: List[str]) -> "RoleInstance": + """ + Update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: The updated RoleInstance + """ + return self._proxy.update( + permission=permission, + ) + + async def update_async(self, permission: List[str]) -> "RoleInstance": + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: The updated RoleInstance + """ + return await self._proxy.update_async( + permission=permission, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V1.RoleInstance {}>".format(context) + + +class RoleContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the RoleContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to update the resource from. + :param sid: The Twilio-provided string that uniquely identifies the Role resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Roles/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update(self, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V1.RoleContext {}>".format(context) + + +class RolePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: + """ + Build an instance of RoleInstance + + :param payload: Payload response from the API + """ + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V1.RolePage>" + + +class RoleList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the RoleList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Roles".format(**self._solution) + + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type` and are described in the documentation. + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoleInstance]: + """ + Streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoleInstance]: + """ + Asynchronously streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Asynchronously lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Asynchronously retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RolePage: + """ + Retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RolePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RolePage: + """ + Asynchronously retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RolePage(self._version, response, self._solution) + + def get(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: The Twilio-provided string that uniquely identifies the Role resource to update. + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: The Twilio-provided string that uniquely identifies the Role resource to update. + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V1.RoleList>" diff --git a/twilio/rest/chat/v1/service/user/__init__.py b/twilio/rest/chat/v1/service/user/__init__.py new file mode 100644 index 0000000000..c6b900957c --- /dev/null +++ b/twilio/rest/chat/v1/service/user/__init__.py @@ -0,0 +1,723 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.chat.v1.service.user.user_channel import UserChannelList + + +class UserInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the User resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the User resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + :ivar attributes: The JSON string that stores application-specific data. **Note** If this property has been assigned a value, it's only displayed in a FETCH action that returns a single resource; otherwise, it's null. If the attributes have not been set, `{}` is returned. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the user. + :ivar identity: The application-defined string that uniquely identifies the resource's User within the [Service](https://www.twilio.com/docs/api/chat/rest/services). This value is often a username or an email address. See [access tokens](https://www.twilio.com/docs/api/chat/guides/create-tokens) for more info. + :ivar is_online: Whether the User is actively connected to the Service instance and online. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service's `reachability_enabled` is `false`, if the User has never been online for the Service instance, even if the Service's `reachability_enabled` is `true`. + :ivar is_notifiable: Whether the User has a potentially valid Push Notification registration (APN or GCM) for the Service instance. If at least one registration exists, `true`; otherwise `false`. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service's `reachability_enabled` is `false`, and if the User has never had a notification registration, even if the Service's `reachability_enabled` is `true`. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar joined_channels_count: The number of Channels this User is a Member of. + :ivar links: The absolute URLs of the [Channel](https://www.twilio.com/docs/chat/api/channels) and [Binding](https://www.twilio.com/docs/chat/rest/bindings-resource) resources related to the user. + :ivar url: The absolute URL of the User resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.role_sid: Optional[str] = payload.get("role_sid") + self.identity: Optional[str] = payload.get("identity") + self.is_online: Optional[bool] = payload.get("is_online") + self.is_notifiable: Optional[bool] = payload.get("is_notifiable") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.joined_channels_count: Optional[int] = deserialize.integer( + payload.get("joined_channels_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserContext] = None + + @property + def _proxy(self) -> "UserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Update the UserInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to this user. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + return self._proxy.update( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to this user. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + return await self._proxy.update_async( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + @property + def user_channels(self) -> UserChannelList: + """ + Access the user_channels + """ + return self._proxy.user_channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V1.UserInstance {}>".format(context) + + +class UserContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the UserContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to update the resource from. + :param sid: The Twilio-provided string that uniquely identifies the User resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Users/{sid}".format(**self._solution) + + self._user_channels: Optional[UserChannelList] = None + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Update the UserInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to this user. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to this user. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def user_channels(self) -> UserChannelList: + """ + Access the user_channels + """ + if self._user_channels is None: + self._user_channels = UserChannelList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._user_channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V1.UserContext {}>".format(context) + + +class UserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance + + :param payload: Payload response from the API + """ + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V1.UserPage>" + + +class UserList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the UserList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Users".format(**self._solution) + + def create( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Create the UserInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). This value is often a username or email address. See the Identity documentation for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/api/chat/rest/v1/user) within the [Service](https://www.twilio.com/docs/api/chat/rest/v1/service). This value is often a username or email address. See the Identity documentation for more details. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/api/chat/rest/roles) assigned to the new User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserInstance]: + """ + Streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserInstance]: + """ + Asynchronously streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Asynchronously lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserPage: + """ + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserPage: + """ + Asynchronously retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserPage(self._version, response, self._solution) + + def get(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The Twilio-provided string that uniquely identifies the User resource to update. + """ + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The Twilio-provided string that uniquely identifies the User resource to update. + """ + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V1.UserList>" diff --git a/twilio/rest/chat/v1/service/user/user_channel.py b/twilio/rest/chat/v1/service/user/user_channel.py new file mode 100644 index 0000000000..b7f35aa9ef --- /dev/null +++ b/twilio/rest/chat/v1/service/user/user_channel.py @@ -0,0 +1,322 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UserChannelInstance(InstanceResource): + + class ChannelStatus(object): + JOINED = "joined" + INVITED = "invited" + NOT_PARTICIPATING = "not_participating" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the User Channel resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) the resource is associated with. + :ivar channel_sid: The SID of the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) the resource belongs to. + :ivar member_sid: The SID of a [Member](https://www.twilio.com/docs/api/chat/rest/members) that represents the User on the Channel. + :ivar status: + :ivar last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/api/chat/rest/messages) in the [Channel](https://www.twilio.com/docs/api/chat/rest/channels) that the Member has read. + :ivar unread_messages_count: The number of unread Messages in the Channel for the User. Note that retrieving messages on a client endpoint does not mean that messages are consumed or read. See [Consumption Horizon feature](/docs/api/chat/guides/consumption-horizon) to learn how to mark messages as consumed. + :ivar links: The absolute URLs of the [Members](https://www.twilio.com/docs/chat/api/members), [Messages](https://www.twilio.com/docs/chat/api/messages) , [Invites](https://www.twilio.com/docs/chat/api/invites) and, if it exists, the last [Message](https://www.twilio.com/docs/chat/api/messages) for the Channel. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], service_sid: str, user_sid: str + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.member_sid: Optional[str] = payload.get("member_sid") + self.status: Optional["UserChannelInstance.ChannelStatus"] = payload.get( + "status" + ) + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.unread_messages_count: Optional[int] = deserialize.integer( + payload.get("unread_messages_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V1.UserChannelInstance {}>".format(context) + + +class UserChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: + """ + Build an instance of UserChannelInstance + + :param payload: Payload response from the API + """ + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V1.UserChannelPage>" + + +class UserChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str, user_sid: str): + """ + Initialize the UserChannelList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/api/chat/rest/services) to read the resources from. + :param user_sid: The SID of the [User](https://www.twilio.com/docs/api/chat/rest/users) to read the User Channel resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Channels".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserChannelInstance]: + """ + Streams UserChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserChannelInstance]: + """ + Asynchronously streams UserChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: + """ + Lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: + """ + Asynchronously lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserChannelPage: + """ + Retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserChannelPage: + """ + Asynchronously retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserChannelPage: + """ + Retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserChannelPage: + """ + Asynchronously retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserChannelPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V1.UserChannelList>" diff --git a/twilio/rest/chat/v2/__init__.py b/twilio/rest/chat/v2/__init__.py new file mode 100644 index 0000000000..e949532d56 --- /dev/null +++ b/twilio/rest/chat/v2/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.chat.v2.credential import CredentialList +from twilio.rest.chat.v2.service import ServiceList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Chat + + :param domain: The Twilio.chat domain + """ + super().__init__(domain, "v2") + self._credentials: Optional[CredentialList] = None + self._services: Optional[ServiceList] = None + + @property + def credentials(self) -> CredentialList: + if self._credentials is None: + self._credentials = CredentialList(self) + return self._credentials + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2>" diff --git a/twilio/rest/chat/v2/credential.py b/twilio/rest/chat/v2/credential.py new file mode 100644 index 0000000000..5479abeca0 --- /dev/null +++ b/twilio/rest/chat/v2/credential.py @@ -0,0 +1,711 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CredentialInstance(InstanceResource): + + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: The unique string that we created to identify the Credential resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Credential resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Credential resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushService"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None + + @property + def _proxy(self) -> "CredentialContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CredentialInstance": + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialInstance": + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.CredentialInstance {}>".format(context) + + +class CredentialContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CredentialContext + + :param version: Version that contains the resource + :param sid: The SID of the Credential resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.CredentialContext {}>".format(context) + + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance + + :param payload: Payload response from the API + """ + return CredentialInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.CredentialPage>" + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Credentials" + + def create( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + async def create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----` + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialInstance]: + """ + Streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: + """ + Asynchronously streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Asynchronously lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Asynchronously retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + def get_page(self, target_url: str) -> CredentialPage: + """ + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CredentialPage: + """ + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) + + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The SID of the Credential resource to update. + """ + return CredentialContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The SID of the Credential resource to update. + """ + return CredentialContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.CredentialList>" diff --git a/twilio/rest/chat/v2/service/__init__.py b/twilio/rest/chat/v2/service/__init__.py new file mode 100644 index 0000000000..90a6c6cdba --- /dev/null +++ b/twilio/rest/chat/v2/service/__init__.py @@ -0,0 +1,1128 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.chat.v2.service.binding import BindingList +from twilio.rest.chat.v2.service.channel import ChannelList +from twilio.rest.chat.v2.service.role import RoleList +from twilio.rest.chat.v2.service.user import UserList + + +class ServiceInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Service resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :ivar default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :ivar default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :ivar read_status_enabled: Whether the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature is enabled. The default is `true`. + :ivar reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) is enabled for this Service instance. The default is `false`. + :ivar typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :ivar consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :ivar limits: An object that describes the limits of the service instance. The `limits` object contains `channel_members` to describe the members/channel limit and `user_channels` to describe the channels/user limit. `channel_members` can be 1,000 or less, with a default of 250. `user_channels` can be 1,000 or less, with a default value of 100. + :ivar pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :ivar post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :ivar webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :ivar webhook_filters: The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :ivar pre_webhook_retry_count: The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won't be retried. + :ivar post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. + :ivar notifications: The notification configuration for the Service instance. See [Push Notification Configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :ivar media: An object that describes the properties of media that the service supports. The object contains the `size_limit_mb` property, which describes the size of the largest media file in MB; and the `compatibility_message` property, which contains the message text to send when a media message does not have any text. + :ivar url: The absolute URL of the Service resource. + :ivar links: The absolute URLs of the Service's [Channels](https://www.twilio.com/docs/chat/channels), [Roles](https://www.twilio.com/docs/chat/rest/role-resource), [Bindings](https://www.twilio.com/docs/chat/rest/binding-resource), and [Users](https://www.twilio.com/docs/chat/rest/user-resource). + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.default_service_role_sid: Optional[str] = payload.get( + "default_service_role_sid" + ) + self.default_channel_role_sid: Optional[str] = payload.get( + "default_channel_role_sid" + ) + self.default_channel_creator_role_sid: Optional[str] = payload.get( + "default_channel_creator_role_sid" + ) + self.read_status_enabled: Optional[bool] = payload.get("read_status_enabled") + self.reachability_enabled: Optional[bool] = payload.get("reachability_enabled") + self.typing_indicator_timeout: Optional[int] = deserialize.integer( + payload.get("typing_indicator_timeout") + ) + self.consumption_report_interval: Optional[int] = deserialize.integer( + payload.get("consumption_report_interval") + ) + self.limits: Optional[Dict[str, object]] = payload.get("limits") + self.pre_webhook_url: Optional[str] = payload.get("pre_webhook_url") + self.post_webhook_url: Optional[str] = payload.get("post_webhook_url") + self.webhook_method: Optional[str] = payload.get("webhook_method") + self.webhook_filters: Optional[List[str]] = payload.get("webhook_filters") + self.pre_webhook_retry_count: Optional[int] = deserialize.integer( + payload.get("pre_webhook_retry_count") + ) + self.post_webhook_retry_count: Optional[int] = deserialize.integer( + payload.get("post_webhook_retry_count") + ) + self.notifications: Optional[Dict[str, object]] = payload.get("notifications") + self.media: Optional[Dict[str, object]] = payload.get("media") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. The default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_sound: The name of the sound to play when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. The default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. The default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. The default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + :param media_compatibility_message: The message to send when a media message has no text. Can be used as placeholder message. + :param pre_webhook_retry_count: The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won't be retried. + :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. + :param notifications_log_enabled: Whether to log notifications. The default is `false`. + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. The default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_sound: The name of the sound to play when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. The default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. The default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. The default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + :param media_compatibility_message: The message to send when a media message has no text. Can be used as placeholder message. + :param pre_webhook_retry_count: The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won't be retried. + :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. + :param notifications_log_enabled: Whether to log notifications. The default is `false`. + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + return self._proxy.bindings + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + return self._proxy.channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + return self._proxy.users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.ServiceInstance {}>".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The SID of the Service resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._bindings: Optional[BindingList] = None + self._channels: Optional[ChannelList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. The default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_sound: The name of the sound to play when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. The default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. The default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. The default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + :param media_compatibility_message: The message to send when a media message has no text. Can be used as placeholder message. + :param pre_webhook_retry_count: The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won't be retried. + :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. + :param notifications_log_enabled: Whether to log notifications. The default is `false`. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.NewMessage.Sound": notifications_new_message_sound, + "Notifications.NewMessage.BadgeCountEnabled": serialize.boolean_to_string( + notifications_new_message_badge_count_enabled + ), + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.AddedToChannel.Sound": notifications_added_to_channel_sound, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.RemovedFromChannel.Sound": notifications_removed_from_channel_sound, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "Notifications.InvitedToChannel.Sound": notifications_invited_to_channel_sound, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + "Media.CompatibilityMessage": media_compatibility_message, + "PreWebhookRetryCount": pre_webhook_retry_count, + "PostWebhookRetryCount": post_webhook_retry_count, + "Notifications.LogEnabled": serialize.boolean_to_string( + notifications_log_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. + :param default_service_role_sid: The service role assigned to users when they are added to the service. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_role_sid: The channel role assigned to users when they are added to a channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param default_channel_creator_role_sid: The channel role assigned to a channel creator when they join a new channel. See the [Role resource](https://www.twilio.com/docs/chat/rest/role-resource) for more info about roles. + :param read_status_enabled: Whether to enable the [Message Consumption Horizon](https://www.twilio.com/docs/chat/consumption-horizon) feature. The default is `true`. + :param reachability_enabled: Whether to enable the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) for this Service instance. The default is `false`. + :param typing_indicator_timeout: How long in seconds after a `started typing` event until clients should assume that user is no longer typing, even if no `ended typing` message was received. The default is 5 seconds. + :param consumption_report_interval: DEPRECATED. The interval in seconds between consumption reports submission batches from client endpoints. + :param notifications_new_message_enabled: Whether to send a notification when a new message is added to a channel. The default is `false`. + :param notifications_new_message_template: The template to use to create the notification text displayed when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_sound: The name of the sound to play when a new message is added to a channel and `notifications.new_message.enabled` is `true`. + :param notifications_new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param notifications_added_to_channel_enabled: Whether to send a notification when a member is added to a channel. The default is `false`. + :param notifications_added_to_channel_template: The template to use to create the notification text displayed when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_added_to_channel_sound: The name of the sound to play when a member is added to a channel and `notifications.added_to_channel.enabled` is `true`. + :param notifications_removed_from_channel_enabled: Whether to send a notification to a user when they are removed from a channel. The default is `false`. + :param notifications_removed_from_channel_template: The template to use to create the notification text displayed to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_removed_from_channel_sound: The name of the sound to play to a user when they are removed from a channel and `notifications.removed_from_channel.enabled` is `true`. + :param notifications_invited_to_channel_enabled: Whether to send a notification when a user is invited to a channel. The default is `false`. + :param notifications_invited_to_channel_template: The template to use to create the notification text displayed when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param notifications_invited_to_channel_sound: The name of the sound to play when a user is invited to a channel and `notifications.invited_to_channel.enabled` is `true`. + :param pre_webhook_url: The URL for pre-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param post_webhook_url: The URL for post-event webhooks, which are called by using the `webhook_method`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_method: The HTTP method to use for calls to the `pre_webhook_url` and `post_webhook_url` webhooks. Can be: `POST` or `GET` and the default is `POST`. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param webhook_filters: The list of webhook events that are enabled for this Service instance. See [Webhook Events](https://www.twilio.com/docs/chat/webhook-events) for more details. + :param limits_channel_members: The maximum number of Members that can be added to Channels within this Service. Can be up to 1,000. + :param limits_user_channels: The maximum number of Channels Users can be a Member of within this Service. Can be up to 1,000. + :param media_compatibility_message: The message to send when a media message has no text. Can be used as placeholder message. + :param pre_webhook_retry_count: The number of times to retry a call to the `pre_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. Default retry count is 0 times, which means the call won't be retried. + :param post_webhook_retry_count: The number of times to retry a call to the `post_webhook_url` if the request times out (after 5 seconds) or it receives a 429, 503, or 504 HTTP response. The default is 0, which means the call won't be retried. + :param notifications_log_enabled: Whether to log notifications. The default is `false`. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.NewMessage.Sound": notifications_new_message_sound, + "Notifications.NewMessage.BadgeCountEnabled": serialize.boolean_to_string( + notifications_new_message_badge_count_enabled + ), + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.AddedToChannel.Sound": notifications_added_to_channel_sound, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.RemovedFromChannel.Sound": notifications_removed_from_channel_sound, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "Notifications.InvitedToChannel.Sound": notifications_invited_to_channel_sound, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + "Media.CompatibilityMessage": media_compatibility_message, + "PreWebhookRetryCount": pre_webhook_retry_count, + "PostWebhookRetryCount": post_webhook_retry_count, + "Notifications.LogEnabled": serialize.boolean_to_string( + notifications_log_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + if self._bindings is None: + self._bindings = BindingList( + self._version, + self._solution["sid"], + ) + return self._bindings + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + if self._channels is None: + self._channels = ChannelList( + self._version, + self._solution["sid"], + ) + return self._channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + if self._roles is None: + self._roles = RoleList( + self._version, + self._solution["sid"], + ) + return self._roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + if self._users is None: + self._users = UserList( + self._version, + self._solution["sid"], + ) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.ServiceContext {}>".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.ServicePage>" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create(self, friendly_name: str) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async(self, friendly_name: str) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The SID of the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The SID of the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.ServiceList>" diff --git a/twilio/rest/chat/v2/service/binding.py b/twilio/rest/chat/v2/service/binding.py new file mode 100644 index 0000000000..125f4b9368 --- /dev/null +++ b/twilio/rest/chat/v2/service/binding.py @@ -0,0 +1,536 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class BindingInstance(InstanceResource): + + class BindingType(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: The unique string that we created to identify the Binding resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Binding resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Binding resource is associated with. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar endpoint: The unique endpoint identifier for the Binding. The format of this value depends on the `binding_type`. + :ivar identity: The application-defined string that uniquely identifies the resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :ivar credential_sid: The SID of the [Credential](https://www.twilio.com/docs/chat/rest/credential-resource) for the binding. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :ivar binding_type: + :ivar message_types: The [Programmable Chat message types](https://www.twilio.com/docs/chat/push-notification-configuration#push-types) the binding is subscribed to. + :ivar url: The absolute URL of the Binding resource. + :ivar links: The absolute URLs of the Binding's [User](https://www.twilio.com/docs/chat/rest/user-resource). + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.endpoint: Optional[str] = payload.get("endpoint") + self.identity: Optional[str] = payload.get("identity") + self.credential_sid: Optional[str] = payload.get("credential_sid") + self.binding_type: Optional["BindingInstance.BindingType"] = payload.get( + "binding_type" + ) + self.message_types: Optional[List[str]] = payload.get("message_types") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[BindingContext] = None + + @property + def _proxy(self) -> "BindingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BindingContext for this BindingInstance + """ + if self._context is None: + self._context = BindingContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "BindingInstance": + """ + Fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BindingInstance": + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.BindingInstance {}>".format(context) + + +class BindingContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the BindingContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the Binding resource from. + :param sid: The SID of the Binding resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Bindings/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> BindingInstance: + """ + Fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> BindingInstance: + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.BindingContext {}>".format(context) + + +class BindingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: + """ + Build an instance of BindingInstance + + :param payload: Payload response from the API + """ + return BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.BindingPage>" + + +class BindingList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the BindingList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the Binding resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Bindings".format(**self._solution) + + def stream( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BindingInstance]: + """ + Streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BindingInstance]: + """ + Asynchronously streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BindingInstance]: + """ + Lists BindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BindingInstance]: + """ + Asynchronously lists BindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BindingPage: + """ + Retrieve a single page of BindingInstance records from the API. + Request is executed immediately + + :param binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BindingInstance + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BindingPage(self._version, response, self._solution) + + async def page_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BindingPage: + """ + Asynchronously retrieve a single page of BindingInstance records from the API. + Request is executed immediately + + :param binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BindingInstance + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BindingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> BindingPage: + """ + Retrieve a specific page of BindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BindingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BindingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> BindingPage: + """ + Asynchronously retrieve a specific page of BindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BindingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BindingPage(self._version, response, self._solution) + + def get(self, sid: str) -> BindingContext: + """ + Constructs a BindingContext + + :param sid: The SID of the Binding resource to fetch. + """ + return BindingContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> BindingContext: + """ + Constructs a BindingContext + + :param sid: The SID of the Binding resource to fetch. + """ + return BindingContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.BindingList>" diff --git a/twilio/rest/chat/v2/service/channel/__init__.py b/twilio/rest/chat/v2/service/channel/__init__.py new file mode 100644 index 0000000000..36d08a3896 --- /dev/null +++ b/twilio/rest/chat/v2/service/channel/__init__.py @@ -0,0 +1,962 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.chat.v2.service.channel.invite import InviteList +from twilio.rest.chat.v2.service.channel.member import MemberList +from twilio.rest.chat.v2.service.channel.message import MessageList +from twilio.rest.chat.v2.service.channel.webhook import WebhookList + + +class ChannelInstance(InstanceResource): + + class ChannelType(object): + PUBLIC = "public" + PRIVATE = "private" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: The unique string that we created to identify the Channel resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Channel resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Channel resource is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :ivar attributes: The JSON string that stores application-specific data. If attributes have not been set, `{}` is returned. + :ivar type: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar created_by: The `identity` of the User that created the channel. If the Channel was created by using the API, the value is `system`. + :ivar members_count: The number of Members in the Channel. + :ivar messages_count: The number of Messages that have been passed in the Channel. + :ivar url: The absolute URL of the Channel resource. + :ivar links: The absolute URLs of the [Members](https://www.twilio.com/docs/chat/rest/member-resource), [Messages](https://www.twilio.com/docs/chat/rest/message-resource), [Invites](https://www.twilio.com/docs/chat/rest/invite-resource), Webhooks and, if it exists, the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) for the Channel. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.type: Optional["ChannelInstance.ChannelType"] = payload.get("type") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + self.members_count: Optional[int] = deserialize.integer( + payload.get("members_count") + ) + self.messages_count: Optional[int] = deserialize.integer( + payload.get("messages_count") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None + + @property + def _proxy(self) -> "ChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ChannelContext for this ChannelInstance + """ + if self._context is None: + self._context = ChannelContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "ChannelInstance": + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ChannelInstance": + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: The updated ChannelInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Asynchronous coroutine to update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: The updated ChannelInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + + @property + def invites(self) -> InviteList: + """ + Access the invites + """ + return self._proxy.invites + + @property + def members(self) -> MemberList: + """ + Access the members + """ + return self._proxy.members + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + return self._proxy.webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.ChannelInstance {}>".format(context) + + +class ChannelContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the ChannelContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to update the Channel resource in. + :param sid: The SID of the Channel resource to update. This value can be either the `sid` or the `unique_name` of the Channel resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Channels/{sid}".format(**self._solution) + + self._invites: Optional[InviteList] = None + self._members: Optional[MemberList] = None + self._messages: Optional[MessageList] = None + self._webhooks: Optional[WebhookList] = None + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelInstance: + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ChannelInstance: + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "CreatedBy": created_by, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronous coroutine to update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 256 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. This value must be 256 characters or less in length and unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "CreatedBy": created_by, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def invites(self) -> InviteList: + """ + Access the invites + """ + if self._invites is None: + self._invites = InviteList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._invites + + @property + def members(self) -> MemberList: + """ + Access the members + """ + if self._members is None: + self._members = MemberList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._members + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._messages + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + if self._webhooks is None: + self._webhooks = WebhookList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.ChannelContext {}>".format(context) + + +class ChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: + """ + Build an instance of ChannelInstance + + :param payload: Payload response from the API + """ + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.ChannelPage>" + + +class ChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ChannelList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the Channel resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Channels".format(**self._solution) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Create the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the Channel resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used in cases where a Channel is being recreated from a backup/separate source and where a Message was previously updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: The created ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "Type": type, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "CreatedBy": created_by, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronously create the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the Channel resource's `sid` in the URL. This value must be 64 characters or less in length and be unique within the Service. + :param attributes: A valid JSON string that contains application-specific data. + :param type: + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this should only be used in cases where a Channel is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used in cases where a Channel is being recreated from a backup/separate source and where a Message was previously updated. + :param created_by: The `identity` of the User that created the channel. Default is: `system`. + + :returns: The created ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "Type": type, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "CreatedBy": created_by, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelInstance]: + """ + Streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(type=type, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChannelInstance]: + """ + Asynchronously streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(type=type, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + type=type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Asynchronously lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + type=type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) + + async def page_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Asynchronously retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: The visibility of the Channels to read. Can be: `public` or `private` and defaults to `public`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ChannelPage: + """ + Retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ChannelPage: + """ + Asynchronously retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelPage(self._version, response, self._solution) + + def get(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: The SID of the Channel resource to update. This value can be either the `sid` or the `unique_name` of the Channel resource to update. + """ + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: The SID of the Channel resource to update. This value can be either the `sid` or the `unique_name` of the Channel resource to update. + """ + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.ChannelList>" diff --git a/twilio/rest/chat/v2/service/channel/invite.py b/twilio/rest/chat/v2/service/channel/invite.py new file mode 100644 index 0000000000..7c7f9f6211 --- /dev/null +++ b/twilio/rest/chat/v2/service/channel/invite.py @@ -0,0 +1,598 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InviteInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Invite resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Invite resource. + :ivar channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Invite resource belongs to. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Invite resource is associated with. + :ivar identity: The application-defined string that uniquely identifies the resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the resource. + :ivar created_by: The `identity` of the User that created the invite. + :ivar url: The absolute URL of the Invite resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.created_by: Optional[str] = payload.get("created_by") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[InviteContext] = None + + @property + def _proxy(self) -> "InviteContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InviteContext for this InviteInstance + """ + if self._context is None: + self._context = InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "InviteInstance": + """ + Fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InviteInstance": + """ + Asynchronous coroutine to fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.InviteInstance {}>".format(context) + + +class InviteContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the InviteContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the Invite resource from. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Invite resource to fetch belongs to. This value can be the Channel resource's `sid` or `unique_name`. + :param sid: The SID of the Invite resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Invites/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> InviteInstance: + """ + Fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InviteInstance: + """ + Asynchronous coroutine to fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.InviteContext {}>".format(context) + + +class InvitePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: + """ + Build an instance of InviteInstance + + :param payload: Payload response from the API + """ + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.InvitePage>" + + +class InviteList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the InviteList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the Invite resources from. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Invite resources to read belong to. This value can be the Channel resource's `sid` or `unique_name`. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Invites".format( + **self._solution + ) + + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Create the InviteInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the new member. + + :returns: The created InviteInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Asynchronously create the InviteInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the new member. + + :returns: The created InviteInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InviteInstance]: + """ + Streams InviteInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InviteInstance]: + """ + Asynchronously streams InviteInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: + """ + Lists InviteInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: + """ + Asynchronously lists InviteInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InvitePage: + """ + Retrieve a single page of InviteInstance records from the API. + Request is executed immediately + + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InviteInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InvitePage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InvitePage: + """ + Asynchronously retrieve a single page of InviteInstance records from the API. + Request is executed immediately + + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InviteInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InvitePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> InvitePage: + """ + Retrieve a specific page of InviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InviteInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InvitePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> InvitePage: + """ + Asynchronously retrieve a specific page of InviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InviteInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InvitePage(self._version, response, self._solution) + + def get(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: The SID of the Invite resource to fetch. + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: The SID of the Invite resource to fetch. + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.InviteList>" diff --git a/twilio/rest/chat/v2/service/channel/member.py b/twilio/rest/chat/v2/service/channel/member.py new file mode 100644 index 0000000000..f07cb21891 --- /dev/null +++ b/twilio/rest/chat/v2/service/channel/member.py @@ -0,0 +1,905 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MemberInstance(InstanceResource): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: The unique string that we created to identify the Member resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Member resource. + :ivar channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Member resource belongs to. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Member resource is associated with. + :ivar identity: The application-defined string that uniquely identifies the resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the member. + :ivar last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :ivar last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :ivar url: The absolute URL of the Member resource. + :ivar attributes: The JSON string that stores application-specific data. If attributes have not been set, `{}` is returned. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.last_consumption_timestamp: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("last_consumption_timestamp")) + ) + self.url: Optional[str] = payload.get("url") + self.attributes: Optional[str] = payload.get("attributes") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[MemberContext] = None + + @property + def _proxy(self) -> "MemberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MemberContext for this MemberInstance + """ + if self._context is None: + self._context = MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "MemberInstance": + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MemberInstance": + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MemberInstance": + """ + Update the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) that the Member has read within the [Channel](https://www.twilio.com/docs/chat/channels). + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MemberInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MemberInstance": + """ + Asynchronous coroutine to update the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) that the Member has read within the [Channel](https://www.twilio.com/docs/chat/channels). + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MemberInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.MemberInstance {}>".format(context) + + +class MemberContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the MemberContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to update the Member resource in. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Member resource to update belongs to. This value can be the Channel resource's `sid` or `unique_name`. + :param sid: The SID of the Member resource to update. This value can be either the Member's `sid` or its `identity` value. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Members/{sid}".format( + **self._solution + ) + ) + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MemberInstance: + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Update the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) that the Member has read within the [Channel](https://www.twilio.com/docs/chat/channels). + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MemberInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Asynchronous coroutine to update the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) that the Member has read within the [Channel](https://www.twilio.com/docs/chat/channels). + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The updated MemberInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.MemberContext {}>".format(context) + + +class MemberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: + """ + Build an instance of MemberInstance + + :param payload: Payload response from the API + """ + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.MemberPage>" + + +class MemberList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MemberList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the Member resources from. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Member resources to read belong to. This value can be the Channel resource's `sid` or `unique_name`. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Members".format( + **self._solution + ) + + def create( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Create the MemberInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. This parameter should only be used when recreating a Member from a backup/separate source. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used when a Member is being recreated from a backup/separate source and where a Member was previously updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The created MemberInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Asynchronously create the MemberInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the member. The default roles are those specified on the [Service](https://www.twilio.com/docs/chat/rest/service-resource). + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. This parameter should only be used when recreating a Member from a backup/separate source. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. Note that this parameter should only be used when a Member is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. The default value is `null`. Note that this parameter should only be used when a Member is being recreated from a backup/separate source and where a Member was previously updated. + :param attributes: A valid JSON string that contains application-specific data. + + :returns: The created MemberInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MemberInstance]: + """ + Streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MemberInstance]: + """ + Asynchronously streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Asynchronously lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Asynchronously retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the Member resources to read. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MemberPage: + """ + Retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MemberPage: + """ + Asynchronously retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MemberPage(self._version, response, self._solution) + + def get(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param sid: The SID of the Member resource to update. This value can be either the Member's `sid` or its `identity` value. + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param sid: The SID of the Member resource to update. This value can be either the Member's `sid` or its `identity` value. + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.MemberList>" diff --git a/twilio/rest/chat/v2/service/channel/message.py b/twilio/rest/chat/v2/service/channel/message.py new file mode 100644 index 0000000000..d0bf2e5ac7 --- /dev/null +++ b/twilio/rest/chat/v2/service/channel/message.py @@ -0,0 +1,905 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MessageInstance(InstanceResource): + + class OrderType(object): + ASC = "asc" + DESC = "desc" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: The unique string that we created to identify the Message resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Message resource. + :ivar attributes: The JSON string that stores application-specific data. If attributes have not been set, `{}` is returned. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Message resource is associated with. + :ivar to: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) that the message was sent to. + :ivar channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Message resource belongs to. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :ivar was_edited: Whether the message has been edited since it was created. + :ivar _from: The [Identity](https://www.twilio.com/docs/chat/identity) of the message's author. The default value is `system`. + :ivar body: The content of the message. + :ivar index: The index of the message within the [Channel](https://www.twilio.com/docs/chat/channels). Indices may skip numbers, but will always be in order of when the message was received. + :ivar type: The Message type. Can be: `text` or `media`. + :ivar media: An object that describes the Message's media, if the message contains media. The object contains these fields: `content_type` with the MIME type of the media, `filename` with the name of the media, `sid` with the SID of the Media resource, and `size` with the media object's file size in bytes. If the Message has no media, this value is `null`. + :ivar url: The absolute URL of the Message resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.service_sid: Optional[str] = payload.get("service_sid") + self.to: Optional[str] = payload.get("to") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.last_updated_by: Optional[str] = payload.get("last_updated_by") + self.was_edited: Optional[bool] = payload.get("was_edited") + self._from: Optional[str] = payload.get("from") + self.body: Optional[str] = payload.get("body") + self.index: Optional[int] = deserialize.integer(payload.get("index")) + self.type: Optional[str] = payload.get("type") + self.media: Optional[Dict[str, object]] = payload.get("media") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[MessageContext] = None + + @property + def _proxy(self) -> "MessageContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the message's author. + + :returns: The updated MessageInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Asynchronous coroutine to update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the message's author. + + :returns: The updated MessageInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.MessageInstance {}>".format(context) + + +class MessageContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the MessageContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to update the Message resource in. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Message resource to update belongs to. This value can be the Channel resource's `sid` or `unique_name`. + :param sid: The SID of the Message resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Messages/{sid}".format( + **self._solution + ) + ) + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the message's author. + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "From": from_, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the message's author. + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "From": from_, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.MessageContext {}>".format(context) + + +class MessagePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance + + :param payload: Payload response from the API + """ + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.MessagePage>" + + +class MessageList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the Message resources from. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Message resource to read belongs to. This value can be the Channel resource's `sid` or `unique_name`. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Messages".format( + **self._solution + ) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the new message's author. The default value is `system`. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param media_sid: The SID of the [Media](https://www.twilio.com/docs/chat/rest/media) to attach to the new Message. + + :returns: The created MessageInstance + """ + + data = values.of( + { + "From": from_, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "Body": body, + "MediaSid": media_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: The [Identity](https://www.twilio.com/docs/chat/identity) of the new message's author. The default value is `system`. + :param attributes: A valid JSON string that contains application-specific data. + :param date_created: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was created. The default value is the current time set by the Chat service. This parameter should only be used when a Chat's history is being recreated from a backup/separate source. + :param date_updated: The date, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, to assign to the resource as the date it was last updated. + :param last_updated_by: The [Identity](https://www.twilio.com/docs/chat/identity) of the User who last updated the Message, if applicable. + :param body: The message to send to the channel. Can be an empty string or `null`, which sets the value as an empty string. You can send structured data in the body by serializing it as a string. + :param media_sid: The SID of the [Media](https://www.twilio.com/docs/chat/rest/media) to attach to the new Message. + + :returns: The created MessageInstance + """ + + data = values.of( + { + "From": from_, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "Body": body, + "MediaSid": media_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: + """ + Streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(order=order, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInstance]: + """ + Asynchronously streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(order=order, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + order=order, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Asynchronously lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + order=order, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + async def page_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending) with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MessagePage: + """ + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MessagePage: + """ + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) + + def get(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: The SID of the Message resource to update. + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: The SID of the Message resource to update. + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.MessageList>" diff --git a/twilio/rest/chat/v2/service/channel/webhook.py b/twilio/rest/chat/v2/service/channel/webhook.py new file mode 100644 index 0000000000..3e31df4288 --- /dev/null +++ b/twilio/rest/chat/v2/service/channel/webhook.py @@ -0,0 +1,800 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class WebhookInstance(InstanceResource): + + class Method(object): + GET = "GET" + POST = "POST" + + class Type(object): + WEBHOOK = "webhook" + TRIGGER = "trigger" + STUDIO = "studio" + + """ + :ivar sid: The unique string that we created to identify the Channel Webhook resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Channel Webhook resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Channel Webhook resource is associated with. + :ivar channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Channel Webhook resource belongs to. + :ivar type: The type of webhook. Can be: `webhook`, `studio`, or `trigger`. + :ivar url: The absolute URL of the Channel Webhook resource. + :ivar configuration: The JSON string that describes how the channel webhook is configured. The configuration object contains the `url`, `method`, `filters`, and `retry_count` values that are configured by the create and update actions. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.type: Optional[str] = payload.get("type") + self.url: Optional[str] = payload.get("url") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[WebhookContext] = None + + @property + def _proxy(self) -> "WebhookContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WebhookContext for this WebhookInstance + """ + if self._context is None: + self._context = WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "WebhookInstance": + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WebhookInstance": + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> "WebhookInstance": + """ + Update the WebhookInstance + + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: The updated WebhookInstance + """ + return self._proxy.update( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> "WebhookInstance": + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: The updated WebhookInstance + """ + return await self._proxy.update_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.WebhookInstance {}>".format(context) + + +class WebhookContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the WebhookContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) with the Channel that has the Webhook resource to update. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Channel Webhook resource to update belongs to. This value can be the Channel resource's `sid` or `unique_name`. + :param sid: The SID of the Channel Webhook resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Webhooks/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.RetryCount": configuration_retry_count, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` = `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.RetryCount": configuration_retry_count, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.WebhookContext {}>".format(context) + + +class WebhookPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: + """ + Build an instance of WebhookInstance + + :param payload: Payload response from the API + """ + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.WebhookPage>" + + +class WebhookList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the WebhookList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) with the Channel to read the resources from. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the Channel Webhook resources to read belong to. This value can be the Channel resource's `sid` or `unique_name`. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Webhooks".format( + **self._solution + ) + + def create( + self, + type: "WebhookInstance.Type", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Create the WebhookInstance + + :param type: + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` is `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: The created WebhookInstance + """ + + data = values.of( + { + "Type": type, + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.RetryCount": configuration_retry_count, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, + type: "WebhookInstance.Type", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronously create the WebhookInstance + + :param type: + :param configuration_url: The URL of the webhook to call using the `configuration.method`. + :param configuration_method: + :param configuration_filters: The events that cause us to call the Channel Webhook. Used when `type` is `webhook`. This parameter takes only one event. To specify more than one event, repeat this parameter for each event. For the list of possible events, see [Webhook Event Triggers](https://www.twilio.com/docs/chat/webhook-events#webhook-event-trigger). + :param configuration_triggers: A string that will cause us to call the webhook when it is present in a message body. This parameter takes only one trigger string. To specify more than one, repeat this parameter for each trigger string up to a total of 5 trigger strings. Used only when `type` = `trigger`. + :param configuration_flow_sid: The SID of the Studio [Flow](https://www.twilio.com/docs/studio/rest-api/flow) to call when an event in `configuration.filters` occurs. Used only when `type` is `studio`. + :param configuration_retry_count: The number of times to retry the webhook if the first attempt fails. Can be an integer between 0 and 3, inclusive, and the default is 0. + + :returns: The created WebhookInstance + """ + + data = values.of( + { + "Type": type, + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.RetryCount": configuration_retry_count, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WebhookInstance]: + """ + Streams WebhookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WebhookInstance]: + """ + Asynchronously streams WebhookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: + """ + Lists WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: + """ + Asynchronously lists WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebhookPage: + """ + Retrieve a single page of WebhookInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebhookInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebhookPage: + """ + Asynchronously retrieve a single page of WebhookInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebhookInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> WebhookPage: + """ + Retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WebhookPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> WebhookPage: + """ + Asynchronously retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WebhookPage(self._version, response, self._solution) + + def get(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: The SID of the Channel Webhook resource to update. + """ + return WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: The SID of the Channel Webhook resource to update. + """ + return WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.WebhookList>" diff --git a/twilio/rest/chat/v2/service/role.py b/twilio/rest/chat/v2/service/role.py new file mode 100644 index 0000000000..fef06436d0 --- /dev/null +++ b/twilio/rest/chat/v2/service/role.py @@ -0,0 +1,645 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RoleInstance(InstanceResource): + + class RoleType(object): + CHANNEL = "channel" + DEPLOYMENT = "deployment" + + """ + :ivar sid: The unique string that we created to identify the Role resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Role resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Role resource is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar permissions: An array of the permissions the role has been granted. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Role resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["RoleInstance.RoleType"] = payload.get("type") + self.permissions: Optional[List[str]] = payload.get("permissions") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[RoleContext] = None + + @property + def _proxy(self) -> "RoleContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoleContext for this RoleInstance + """ + if self._context is None: + self._context = RoleContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RoleInstance": + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RoleInstance": + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return await self._proxy.fetch_async() + + def update(self, permission: List[str]) -> "RoleInstance": + """ + Update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + return self._proxy.update( + permission=permission, + ) + + async def update_async(self, permission: List[str]) -> "RoleInstance": + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + return await self._proxy.update_async( + permission=permission, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.RoleInstance {}>".format(context) + + +class RoleContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the RoleContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to update the Role resource in. + :param sid: The SID of the Role resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Roles/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update(self, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.RoleContext {}>".format(context) + + +class RolePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: + """ + Build an instance of RoleInstance + + :param payload: Payload response from the API + """ + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.RolePage>" + + +class RoleList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the RoleList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the Role resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Roles".format(**self._solution) + + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoleInstance]: + """ + Streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoleInstance]: + """ + Asynchronously streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Asynchronously lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Asynchronously retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RolePage: + """ + Retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RolePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RolePage: + """ + Asynchronously retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RolePage(self._version, response, self._solution) + + def get(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: The SID of the Role resource to update. + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: The SID of the Role resource to update. + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.RoleList>" diff --git a/twilio/rest/chat/v2/service/user/__init__.py b/twilio/rest/chat/v2/service/user/__init__.py new file mode 100644 index 0000000000..9fbde6feda --- /dev/null +++ b/twilio/rest/chat/v2/service/user/__init__.py @@ -0,0 +1,804 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.chat.v2.service.user.user_binding import UserBindingList +from twilio.rest.chat.v2.service.user.user_channel import UserChannelList + + +class UserInstance(InstanceResource): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: The unique string that we created to identify the User resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the User resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the User resource is associated with. + :ivar attributes: The JSON string that stores application-specific data. If attributes have not been set, `{}` is returned. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) assigned to the user. + :ivar identity: The application-defined string that uniquely identifies the resource's User within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). This value is often a username or an email address, and is case-sensitive. See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :ivar is_online: Whether the User is actively connected to the Service instance and online. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service's `reachability_enabled` is `false`, if the User has never been online for the Service instance, even if the Service's `reachability_enabled` is `true`. + :ivar is_notifiable: Whether the User has a potentially valid Push Notification registration (APN or GCM) for the Service instance. If at least one registration exists, `true`; otherwise `false`. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service's `reachability_enabled` is `false`, and if the User has never had a notification registration, even if the Service's `reachability_enabled` is `true`. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar joined_channels_count: The number of Channels the User is a Member of. + :ivar links: The absolute URLs of the [Channel](https://www.twilio.com/docs/chat/channels) and [Binding](https://www.twilio.com/docs/chat/rest/binding-resource) resources related to the user. + :ivar url: The absolute URL of the User resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.role_sid: Optional[str] = payload.get("role_sid") + self.identity: Optional[str] = payload.get("identity") + self.is_online: Optional[bool] = payload.get("is_online") + self.is_notifiable: Optional[bool] = payload.get("is_notifiable") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.joined_channels_count: Optional[int] = deserialize.integer( + payload.get("joined_channels_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserContext] = None + + @property + def _proxy(self) -> "UserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + @property + def user_bindings(self) -> UserBindingList: + """ + Access the user_bindings + """ + return self._proxy.user_bindings + + @property + def user_channels(self) -> UserChannelList: + """ + Access the user_channels + """ + return self._proxy.user_channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.UserInstance {}>".format(context) + + +class UserContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the UserContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to update the User resource in. + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Users/{sid}".format(**self._solution) + + self._user_bindings: Optional[UserBindingList] = None + self._user_channels: Optional[UserChannelList] = None + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the resource. It is often used for display purposes. + + :returns: The updated UserInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def user_bindings(self) -> UserBindingList: + """ + Access the user_bindings + """ + if self._user_bindings is None: + self._user_bindings = UserBindingList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._user_bindings + + @property + def user_channels(self) -> UserChannelList: + """ + Access the user_channels + """ + if self._user_channels is None: + self._user_channels = UserChannelList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._user_channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.UserContext {}>".format(context) + + +class UserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance + + :param payload: Payload response from the API + """ + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.UserPage>" + + +class UserList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the UserList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the User resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Users".format(**self._solution) + + def create( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Create the UserInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). This value is often a username or email address. See the Identity documentation for more info. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the new User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). This value is often a username or email address. See the Identity documentation for more info. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: The SID of the [Role](https://www.twilio.com/docs/chat/rest/role-resource) to assign to the new User. + :param attributes: A valid JSON string that contains application-specific data. + :param friendly_name: A descriptive string that you create to describe the new resource. This value is often used for display purposes. + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserInstance]: + """ + Streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserInstance]: + """ + Asynchronously streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Asynchronously lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserPage: + """ + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserPage: + """ + Asynchronously retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserPage(self._version, response, self._solution) + + def get(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.UserList>" diff --git a/twilio/rest/chat/v2/service/user/user_binding.py b/twilio/rest/chat/v2/service/user/user_binding.py new file mode 100644 index 0000000000..8d79c551af --- /dev/null +++ b/twilio/rest/chat/v2/service/user/user_binding.py @@ -0,0 +1,552 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UserBindingInstance(InstanceResource): + + class BindingType(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: The unique string that we created to identify the User Binding resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the User Binding resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the User Binding resource is associated with. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar endpoint: The unique endpoint identifier for the User Binding. The format of the value depends on the `binding_type`. + :ivar identity: The application-defined string that uniquely identifies the resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/chat/rest/service-resource). See [access tokens](https://www.twilio.com/docs/chat/create-tokens) for more info. + :ivar user_sid: The SID of the [User](https://www.twilio.com/docs/chat/rest/user-resource) with the User Binding resource. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :ivar credential_sid: The SID of the [Credential](https://www.twilio.com/docs/chat/rest/credential-resource) for the binding. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :ivar binding_type: + :ivar message_types: The [Programmable Chat message types](https://www.twilio.com/docs/chat/push-notification-configuration#push-types) the binding is subscribed to. + :ivar url: The absolute URL of the User Binding resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + user_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.endpoint: Optional[str] = payload.get("endpoint") + self.identity: Optional[str] = payload.get("identity") + self.user_sid: Optional[str] = payload.get("user_sid") + self.credential_sid: Optional[str] = payload.get("credential_sid") + self.binding_type: Optional["UserBindingInstance.BindingType"] = payload.get( + "binding_type" + ) + self.message_types: Optional[List[str]] = payload.get("message_types") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserBindingContext] = None + + @property + def _proxy(self) -> "UserBindingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserBindingContext for this UserBindingInstance + """ + if self._context is None: + self._context = UserBindingContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserBindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserBindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserBindingInstance": + """ + Fetch the UserBindingInstance + + + :returns: The fetched UserBindingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserBindingInstance": + """ + Asynchronous coroutine to fetch the UserBindingInstance + + + :returns: The fetched UserBindingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.UserBindingInstance {}>".format(context) + + +class UserBindingContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, user_sid: str, sid: str): + """ + Initialize the UserBindingContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the User Binding resource from. + :param user_sid: The SID of the [User](https://www.twilio.com/docs/chat/rest/user-resource) with the User Binding resource to fetch. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param sid: The SID of the User Binding resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Bindings/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the UserBindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserBindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserBindingInstance: + """ + Fetch the UserBindingInstance + + + :returns: The fetched UserBindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UserBindingInstance: + """ + Asynchronous coroutine to fetch the UserBindingInstance + + + :returns: The fetched UserBindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.UserBindingContext {}>".format(context) + + +class UserBindingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserBindingInstance: + """ + Build an instance of UserBindingInstance + + :param payload: Payload response from the API + """ + return UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.UserBindingPage>" + + +class UserBindingList(ListResource): + + def __init__(self, version: Version, service_sid: str, user_sid: str): + """ + Initialize the UserBindingList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the User Binding resources from. + :param user_sid: The SID of the [User](https://www.twilio.com/docs/chat/rest/user-resource) with the User Binding resources to read. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Bindings".format( + **self._solution + ) + + def stream( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserBindingInstance]: + """ + Streams UserBindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["UserBindingInstance.BindingType"] binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(binding_type=binding_type, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserBindingInstance]: + """ + Asynchronously streams UserBindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["UserBindingInstance.BindingType"] binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + binding_type=binding_type, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserBindingInstance]: + """ + Lists UserBindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["UserBindingInstance.BindingType"] binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + binding_type=binding_type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserBindingInstance]: + """ + Asynchronously lists UserBindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["UserBindingInstance.BindingType"] binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + binding_type=binding_type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserBindingPage: + """ + Retrieve a single page of UserBindingInstance records from the API. + Request is executed immediately + + :param binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserBindingInstance + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserBindingPage(self._version, response, self._solution) + + async def page_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserBindingPage: + """ + Asynchronously retrieve a single page of UserBindingInstance records from the API. + Request is executed immediately + + :param binding_type: The push technology used by the User Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserBindingInstance + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserBindingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserBindingPage: + """ + Retrieve a specific page of UserBindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserBindingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserBindingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserBindingPage: + """ + Asynchronously retrieve a specific page of UserBindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserBindingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserBindingPage(self._version, response, self._solution) + + def get(self, sid: str) -> UserBindingContext: + """ + Constructs a UserBindingContext + + :param sid: The SID of the User Binding resource to fetch. + """ + return UserBindingContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> UserBindingContext: + """ + Constructs a UserBindingContext + + :param sid: The SID of the User Binding resource to fetch. + """ + return UserBindingContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.UserBindingList>" diff --git a/twilio/rest/chat/v2/service/user/user_channel.py b/twilio/rest/chat/v2/service/user/user_channel.py new file mode 100644 index 0000000000..9fab357368 --- /dev/null +++ b/twilio/rest/chat/v2/service/user/user_channel.py @@ -0,0 +1,708 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UserChannelInstance(InstanceResource): + + class ChannelStatus(object): + JOINED = "joined" + INVITED = "invited" + NOT_PARTICIPATING = "not_participating" + + class NotificationLevel(object): + DEFAULT = "default" + MUTED = "muted" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the User Channel resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the User Channel resource is associated with. + :ivar channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) the User Channel resource belongs to. + :ivar user_sid: The SID of the [User](https://www.twilio.com/docs/chat/rest/user-resource) the User Channel belongs to. + :ivar member_sid: The SID of a [Member](https://www.twilio.com/docs/chat/rest/member-resource) that represents the User on the Channel. + :ivar status: + :ivar last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :ivar unread_messages_count: The number of unread Messages in the Channel for the User. Note that retrieving messages on a client endpoint does not mean that messages are consumed or read. See [Consumption Horizon feature](https://www.twilio.com/docs/chat/consumption-horizon) to learn how to mark messages as consumed. + :ivar links: The absolute URLs of the [Members](https://www.twilio.com/docs/chat/rest/member-resource), [Messages](https://www.twilio.com/docs/chat/rest/message-resource) , [Invites](https://www.twilio.com/docs/chat/rest/invite-resource) and, if it exists, the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) for the Channel. + :ivar url: The absolute URL of the User Channel resource. + :ivar notification_level: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + user_sid: str, + channel_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.user_sid: Optional[str] = payload.get("user_sid") + self.member_sid: Optional[str] = payload.get("member_sid") + self.status: Optional["UserChannelInstance.ChannelStatus"] = payload.get( + "status" + ) + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.unread_messages_count: Optional[int] = deserialize.integer( + payload.get("unread_messages_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + self.url: Optional[str] = payload.get("url") + self.notification_level: Optional["UserChannelInstance.NotificationLevel"] = ( + payload.get("notification_level") + ) + + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "channel_sid": channel_sid or self.channel_sid, + } + self._context: Optional[UserChannelContext] = None + + @property + def _proxy(self) -> "UserChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserChannelContext for this UserChannelInstance + """ + if self._context is None: + self._context = UserChannelContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the UserChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the UserChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "UserChannelInstance": + """ + Fetch the UserChannelInstance + + + :returns: The fetched UserChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserChannelInstance": + """ + Asynchronous coroutine to fetch the UserChannelInstance + + + :returns: The fetched UserChannelInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> "UserChannelInstance": + """ + Update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + + :returns: The updated UserChannelInstance + """ + return self._proxy.update( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + + async def update_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> "UserChannelInstance": + """ + Asynchronous coroutine to update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + + :returns: The updated UserChannelInstance + """ + return await self._proxy.update_async( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.UserChannelInstance {}>".format(context) + + +class UserChannelContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, user_sid: str, channel_sid: str + ): + """ + Initialize the UserChannelContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to update the User Channel resource in. + :param user_sid: The SID of the [User](https://www.twilio.com/docs/chat/rest/user-resource) to update the User Channel resource from. This value can be either the `sid` or the `identity` of the User resource. + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) with the User Channel resource to update. This value can be the Channel resource's `sid` or `unique_name`. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "channel_sid": channel_sid, + } + self._uri = ( + "/Services/{service_sid}/Users/{user_sid}/Channels/{channel_sid}".format( + **self._solution + ) + ) + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the UserChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the UserChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserChannelInstance: + """ + Fetch the UserChannelInstance + + + :returns: The fetched UserChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def fetch_async(self) -> UserChannelInstance: + """ + Asynchronous coroutine to fetch the UserChannelInstance + + + :returns: The fetched UserChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def update( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> UserChannelInstance: + """ + Update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + + :returns: The updated UserChannelInstance + """ + + data = values.of( + { + "NotificationLevel": notification_level, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def update_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> UserChannelInstance: + """ + Asynchronous coroutine to update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: The index of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) in the [Channel](https://www.twilio.com/docs/chat/channels) that the Member has read. + :param last_consumption_timestamp: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp of the last [Message](https://www.twilio.com/docs/chat/rest/message-resource) read event for the Member within the [Channel](https://www.twilio.com/docs/chat/channels). + + :returns: The updated UserChannelInstance + """ + + data = values.of( + { + "NotificationLevel": notification_level, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V2.UserChannelContext {}>".format(context) + + +class UserChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: + """ + Build an instance of UserChannelInstance + + :param payload: Payload response from the API + """ + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.UserChannelPage>" + + +class UserChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str, user_sid: str): + """ + Initialize the UserChannelList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the User Channel resources from. + :param user_sid: The SID of the [User](https://www.twilio.com/docs/chat/rest/user-resource) to read the User Channel resources from. This value can be either the `sid` or the `identity` of the User resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Channels".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserChannelInstance]: + """ + Streams UserChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserChannelInstance]: + """ + Asynchronously streams UserChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: + """ + Lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: + """ + Asynchronously lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserChannelPage: + """ + Retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserChannelPage: + """ + Asynchronously retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserChannelPage: + """ + Retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserChannelPage: + """ + Asynchronously retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserChannelPage(self._version, response, self._solution) + + def get(self, channel_sid: str) -> UserChannelContext: + """ + Constructs a UserChannelContext + + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) with the User Channel resource to update. This value can be the Channel resource's `sid` or `unique_name`. + """ + return UserChannelContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=channel_sid, + ) + + def __call__(self, channel_sid: str) -> UserChannelContext: + """ + Constructs a UserChannelContext + + :param channel_sid: The SID of the [Channel](https://www.twilio.com/docs/chat/channels) with the User Channel resource to update. This value can be the Channel resource's `sid` or `unique_name`. + """ + return UserChannelContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=channel_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V2.UserChannelList>" diff --git a/twilio/rest/chat/v3/__init__.py b/twilio/rest/chat/v3/__init__.py new file mode 100644 index 0000000000..582dc44069 --- /dev/null +++ b/twilio/rest/chat/v3/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.chat.v3.channel import ChannelList + + +class V3(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V3 version of Chat + + :param domain: The Twilio.chat domain + """ + super().__init__(domain, "v3") + self._channels: Optional[ChannelList] = None + + @property + def channels(self) -> ChannelList: + if self._channels is None: + self._channels = ChannelList(self) + return self._channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V3>" diff --git a/twilio/rest/chat/v3/channel.py b/twilio/rest/chat/v3/channel.py new file mode 100644 index 0000000000..4682838fba --- /dev/null +++ b/twilio/rest/chat/v3/channel.py @@ -0,0 +1,325 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Chat + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ChannelInstance(InstanceResource): + + class ChannelType(object): + PUBLIC = "public" + PRIVATE = "private" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: The unique string that we created to identify the Channel resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Channel resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the Channel resource is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :ivar attributes: The JSON string that stores application-specific data. If attributes have not been set, `{}` is returned. + :ivar type: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar created_by: The `identity` of the User that created the channel. If the Channel was created by using the API, the value is `system`. + :ivar members_count: The number of Members in the Channel. + :ivar messages_count: The number of Messages that have been passed in the Channel. + :ivar messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. + :ivar url: The absolute URL of the Channel resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: Optional[str] = None, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.type: Optional["ChannelInstance.ChannelType"] = payload.get("type") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + self.members_count: Optional[int] = deserialize.integer( + payload.get("members_count") + ) + self.messages_count: Optional[int] = deserialize.integer( + payload.get("messages_count") + ) + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid or self.service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None + + @property + def _proxy(self) -> "ChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ChannelContext for this ChannelInstance + """ + if self._context is None: + self._context = ChannelContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param type: + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. + + :returns: The updated ChannelInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + type=type, + messaging_service_sid=messaging_service_sid, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Asynchronous coroutine to update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param type: + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. + + :returns: The updated ChannelInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + type=type, + messaging_service_sid=messaging_service_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V3.ChannelInstance {}>".format(context) + + +class ChannelContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the ChannelContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param sid: A 34 character string that uniquely identifies this Channel. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Channels/{sid}".format(**self._solution) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param type: + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "Type": type, + "MessagingServiceSid": messaging_service_sid, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronous coroutine to update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param type: + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "Type": type, + "MessagingServiceSid": messaging_service_sid, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Chat.V3.ChannelContext {}>".format(context) + + +class ChannelList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ChannelList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, service_sid: str, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param service_sid: The unique SID identifier of the Service. + :param sid: A 34 character string that uniquely identifies this Channel. + """ + return ChannelContext(self._version, service_sid=service_sid, sid=sid) + + def __call__(self, service_sid: str, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param service_sid: The unique SID identifier of the Service. + :param sid: A 34 character string that uniquely identifies this Channel. + """ + return ChannelContext(self._version, service_sid=service_sid, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Chat.V3.ChannelList>" diff --git a/twilio/rest/content/ContentBase.py b/twilio/rest/content/ContentBase.py new file mode 100644 index 0000000000..8a1ccd5d94 --- /dev/null +++ b/twilio/rest/content/ContentBase.py @@ -0,0 +1,55 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.content.v1 import V1 +from twilio.rest.content.v2 import V2 + + +class ContentBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Content Domain + + :returns: Domain for Content + """ + super().__init__(twilio, "https://content.twilio.com") + self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Content + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Content + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Content>" diff --git a/twilio/rest/content/__init__.py b/twilio/rest/content/__init__.py new file mode 100644 index 0000000000..7663bd7138 --- /dev/null +++ b/twilio/rest/content/__init__.py @@ -0,0 +1,35 @@ +from warnings import warn + +from twilio.rest.content.ContentBase import ContentBase +from twilio.rest.content.v1.content import ContentList +from twilio.rest.content.v1.content_and_approvals import ContentAndApprovalsList +from twilio.rest.content.v1.legacy_content import LegacyContentList + + +class Content(ContentBase): + @property + def contents(self) -> ContentList: + warn( + "contents is deprecated. Use v1.contents instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.contents + + @property + def content_and_approvals(self) -> ContentAndApprovalsList: + warn( + "content_and_approvals is deprecated. Use v1.content_and_approvals instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.content_and_approvals + + @property + def legacy_contents(self) -> LegacyContentList: + warn( + "legacy_contents is deprecated. Use v1.legacy_contents instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.legacy_contents diff --git a/twilio/rest/content/v1/__init__.py b/twilio/rest/content/v1/__init__.py new file mode 100644 index 0000000000..1410fe4788 --- /dev/null +++ b/twilio/rest/content/v1/__init__.py @@ -0,0 +1,59 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.content.v1.content import ContentList +from twilio.rest.content.v1.content_and_approvals import ContentAndApprovalsList +from twilio.rest.content.v1.legacy_content import LegacyContentList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Content + + :param domain: The Twilio.content domain + """ + super().__init__(domain, "v1") + self._contents: Optional[ContentList] = None + self._content_and_approvals: Optional[ContentAndApprovalsList] = None + self._legacy_contents: Optional[LegacyContentList] = None + + @property + def contents(self) -> ContentList: + if self._contents is None: + self._contents = ContentList(self) + return self._contents + + @property + def content_and_approvals(self) -> ContentAndApprovalsList: + if self._content_and_approvals is None: + self._content_and_approvals = ContentAndApprovalsList(self) + return self._content_and_approvals + + @property + def legacy_contents(self) -> LegacyContentList: + if self._legacy_contents is None: + self._legacy_contents = LegacyContentList(self) + return self._legacy_contents + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Content.V1>" diff --git a/twilio/rest/content/v1/content/__init__.py b/twilio/rest/content/v1/content/__init__.py new file mode 100644 index 0000000000..44cc6a67bc --- /dev/null +++ b/twilio/rest/content/v1/content/__init__.py @@ -0,0 +1,2766 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.content.v1.content.approval_create import ApprovalCreateList +from twilio.rest.content.v1.content.approval_fetch import ApprovalFetchList + + +class ContentInstance(InstanceResource): + + class AuthenticationAction(object): + """ + :ivar type: + :ivar copy_code_text: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.AuthenticationActionType"] = ( + payload.get("type") + ) + self.copy_code_text: Optional[str] = payload.get("copy_code_text") + + def to_dict(self): + return { + "type": self.type, + "copy_code_text": self.copy_code_text, + } + + class CallToActionAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar code: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CallToActionActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.code: Optional[str] = payload.get("code") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "code": self.code, + "id": self.id, + } + + class CardAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar id: + :ivar code: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CardActionType"] = payload.get("type") + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.id: Optional[str] = payload.get("id") + self.code: Optional[str] = payload.get("code") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + "code": self.code, + } + + class CarouselAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CarouselActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + } + + class CarouselCard(object): + """ + :ivar title: + :ivar body: + :ivar media: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.media: Optional[str] = payload.get("media") + self.actions: Optional[List[ContentList.CarouselAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "title": self.title, + "body": self.body, + "media": self.media, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class CatalogItem(object): + """ + :ivar id: + :ivar section_title: + :ivar name: + :ivar media_url: + :ivar price: + :ivar description: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.section_title: Optional[str] = payload.get("section_title") + self.name: Optional[str] = payload.get("name") + self.media_url: Optional[str] = payload.get("media_url") + self.price: Optional[float] = payload.get("price") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "id": self.id, + "section_title": self.section_title, + "name": self.name, + "media_url": self.media_url, + "price": self.price, + "description": self.description, + } + + class ContentCreateRequest(object): + """ + :ivar friendly_name: User defined name of the content + :ivar variables: Key value pairs of variable name to value + :ivar language: Language code for the content + :ivar types: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.variables: Optional[dict[str, str]] = payload.get("variables") + self.language: Optional[str] = payload.get("language") + self.types: Optional[ContentList.Types] = payload.get("types") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "variables": self.variables, + "language": self.language, + "types": self.types.to_dict() if self.types is not None else None, + } + + class FlowsPage(object): + """ + :ivar id: + :ivar next_page_id: + :ivar title: + :ivar subtitle: + :ivar layout: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.next_page_id: Optional[str] = payload.get("next_page_id") + self.title: Optional[str] = payload.get("title") + self.subtitle: Optional[str] = payload.get("subtitle") + self.layout: Optional[List[ContentList.FlowsPageComponent]] = payload.get( + "layout" + ) + + def to_dict(self): + return { + "id": self.id, + "next_page_id": self.next_page_id, + "title": self.title, + "subtitle": self.subtitle, + "layout": ( + [layout.to_dict() for layout in self.layout] + if self.layout is not None + else None + ), + } + + class FlowsPageComponent(object): + """ + :ivar label: + :ivar type: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.label: Optional[str] = payload.get("label") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "label": self.label, + "type": self.type, + } + + class ListItem(object): + """ + :ivar id: + :ivar item: + :ivar description: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.item: Optional[str] = payload.get("item") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "id": self.id, + "item": self.item, + "description": self.description, + } + + class QuickReplyAction(object): + """ + :ivar type: + :ivar title: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.QuickReplyActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "id": self.id, + } + + class TwilioCallToAction(object): + """ + :ivar body: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.actions: Optional[List[ContentList.CallToActionAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioCard(object): + """ + :ivar title: + :ivar subtitle: + :ivar media: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.subtitle: Optional[str] = payload.get("subtitle") + self.media: Optional[List[str]] = payload.get("media") + self.actions: Optional[List[ContentList.CardAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "title": self.title, + "subtitle": self.subtitle, + "media": self.media, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioCarousel(object): + """ + :ivar body: + :ivar cards: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.cards: Optional[List[ContentList.CarouselCard]] = payload.get("cards") + + def to_dict(self): + return { + "body": self.body, + "cards": ( + [cards.to_dict() for cards in self.cards] + if self.cards is not None + else None + ), + } + + class TwilioCatalog(object): + """ + :ivar title: + :ivar body: + :ivar subtitle: + :ivar id: + :ivar items: + :ivar dynamic_items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.subtitle: Optional[str] = payload.get("subtitle") + self.id: Optional[str] = payload.get("id") + self.items: Optional[List[ContentList.CatalogItem]] = payload.get("items") + self.dynamic_items: Optional[str] = payload.get("dynamic_items") + + def to_dict(self): + return { + "title": self.title, + "body": self.body, + "subtitle": self.subtitle, + "id": self.id, + "items": ( + [items.to_dict() for items in self.items] + if self.items is not None + else None + ), + "dynamic_items": self.dynamic_items, + } + + class TwilioFlows(object): + """ + :ivar body: + :ivar button_text: + :ivar subtitle: + :ivar media_url: + :ivar pages: + :ivar type: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.button_text: Optional[str] = payload.get("button_text") + self.subtitle: Optional[str] = payload.get("subtitle") + self.media_url: Optional[str] = payload.get("media_url") + self.pages: Optional[List[ContentList.FlowsPage]] = payload.get("pages") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "body": self.body, + "button_text": self.button_text, + "subtitle": self.subtitle, + "media_url": self.media_url, + "pages": ( + [pages.to_dict() for pages in self.pages] + if self.pages is not None + else None + ), + "type": self.type, + } + + class TwilioListPicker(object): + """ + :ivar body: + :ivar button: + :ivar items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.button: Optional[str] = payload.get("button") + self.items: Optional[List[ContentList.ListItem]] = payload.get("items") + + def to_dict(self): + return { + "body": self.body, + "button": self.button, + "items": ( + [items.to_dict() for items in self.items] + if self.items is not None + else None + ), + } + + class TwilioLocation(object): + """ + :ivar latitude: + :ivar longitude: + :ivar label: + :ivar id: + :ivar address: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.latitude: Optional[float] = payload.get("latitude") + self.longitude: Optional[float] = payload.get("longitude") + self.label: Optional[str] = payload.get("label") + self.id: Optional[str] = payload.get("id") + self.address: Optional[str] = payload.get("address") + + def to_dict(self): + return { + "latitude": self.latitude, + "longitude": self.longitude, + "label": self.label, + "id": self.id, + "address": self.address, + } + + class TwilioMedia(object): + """ + :ivar body: + :ivar media: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.media: Optional[List[str]] = payload.get("media") + + def to_dict(self): + return { + "body": self.body, + "media": self.media, + } + + class TwilioQuickReply(object): + """ + :ivar body: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.actions: Optional[List[ContentList.QuickReplyAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioSchedule(object): + """ + :ivar id: + :ivar title: + :ivar time_slots: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.title: Optional[str] = payload.get("title") + self.time_slots: Optional[str] = payload.get("time_slots") + + def to_dict(self): + return { + "id": self.id, + "title": self.title, + "time_slots": self.time_slots, + } + + class TwilioText(object): + """ + :ivar body: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + + def to_dict(self): + return { + "body": self.body, + } + + class Types(object): + """ + :ivar twilio_text: + :ivar twilio_media: + :ivar twilio_location: + :ivar twilio_list_picker: + :ivar twilio_call_to_action: + :ivar twilio_quick_reply: + :ivar twilio_card: + :ivar twilio_catalog: + :ivar twilio_carousel: + :ivar twilio_flows: + :ivar twilio_schedule: + :ivar whatsapp_card: + :ivar whatsapp_authentication: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.twilio_text: Optional[ContentList.TwilioText] = payload.get( + "twilio_text" + ) + self.twilio_media: Optional[ContentList.TwilioMedia] = payload.get( + "twilio_media" + ) + self.twilio_location: Optional[ContentList.TwilioLocation] = payload.get( + "twilio_location" + ) + self.twilio_list_picker: Optional[ContentList.TwilioListPicker] = ( + payload.get("twilio_list_picker") + ) + self.twilio_call_to_action: Optional[ContentList.TwilioCallToAction] = ( + payload.get("twilio_call_to_action") + ) + self.twilio_quick_reply: Optional[ContentList.TwilioQuickReply] = ( + payload.get("twilio_quick_reply") + ) + self.twilio_card: Optional[ContentList.TwilioCard] = payload.get( + "twilio_card" + ) + self.twilio_catalog: Optional[ContentList.TwilioCatalog] = payload.get( + "twilio_catalog" + ) + self.twilio_carousel: Optional[ContentList.TwilioCarousel] = payload.get( + "twilio_carousel" + ) + self.twilio_flows: Optional[ContentList.TwilioFlows] = payload.get( + "twilio_flows" + ) + self.twilio_schedule: Optional[ContentList.TwilioSchedule] = payload.get( + "twilio_schedule" + ) + self.whatsapp_card: Optional[ContentList.WhatsappCard] = payload.get( + "whatsapp_card" + ) + self.whatsapp_authentication: Optional[ + ContentList.WhatsappAuthentication + ] = payload.get("whatsapp_authentication") + + def to_dict(self): + return { + "twilio_text": ( + self.twilio_text.to_dict() if self.twilio_text is not None else None + ), + "twilio_media": ( + self.twilio_media.to_dict() + if self.twilio_media is not None + else None + ), + "twilio_location": ( + self.twilio_location.to_dict() + if self.twilio_location is not None + else None + ), + "twilio_list_picker": ( + self.twilio_list_picker.to_dict() + if self.twilio_list_picker is not None + else None + ), + "twilio_call_to_action": ( + self.twilio_call_to_action.to_dict() + if self.twilio_call_to_action is not None + else None + ), + "twilio_quick_reply": ( + self.twilio_quick_reply.to_dict() + if self.twilio_quick_reply is not None + else None + ), + "twilio_card": ( + self.twilio_card.to_dict() if self.twilio_card is not None else None + ), + "twilio_catalog": ( + self.twilio_catalog.to_dict() + if self.twilio_catalog is not None + else None + ), + "twilio_carousel": ( + self.twilio_carousel.to_dict() + if self.twilio_carousel is not None + else None + ), + "twilio_flows": ( + self.twilio_flows.to_dict() + if self.twilio_flows is not None + else None + ), + "twilio_schedule": ( + self.twilio_schedule.to_dict() + if self.twilio_schedule is not None + else None + ), + "whatsapp_card": ( + self.whatsapp_card.to_dict() + if self.whatsapp_card is not None + else None + ), + "whatsapp_authentication": ( + self.whatsapp_authentication.to_dict() + if self.whatsapp_authentication is not None + else None + ), + } + + class WhatsappAuthentication(object): + """ + :ivar add_security_recommendation: + :ivar code_expiration_minutes: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.add_security_recommendation: Optional[bool] = payload.get( + "add_security_recommendation" + ) + self.code_expiration_minutes: Optional[float] = payload.get( + "code_expiration_minutes" + ) + self.actions: Optional[List[ContentList.AuthenticationAction]] = ( + payload.get("actions") + ) + + def to_dict(self): + return { + "add_security_recommendation": self.add_security_recommendation, + "code_expiration_minutes": self.code_expiration_minutes, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class WhatsappCard(object): + """ + :ivar body: + :ivar footer: + :ivar media: + :ivar header_text: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.footer: Optional[str] = payload.get("footer") + self.media: Optional[List[str]] = payload.get("media") + self.header_text: Optional[str] = payload.get("header_text") + self.actions: Optional[List[ContentList.CardAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "footer": self.footer, + "media": self.media, + "header_text": self.header_text, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class AuthenticationActionType(object): + COPY_CODE = "COPY_CODE" + + class CallToActionActionType(object): + URL = "URL" + PHONE_NUMBER = "PHONE_NUMBER" + COPY_CODE = "COPY_CODE" + VOICE_CALL = "VOICE_CALL" + VOICE_CALL_REQUEST = "VOICE_CALL_REQUEST" + + class CardActionType(object): + URL = "URL" + PHONE_NUMBER = "PHONE_NUMBER" + QUICK_REPLY = "QUICK_REPLY" + COPY_CODE = "COPY_CODE" + VOICE_CALL = "VOICE_CALL" + + class CarouselActionType(object): + URL = "URL" + PHONE_NUMBER = "PHONE_NUMBER" + QUICK_REPLY = "QUICK_REPLY" + + class QuickReplyActionType(object): + QUICK_REPLY = "QUICK_REPLY" + + """ + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar sid: The unique string that that we created to identify the Content resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. + :ivar friendly_name: A string name used to describe the Content resource. Not visible to the end recipient. + :ivar language: Two-letter (ISO 639-1) language code (e.g., en) identifying the language the Content resource is in. + :ivar variables: Defines the default placeholder values for variables included in the Content resource. e.g. {\"1\": \"Customer_Name\"}. + :ivar types: The [Content types](https://www.twilio.com/docs/content-api/content-types-overview) (e.g. twilio/text) for this Content resource. + :ivar url: The URL of the resource, relative to `https://content.twilio.com`. + :ivar links: A list of links related to the Content resource, such as approval_fetch and approval_create + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.language: Optional[str] = payload.get("language") + self.variables: Optional[Dict[str, object]] = payload.get("variables") + self.types: Optional[Dict[str, object]] = payload.get("types") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ContentContext] = None + + @property + def _proxy(self) -> "ContentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ContentContext for this ContentInstance + """ + if self._context is None: + self._context = ContentContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ContentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ContentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ContentInstance": + """ + Fetch the ContentInstance + + + :returns: The fetched ContentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ContentInstance": + """ + Asynchronous coroutine to fetch the ContentInstance + + + :returns: The fetched ContentInstance + """ + return await self._proxy.fetch_async() + + @property + def approval_create(self) -> ApprovalCreateList: + """ + Access the approval_create + """ + return self._proxy.approval_create + + @property + def approval_fetch(self) -> ApprovalFetchList: + """ + Access the approval_fetch + """ + return self._proxy.approval_fetch + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Content.V1.ContentInstance {}>".format(context) + + +class ContentContext(InstanceContext): + + class AuthenticationAction(object): + """ + :ivar type: + :ivar copy_code_text: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.AuthenticationActionType"] = ( + payload.get("type") + ) + self.copy_code_text: Optional[str] = payload.get("copy_code_text") + + def to_dict(self): + return { + "type": self.type, + "copy_code_text": self.copy_code_text, + } + + class CallToActionAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar code: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CallToActionActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.code: Optional[str] = payload.get("code") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "code": self.code, + "id": self.id, + } + + class CardAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar id: + :ivar code: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CardActionType"] = payload.get("type") + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.id: Optional[str] = payload.get("id") + self.code: Optional[str] = payload.get("code") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + "code": self.code, + } + + class CarouselAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CarouselActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + } + + class CarouselCard(object): + """ + :ivar title: + :ivar body: + :ivar media: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.media: Optional[str] = payload.get("media") + self.actions: Optional[List[ContentList.CarouselAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "title": self.title, + "body": self.body, + "media": self.media, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class CatalogItem(object): + """ + :ivar id: + :ivar section_title: + :ivar name: + :ivar media_url: + :ivar price: + :ivar description: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.section_title: Optional[str] = payload.get("section_title") + self.name: Optional[str] = payload.get("name") + self.media_url: Optional[str] = payload.get("media_url") + self.price: Optional[float] = payload.get("price") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "id": self.id, + "section_title": self.section_title, + "name": self.name, + "media_url": self.media_url, + "price": self.price, + "description": self.description, + } + + class ContentCreateRequest(object): + """ + :ivar friendly_name: User defined name of the content + :ivar variables: Key value pairs of variable name to value + :ivar language: Language code for the content + :ivar types: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.variables: Optional[dict[str, str]] = payload.get("variables") + self.language: Optional[str] = payload.get("language") + self.types: Optional[ContentList.Types] = payload.get("types") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "variables": self.variables, + "language": self.language, + "types": self.types.to_dict() if self.types is not None else None, + } + + class FlowsPage(object): + """ + :ivar id: + :ivar next_page_id: + :ivar title: + :ivar subtitle: + :ivar layout: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.next_page_id: Optional[str] = payload.get("next_page_id") + self.title: Optional[str] = payload.get("title") + self.subtitle: Optional[str] = payload.get("subtitle") + self.layout: Optional[List[ContentList.FlowsPageComponent]] = payload.get( + "layout" + ) + + def to_dict(self): + return { + "id": self.id, + "next_page_id": self.next_page_id, + "title": self.title, + "subtitle": self.subtitle, + "layout": ( + [layout.to_dict() for layout in self.layout] + if self.layout is not None + else None + ), + } + + class FlowsPageComponent(object): + """ + :ivar label: + :ivar type: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.label: Optional[str] = payload.get("label") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "label": self.label, + "type": self.type, + } + + class ListItem(object): + """ + :ivar id: + :ivar item: + :ivar description: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.item: Optional[str] = payload.get("item") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "id": self.id, + "item": self.item, + "description": self.description, + } + + class QuickReplyAction(object): + """ + :ivar type: + :ivar title: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.QuickReplyActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "id": self.id, + } + + class TwilioCallToAction(object): + """ + :ivar body: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.actions: Optional[List[ContentList.CallToActionAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioCard(object): + """ + :ivar title: + :ivar subtitle: + :ivar media: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.subtitle: Optional[str] = payload.get("subtitle") + self.media: Optional[List[str]] = payload.get("media") + self.actions: Optional[List[ContentList.CardAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "title": self.title, + "subtitle": self.subtitle, + "media": self.media, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioCarousel(object): + """ + :ivar body: + :ivar cards: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.cards: Optional[List[ContentList.CarouselCard]] = payload.get("cards") + + def to_dict(self): + return { + "body": self.body, + "cards": ( + [cards.to_dict() for cards in self.cards] + if self.cards is not None + else None + ), + } + + class TwilioCatalog(object): + """ + :ivar title: + :ivar body: + :ivar subtitle: + :ivar id: + :ivar items: + :ivar dynamic_items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.subtitle: Optional[str] = payload.get("subtitle") + self.id: Optional[str] = payload.get("id") + self.items: Optional[List[ContentList.CatalogItem]] = payload.get("items") + self.dynamic_items: Optional[str] = payload.get("dynamic_items") + + def to_dict(self): + return { + "title": self.title, + "body": self.body, + "subtitle": self.subtitle, + "id": self.id, + "items": ( + [items.to_dict() for items in self.items] + if self.items is not None + else None + ), + "dynamic_items": self.dynamic_items, + } + + class TwilioFlows(object): + """ + :ivar body: + :ivar button_text: + :ivar subtitle: + :ivar media_url: + :ivar pages: + :ivar type: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.button_text: Optional[str] = payload.get("button_text") + self.subtitle: Optional[str] = payload.get("subtitle") + self.media_url: Optional[str] = payload.get("media_url") + self.pages: Optional[List[ContentList.FlowsPage]] = payload.get("pages") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "body": self.body, + "button_text": self.button_text, + "subtitle": self.subtitle, + "media_url": self.media_url, + "pages": ( + [pages.to_dict() for pages in self.pages] + if self.pages is not None + else None + ), + "type": self.type, + } + + class TwilioListPicker(object): + """ + :ivar body: + :ivar button: + :ivar items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.button: Optional[str] = payload.get("button") + self.items: Optional[List[ContentList.ListItem]] = payload.get("items") + + def to_dict(self): + return { + "body": self.body, + "button": self.button, + "items": ( + [items.to_dict() for items in self.items] + if self.items is not None + else None + ), + } + + class TwilioLocation(object): + """ + :ivar latitude: + :ivar longitude: + :ivar label: + :ivar id: + :ivar address: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.latitude: Optional[float] = payload.get("latitude") + self.longitude: Optional[float] = payload.get("longitude") + self.label: Optional[str] = payload.get("label") + self.id: Optional[str] = payload.get("id") + self.address: Optional[str] = payload.get("address") + + def to_dict(self): + return { + "latitude": self.latitude, + "longitude": self.longitude, + "label": self.label, + "id": self.id, + "address": self.address, + } + + class TwilioMedia(object): + """ + :ivar body: + :ivar media: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.media: Optional[List[str]] = payload.get("media") + + def to_dict(self): + return { + "body": self.body, + "media": self.media, + } + + class TwilioQuickReply(object): + """ + :ivar body: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.actions: Optional[List[ContentList.QuickReplyAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioSchedule(object): + """ + :ivar id: + :ivar title: + :ivar time_slots: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.title: Optional[str] = payload.get("title") + self.time_slots: Optional[str] = payload.get("time_slots") + + def to_dict(self): + return { + "id": self.id, + "title": self.title, + "time_slots": self.time_slots, + } + + class TwilioText(object): + """ + :ivar body: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + + def to_dict(self): + return { + "body": self.body, + } + + class Types(object): + """ + :ivar twilio_text: + :ivar twilio_media: + :ivar twilio_location: + :ivar twilio_list_picker: + :ivar twilio_call_to_action: + :ivar twilio_quick_reply: + :ivar twilio_card: + :ivar twilio_catalog: + :ivar twilio_carousel: + :ivar twilio_flows: + :ivar twilio_schedule: + :ivar whatsapp_card: + :ivar whatsapp_authentication: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.twilio_text: Optional[ContentList.TwilioText] = payload.get( + "twilio_text" + ) + self.twilio_media: Optional[ContentList.TwilioMedia] = payload.get( + "twilio_media" + ) + self.twilio_location: Optional[ContentList.TwilioLocation] = payload.get( + "twilio_location" + ) + self.twilio_list_picker: Optional[ContentList.TwilioListPicker] = ( + payload.get("twilio_list_picker") + ) + self.twilio_call_to_action: Optional[ContentList.TwilioCallToAction] = ( + payload.get("twilio_call_to_action") + ) + self.twilio_quick_reply: Optional[ContentList.TwilioQuickReply] = ( + payload.get("twilio_quick_reply") + ) + self.twilio_card: Optional[ContentList.TwilioCard] = payload.get( + "twilio_card" + ) + self.twilio_catalog: Optional[ContentList.TwilioCatalog] = payload.get( + "twilio_catalog" + ) + self.twilio_carousel: Optional[ContentList.TwilioCarousel] = payload.get( + "twilio_carousel" + ) + self.twilio_flows: Optional[ContentList.TwilioFlows] = payload.get( + "twilio_flows" + ) + self.twilio_schedule: Optional[ContentList.TwilioSchedule] = payload.get( + "twilio_schedule" + ) + self.whatsapp_card: Optional[ContentList.WhatsappCard] = payload.get( + "whatsapp_card" + ) + self.whatsapp_authentication: Optional[ + ContentList.WhatsappAuthentication + ] = payload.get("whatsapp_authentication") + + def to_dict(self): + return { + "twilio_text": ( + self.twilio_text.to_dict() if self.twilio_text is not None else None + ), + "twilio_media": ( + self.twilio_media.to_dict() + if self.twilio_media is not None + else None + ), + "twilio_location": ( + self.twilio_location.to_dict() + if self.twilio_location is not None + else None + ), + "twilio_list_picker": ( + self.twilio_list_picker.to_dict() + if self.twilio_list_picker is not None + else None + ), + "twilio_call_to_action": ( + self.twilio_call_to_action.to_dict() + if self.twilio_call_to_action is not None + else None + ), + "twilio_quick_reply": ( + self.twilio_quick_reply.to_dict() + if self.twilio_quick_reply is not None + else None + ), + "twilio_card": ( + self.twilio_card.to_dict() if self.twilio_card is not None else None + ), + "twilio_catalog": ( + self.twilio_catalog.to_dict() + if self.twilio_catalog is not None + else None + ), + "twilio_carousel": ( + self.twilio_carousel.to_dict() + if self.twilio_carousel is not None + else None + ), + "twilio_flows": ( + self.twilio_flows.to_dict() + if self.twilio_flows is not None + else None + ), + "twilio_schedule": ( + self.twilio_schedule.to_dict() + if self.twilio_schedule is not None + else None + ), + "whatsapp_card": ( + self.whatsapp_card.to_dict() + if self.whatsapp_card is not None + else None + ), + "whatsapp_authentication": ( + self.whatsapp_authentication.to_dict() + if self.whatsapp_authentication is not None + else None + ), + } + + class WhatsappAuthentication(object): + """ + :ivar add_security_recommendation: + :ivar code_expiration_minutes: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.add_security_recommendation: Optional[bool] = payload.get( + "add_security_recommendation" + ) + self.code_expiration_minutes: Optional[float] = payload.get( + "code_expiration_minutes" + ) + self.actions: Optional[List[ContentList.AuthenticationAction]] = ( + payload.get("actions") + ) + + def to_dict(self): + return { + "add_security_recommendation": self.add_security_recommendation, + "code_expiration_minutes": self.code_expiration_minutes, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class WhatsappCard(object): + """ + :ivar body: + :ivar footer: + :ivar media: + :ivar header_text: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.footer: Optional[str] = payload.get("footer") + self.media: Optional[List[str]] = payload.get("media") + self.header_text: Optional[str] = payload.get("header_text") + self.actions: Optional[List[ContentList.CardAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "footer": self.footer, + "media": self.media, + "header_text": self.header_text, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + def __init__(self, version: Version, sid: str): + """ + Initialize the ContentContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Content resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Content/{sid}".format(**self._solution) + + self._approval_create: Optional[ApprovalCreateList] = None + self._approval_fetch: Optional[ApprovalFetchList] = None + + def delete(self) -> bool: + """ + Deletes the ContentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ContentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ContentInstance: + """ + Fetch the ContentInstance + + + :returns: The fetched ContentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ContentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ContentInstance: + """ + Asynchronous coroutine to fetch the ContentInstance + + + :returns: The fetched ContentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ContentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + @property + def approval_create(self) -> ApprovalCreateList: + """ + Access the approval_create + """ + if self._approval_create is None: + self._approval_create = ApprovalCreateList( + self._version, + self._solution["sid"], + ) + return self._approval_create + + @property + def approval_fetch(self) -> ApprovalFetchList: + """ + Access the approval_fetch + """ + if self._approval_fetch is None: + self._approval_fetch = ApprovalFetchList( + self._version, + self._solution["sid"], + ) + return self._approval_fetch + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Content.V1.ContentContext {}>".format(context) + + +class ContentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ContentInstance: + """ + Build an instance of ContentInstance + + :param payload: Payload response from the API + """ + return ContentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Content.V1.ContentPage>" + + +class ContentList(ListResource): + + class AuthenticationAction(object): + """ + :ivar type: + :ivar copy_code_text: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.AuthenticationActionType"] = ( + payload.get("type") + ) + self.copy_code_text: Optional[str] = payload.get("copy_code_text") + + def to_dict(self): + return { + "type": self.type, + "copy_code_text": self.copy_code_text, + } + + class CallToActionAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar code: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CallToActionActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.code: Optional[str] = payload.get("code") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "code": self.code, + "id": self.id, + } + + class CardAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar id: + :ivar code: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CardActionType"] = payload.get("type") + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.id: Optional[str] = payload.get("id") + self.code: Optional[str] = payload.get("code") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + "code": self.code, + } + + class CarouselAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CarouselActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + } + + class CarouselCard(object): + """ + :ivar title: + :ivar body: + :ivar media: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.media: Optional[str] = payload.get("media") + self.actions: Optional[List[ContentList.CarouselAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "title": self.title, + "body": self.body, + "media": self.media, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class CatalogItem(object): + """ + :ivar id: + :ivar section_title: + :ivar name: + :ivar media_url: + :ivar price: + :ivar description: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.section_title: Optional[str] = payload.get("section_title") + self.name: Optional[str] = payload.get("name") + self.media_url: Optional[str] = payload.get("media_url") + self.price: Optional[float] = payload.get("price") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "id": self.id, + "section_title": self.section_title, + "name": self.name, + "media_url": self.media_url, + "price": self.price, + "description": self.description, + } + + class ContentCreateRequest(object): + """ + :ivar friendly_name: User defined name of the content + :ivar variables: Key value pairs of variable name to value + :ivar language: Language code for the content + :ivar types: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.variables: Optional[dict[str, str]] = payload.get("variables") + self.language: Optional[str] = payload.get("language") + self.types: Optional[ContentList.Types] = payload.get("types") + + def to_dict(self): + return { + "friendly_name": self.friendly_name, + "variables": self.variables, + "language": self.language, + "types": self.types.to_dict() if self.types is not None else None, + } + + class FlowsPage(object): + """ + :ivar id: + :ivar next_page_id: + :ivar title: + :ivar subtitle: + :ivar layout: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.next_page_id: Optional[str] = payload.get("next_page_id") + self.title: Optional[str] = payload.get("title") + self.subtitle: Optional[str] = payload.get("subtitle") + self.layout: Optional[List[ContentList.FlowsPageComponent]] = payload.get( + "layout" + ) + + def to_dict(self): + return { + "id": self.id, + "next_page_id": self.next_page_id, + "title": self.title, + "subtitle": self.subtitle, + "layout": ( + [layout.to_dict() for layout in self.layout] + if self.layout is not None + else None + ), + } + + class FlowsPageComponent(object): + """ + :ivar label: + :ivar type: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.label: Optional[str] = payload.get("label") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "label": self.label, + "type": self.type, + } + + class ListItem(object): + """ + :ivar id: + :ivar item: + :ivar description: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.item: Optional[str] = payload.get("item") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "id": self.id, + "item": self.item, + "description": self.description, + } + + class QuickReplyAction(object): + """ + :ivar type: + :ivar title: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.QuickReplyActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "id": self.id, + } + + class TwilioCallToAction(object): + """ + :ivar body: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.actions: Optional[List[ContentList.CallToActionAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioCard(object): + """ + :ivar title: + :ivar subtitle: + :ivar media: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.subtitle: Optional[str] = payload.get("subtitle") + self.media: Optional[List[str]] = payload.get("media") + self.actions: Optional[List[ContentList.CardAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "title": self.title, + "subtitle": self.subtitle, + "media": self.media, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioCarousel(object): + """ + :ivar body: + :ivar cards: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.cards: Optional[List[ContentList.CarouselCard]] = payload.get("cards") + + def to_dict(self): + return { + "body": self.body, + "cards": ( + [cards.to_dict() for cards in self.cards] + if self.cards is not None + else None + ), + } + + class TwilioCatalog(object): + """ + :ivar title: + :ivar body: + :ivar subtitle: + :ivar id: + :ivar items: + :ivar dynamic_items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.subtitle: Optional[str] = payload.get("subtitle") + self.id: Optional[str] = payload.get("id") + self.items: Optional[List[ContentList.CatalogItem]] = payload.get("items") + self.dynamic_items: Optional[str] = payload.get("dynamic_items") + + def to_dict(self): + return { + "title": self.title, + "body": self.body, + "subtitle": self.subtitle, + "id": self.id, + "items": ( + [items.to_dict() for items in self.items] + if self.items is not None + else None + ), + "dynamic_items": self.dynamic_items, + } + + class TwilioFlows(object): + """ + :ivar body: + :ivar button_text: + :ivar subtitle: + :ivar media_url: + :ivar pages: + :ivar type: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.button_text: Optional[str] = payload.get("button_text") + self.subtitle: Optional[str] = payload.get("subtitle") + self.media_url: Optional[str] = payload.get("media_url") + self.pages: Optional[List[ContentList.FlowsPage]] = payload.get("pages") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "body": self.body, + "button_text": self.button_text, + "subtitle": self.subtitle, + "media_url": self.media_url, + "pages": ( + [pages.to_dict() for pages in self.pages] + if self.pages is not None + else None + ), + "type": self.type, + } + + class TwilioListPicker(object): + """ + :ivar body: + :ivar button: + :ivar items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.button: Optional[str] = payload.get("button") + self.items: Optional[List[ContentList.ListItem]] = payload.get("items") + + def to_dict(self): + return { + "body": self.body, + "button": self.button, + "items": ( + [items.to_dict() for items in self.items] + if self.items is not None + else None + ), + } + + class TwilioLocation(object): + """ + :ivar latitude: + :ivar longitude: + :ivar label: + :ivar id: + :ivar address: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.latitude: Optional[float] = payload.get("latitude") + self.longitude: Optional[float] = payload.get("longitude") + self.label: Optional[str] = payload.get("label") + self.id: Optional[str] = payload.get("id") + self.address: Optional[str] = payload.get("address") + + def to_dict(self): + return { + "latitude": self.latitude, + "longitude": self.longitude, + "label": self.label, + "id": self.id, + "address": self.address, + } + + class TwilioMedia(object): + """ + :ivar body: + :ivar media: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.media: Optional[List[str]] = payload.get("media") + + def to_dict(self): + return { + "body": self.body, + "media": self.media, + } + + class TwilioQuickReply(object): + """ + :ivar body: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.actions: Optional[List[ContentList.QuickReplyAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioSchedule(object): + """ + :ivar id: + :ivar title: + :ivar time_slots: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.title: Optional[str] = payload.get("title") + self.time_slots: Optional[str] = payload.get("time_slots") + + def to_dict(self): + return { + "id": self.id, + "title": self.title, + "time_slots": self.time_slots, + } + + class TwilioText(object): + """ + :ivar body: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + + def to_dict(self): + return { + "body": self.body, + } + + class Types(object): + """ + :ivar twilio_text: + :ivar twilio_media: + :ivar twilio_location: + :ivar twilio_list_picker: + :ivar twilio_call_to_action: + :ivar twilio_quick_reply: + :ivar twilio_card: + :ivar twilio_catalog: + :ivar twilio_carousel: + :ivar twilio_flows: + :ivar twilio_schedule: + :ivar whatsapp_card: + :ivar whatsapp_authentication: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.twilio_text: Optional[ContentList.TwilioText] = payload.get( + "twilio_text" + ) + self.twilio_media: Optional[ContentList.TwilioMedia] = payload.get( + "twilio_media" + ) + self.twilio_location: Optional[ContentList.TwilioLocation] = payload.get( + "twilio_location" + ) + self.twilio_list_picker: Optional[ContentList.TwilioListPicker] = ( + payload.get("twilio_list_picker") + ) + self.twilio_call_to_action: Optional[ContentList.TwilioCallToAction] = ( + payload.get("twilio_call_to_action") + ) + self.twilio_quick_reply: Optional[ContentList.TwilioQuickReply] = ( + payload.get("twilio_quick_reply") + ) + self.twilio_card: Optional[ContentList.TwilioCard] = payload.get( + "twilio_card" + ) + self.twilio_catalog: Optional[ContentList.TwilioCatalog] = payload.get( + "twilio_catalog" + ) + self.twilio_carousel: Optional[ContentList.TwilioCarousel] = payload.get( + "twilio_carousel" + ) + self.twilio_flows: Optional[ContentList.TwilioFlows] = payload.get( + "twilio_flows" + ) + self.twilio_schedule: Optional[ContentList.TwilioSchedule] = payload.get( + "twilio_schedule" + ) + self.whatsapp_card: Optional[ContentList.WhatsappCard] = payload.get( + "whatsapp_card" + ) + self.whatsapp_authentication: Optional[ + ContentList.WhatsappAuthentication + ] = payload.get("whatsapp_authentication") + + def to_dict(self): + return { + "twilio_text": ( + self.twilio_text.to_dict() if self.twilio_text is not None else None + ), + "twilio_media": ( + self.twilio_media.to_dict() + if self.twilio_media is not None + else None + ), + "twilio_location": ( + self.twilio_location.to_dict() + if self.twilio_location is not None + else None + ), + "twilio_list_picker": ( + self.twilio_list_picker.to_dict() + if self.twilio_list_picker is not None + else None + ), + "twilio_call_to_action": ( + self.twilio_call_to_action.to_dict() + if self.twilio_call_to_action is not None + else None + ), + "twilio_quick_reply": ( + self.twilio_quick_reply.to_dict() + if self.twilio_quick_reply is not None + else None + ), + "twilio_card": ( + self.twilio_card.to_dict() if self.twilio_card is not None else None + ), + "twilio_catalog": ( + self.twilio_catalog.to_dict() + if self.twilio_catalog is not None + else None + ), + "twilio_carousel": ( + self.twilio_carousel.to_dict() + if self.twilio_carousel is not None + else None + ), + "twilio_flows": ( + self.twilio_flows.to_dict() + if self.twilio_flows is not None + else None + ), + "twilio_schedule": ( + self.twilio_schedule.to_dict() + if self.twilio_schedule is not None + else None + ), + "whatsapp_card": ( + self.whatsapp_card.to_dict() + if self.whatsapp_card is not None + else None + ), + "whatsapp_authentication": ( + self.whatsapp_authentication.to_dict() + if self.whatsapp_authentication is not None + else None + ), + } + + class WhatsappAuthentication(object): + """ + :ivar add_security_recommendation: + :ivar code_expiration_minutes: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.add_security_recommendation: Optional[bool] = payload.get( + "add_security_recommendation" + ) + self.code_expiration_minutes: Optional[float] = payload.get( + "code_expiration_minutes" + ) + self.actions: Optional[List[ContentList.AuthenticationAction]] = ( + payload.get("actions") + ) + + def to_dict(self): + return { + "add_security_recommendation": self.add_security_recommendation, + "code_expiration_minutes": self.code_expiration_minutes, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class WhatsappCard(object): + """ + :ivar body: + :ivar footer: + :ivar media: + :ivar header_text: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.footer: Optional[str] = payload.get("footer") + self.media: Optional[List[str]] = payload.get("media") + self.header_text: Optional[str] = payload.get("header_text") + self.actions: Optional[List[ContentList.CardAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "footer": self.footer, + "media": self.media, + "header_text": self.header_text, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + def __init__(self, version: Version): + """ + Initialize the ContentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Content" + + def create(self, content_create_request: ContentCreateRequest) -> ContentInstance: + """ + Create the ContentInstance + + :param content_create_request: + + :returns: The created ContentInstance + """ + data = content_create_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ContentInstance(self._version, payload) + + async def create_async( + self, content_create_request: ContentCreateRequest + ) -> ContentInstance: + """ + Asynchronously create the ContentInstance + + :param content_create_request: + + :returns: The created ContentInstance + """ + data = content_create_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ContentInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ContentInstance]: + """ + Streams ContentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ContentInstance]: + """ + Asynchronously streams ContentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ContentInstance]: + """ + Lists ContentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ContentInstance]: + """ + Asynchronously lists ContentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ContentPage: + """ + Retrieve a single page of ContentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ContentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ContentPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ContentPage: + """ + Asynchronously retrieve a single page of ContentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ContentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ContentPage(self._version, response) + + def get_page(self, target_url: str) -> ContentPage: + """ + Retrieve a specific page of ContentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ContentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ContentPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ContentPage: + """ + Asynchronously retrieve a specific page of ContentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ContentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ContentPage(self._version, response) + + def get(self, sid: str) -> ContentContext: + """ + Constructs a ContentContext + + :param sid: The Twilio-provided string that uniquely identifies the Content resource to fetch. + """ + return ContentContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ContentContext: + """ + Constructs a ContentContext + + :param sid: The Twilio-provided string that uniquely identifies the Content resource to fetch. + """ + return ContentContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Content.V1.ContentList>" diff --git a/twilio/rest/content/v1/content/approval_create.py b/twilio/rest/content/v1/content/approval_create.py new file mode 100644 index 0000000000..9f34064e35 --- /dev/null +++ b/twilio/rest/content/v1/content/approval_create.py @@ -0,0 +1,172 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ApprovalCreateInstance(InstanceResource): + + class ContentApprovalRequest(object): + """ + :ivar name: Name of the template. + :ivar category: A WhatsApp recognized template category. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.category: Optional[str] = payload.get("category") + + def to_dict(self): + return { + "name": self.name, + "category": self.category, + } + + """ + :ivar name: + :ivar category: + :ivar content_type: + :ivar status: + :ivar rejection_reason: + :ivar allow_category_change: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], content_sid: str): + super().__init__(version) + + self.name: Optional[str] = payload.get("name") + self.category: Optional[str] = payload.get("category") + self.content_type: Optional[str] = payload.get("content_type") + self.status: Optional[str] = payload.get("status") + self.rejection_reason: Optional[str] = payload.get("rejection_reason") + self.allow_category_change: Optional[bool] = payload.get( + "allow_category_change" + ) + + self._solution = { + "content_sid": content_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Content.V1.ApprovalCreateInstance {}>".format(context) + + +class ApprovalCreateList(ListResource): + + class ContentApprovalRequest(object): + """ + :ivar name: Name of the template. + :ivar category: A WhatsApp recognized template category. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.category: Optional[str] = payload.get("category") + + def to_dict(self): + return { + "name": self.name, + "category": self.category, + } + + def __init__(self, version: Version, content_sid: str): + """ + Initialize the ApprovalCreateList + + :param version: Version that contains the resource + :param content_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "content_sid": content_sid, + } + self._uri = "/Content/{content_sid}/ApprovalRequests/whatsapp".format( + **self._solution + ) + + def create( + self, content_approval_request: ContentApprovalRequest + ) -> ApprovalCreateInstance: + """ + Create the ApprovalCreateInstance + + :param content_approval_request: + + :returns: The created ApprovalCreateInstance + """ + data = content_approval_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ApprovalCreateInstance( + self._version, payload, content_sid=self._solution["content_sid"] + ) + + async def create_async( + self, content_approval_request: ContentApprovalRequest + ) -> ApprovalCreateInstance: + """ + Asynchronously create the ApprovalCreateInstance + + :param content_approval_request: + + :returns: The created ApprovalCreateInstance + """ + data = content_approval_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ApprovalCreateInstance( + self._version, payload, content_sid=self._solution["content_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Content.V1.ApprovalCreateList>" diff --git a/twilio/rest/content/v1/content/approval_fetch.py b/twilio/rest/content/v1/content/approval_fetch.py new file mode 100644 index 0000000000..d3d00e5058 --- /dev/null +++ b/twilio/rest/content/v1/content/approval_fetch.py @@ -0,0 +1,193 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ApprovalFetchInstance(InstanceResource): + """ + :ivar sid: The unique string that that we created to identify the Content resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. + :ivar whatsapp: Contains the whatsapp approval information for the Content resource, with fields such as approval status, rejection reason, and category, amongst others. + :ivar url: The URL of the resource, relative to `https://content.twilio.com`. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.whatsapp: Optional[Dict[str, object]] = payload.get("whatsapp") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid, + } + self._context: Optional[ApprovalFetchContext] = None + + @property + def _proxy(self) -> "ApprovalFetchContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ApprovalFetchContext for this ApprovalFetchInstance + """ + if self._context is None: + self._context = ApprovalFetchContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ApprovalFetchInstance": + """ + Fetch the ApprovalFetchInstance + + + :returns: The fetched ApprovalFetchInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ApprovalFetchInstance": + """ + Asynchronous coroutine to fetch the ApprovalFetchInstance + + + :returns: The fetched ApprovalFetchInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Content.V1.ApprovalFetchInstance {}>".format(context) + + +class ApprovalFetchContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ApprovalFetchContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Content resource whose approval information to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Content/{sid}/ApprovalRequests".format(**self._solution) + + def fetch(self) -> ApprovalFetchInstance: + """ + Fetch the ApprovalFetchInstance + + + :returns: The fetched ApprovalFetchInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ApprovalFetchInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ApprovalFetchInstance: + """ + Asynchronous coroutine to fetch the ApprovalFetchInstance + + + :returns: The fetched ApprovalFetchInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ApprovalFetchInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Content.V1.ApprovalFetchContext {}>".format(context) + + +class ApprovalFetchList(ListResource): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ApprovalFetchList + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Content resource whose approval information to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + + def get(self) -> ApprovalFetchContext: + """ + Constructs a ApprovalFetchContext + + """ + return ApprovalFetchContext(self._version, sid=self._solution["sid"]) + + def __call__(self) -> ApprovalFetchContext: + """ + Constructs a ApprovalFetchContext + + """ + return ApprovalFetchContext(self._version, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Content.V1.ApprovalFetchList>" diff --git a/twilio/rest/content/v1/content_and_approvals.py b/twilio/rest/content/v1/content_and_approvals.py new file mode 100644 index 0000000000..c2a210665d --- /dev/null +++ b/twilio/rest/content/v1/content_and_approvals.py @@ -0,0 +1,298 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ContentAndApprovalsInstance(InstanceResource): + """ + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar sid: The unique string that that we created to identify the Content resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. + :ivar friendly_name: A string name used to describe the Content resource. Not visible to the end recipient. + :ivar language: Two-letter (ISO 639-1) language code (e.g., en) identifying the language the Content resource is in. + :ivar variables: Defines the default placeholder values for variables included in the Content resource. e.g. {\"1\": \"Customer_Name\"}. + :ivar types: The [Content types](https://www.twilio.com/docs/content-api/content-types-overview) (e.g. twilio/text) for this Content resource. + :ivar approval_requests: The submitted information and approval request status of the Content resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.language: Optional[str] = payload.get("language") + self.variables: Optional[Dict[str, object]] = payload.get("variables") + self.types: Optional[Dict[str, object]] = payload.get("types") + self.approval_requests: Optional[Dict[str, object]] = payload.get( + "approval_requests" + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Content.V1.ContentAndApprovalsInstance>" + + +class ContentAndApprovalsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ContentAndApprovalsInstance: + """ + Build an instance of ContentAndApprovalsInstance + + :param payload: Payload response from the API + """ + return ContentAndApprovalsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Content.V1.ContentAndApprovalsPage>" + + +class ContentAndApprovalsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ContentAndApprovalsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ContentAndApprovals" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ContentAndApprovalsInstance]: + """ + Streams ContentAndApprovalsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ContentAndApprovalsInstance]: + """ + Asynchronously streams ContentAndApprovalsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ContentAndApprovalsInstance]: + """ + Lists ContentAndApprovalsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ContentAndApprovalsInstance]: + """ + Asynchronously lists ContentAndApprovalsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ContentAndApprovalsPage: + """ + Retrieve a single page of ContentAndApprovalsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ContentAndApprovalsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ContentAndApprovalsPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ContentAndApprovalsPage: + """ + Asynchronously retrieve a single page of ContentAndApprovalsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ContentAndApprovalsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ContentAndApprovalsPage(self._version, response) + + def get_page(self, target_url: str) -> ContentAndApprovalsPage: + """ + Retrieve a specific page of ContentAndApprovalsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ContentAndApprovalsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ContentAndApprovalsPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ContentAndApprovalsPage: + """ + Asynchronously retrieve a specific page of ContentAndApprovalsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ContentAndApprovalsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ContentAndApprovalsPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Content.V1.ContentAndApprovalsList>" diff --git a/twilio/rest/content/v1/legacy_content.py b/twilio/rest/content/v1/legacy_content.py new file mode 100644 index 0000000000..d32778e748 --- /dev/null +++ b/twilio/rest/content/v1/legacy_content.py @@ -0,0 +1,300 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class LegacyContentInstance(InstanceResource): + """ + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar sid: The unique string that that we created to identify the Content resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. + :ivar friendly_name: A string name used to describe the Content resource. Not visible to the end recipient. + :ivar language: Two-letter (ISO 639-1) language code (e.g., en) identifying the language the Content resource is in. + :ivar variables: Defines the default placeholder values for variables included in the Content resource. e.g. {\"1\": \"Customer_Name\"}. + :ivar types: The [Content types](https://www.twilio.com/docs/content-api/content-types-overview) (e.g. twilio/text) for this Content resource. + :ivar legacy_template_name: The string name of the legacy content template associated with this Content resource, unique across all template names for its account. Only lowercase letters, numbers and underscores are allowed + :ivar legacy_body: The string body field of the legacy content template associated with this Content resource + :ivar url: The URL of the resource, relative to `https://content.twilio.com`. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.language: Optional[str] = payload.get("language") + self.variables: Optional[Dict[str, object]] = payload.get("variables") + self.types: Optional[Dict[str, object]] = payload.get("types") + self.legacy_template_name: Optional[str] = payload.get("legacy_template_name") + self.legacy_body: Optional[str] = payload.get("legacy_body") + self.url: Optional[str] = payload.get("url") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Content.V1.LegacyContentInstance>" + + +class LegacyContentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> LegacyContentInstance: + """ + Build an instance of LegacyContentInstance + + :param payload: Payload response from the API + """ + return LegacyContentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Content.V1.LegacyContentPage>" + + +class LegacyContentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the LegacyContentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/LegacyContent" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[LegacyContentInstance]: + """ + Streams LegacyContentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[LegacyContentInstance]: + """ + Asynchronously streams LegacyContentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LegacyContentInstance]: + """ + Lists LegacyContentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LegacyContentInstance]: + """ + Asynchronously lists LegacyContentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LegacyContentPage: + """ + Retrieve a single page of LegacyContentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LegacyContentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LegacyContentPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LegacyContentPage: + """ + Asynchronously retrieve a single page of LegacyContentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LegacyContentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LegacyContentPage(self._version, response) + + def get_page(self, target_url: str) -> LegacyContentPage: + """ + Retrieve a specific page of LegacyContentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of LegacyContentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return LegacyContentPage(self._version, response) + + async def get_page_async(self, target_url: str) -> LegacyContentPage: + """ + Asynchronously retrieve a specific page of LegacyContentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of LegacyContentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return LegacyContentPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Content.V1.LegacyContentList>" diff --git a/twilio/rest/content/v2/__init__.py b/twilio/rest/content/v2/__init__.py new file mode 100644 index 0000000000..ca6d8bcd74 --- /dev/null +++ b/twilio/rest/content/v2/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.content.v2.content import ContentList +from twilio.rest.content.v2.content_and_approvals import ContentAndApprovalsList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Content + + :param domain: The Twilio.content domain + """ + super().__init__(domain, "v2") + self._contents: Optional[ContentList] = None + self._content_and_approvals: Optional[ContentAndApprovalsList] = None + + @property + def contents(self) -> ContentList: + if self._contents is None: + self._contents = ContentList(self) + return self._contents + + @property + def content_and_approvals(self) -> ContentAndApprovalsList: + if self._content_and_approvals is None: + self._content_and_approvals = ContentAndApprovalsList(self) + return self._content_and_approvals + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Content.V2>" diff --git a/twilio/rest/content/v2/content.py b/twilio/rest/content/v2/content.py new file mode 100644 index 0000000000..c2e2db7d8c --- /dev/null +++ b/twilio/rest/content/v2/content.py @@ -0,0 +1,464 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ContentInstance(InstanceResource): + """ + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar sid: The unique string that that we created to identify the Content resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. + :ivar friendly_name: A string name used to describe the Content resource. Not visible to the end recipient. + :ivar language: Two-letter (ISO 639-1) language code (e.g., en) identifying the language the Content resource is in. + :ivar variables: Defines the default placeholder values for variables included in the Content resource. e.g. {\"1\": \"Customer_Name\"}. + :ivar types: The [Content types](https://www.twilio.com/docs/content/content-types-overview) (e.g. twilio/text) for this Content resource. + :ivar url: The URL of the resource, relative to `https://content.twilio.com`. + :ivar links: A list of links related to the Content resource, such as approval_fetch and approval_create + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.language: Optional[str] = payload.get("language") + self.variables: Optional[Dict[str, object]] = payload.get("variables") + self.types: Optional[Dict[str, object]] = payload.get("types") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Content.V2.ContentInstance>" + + +class ContentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ContentInstance: + """ + Build an instance of ContentInstance + + :param payload: Payload response from the API + """ + return ContentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Content.V2.ContentPage>" + + +class ContentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ContentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Content" + + def stream( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ContentInstance]: + """ + Streams ContentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=<channel>:<status> + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ContentInstance]: + """ + Asynchronously streams ContentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=<channel>:<status> + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ContentInstance]: + """ + Lists ContentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=<channel>:<status> + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ContentInstance]: + """ + Asynchronously lists ContentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=<channel>:<status> + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ContentPage: + """ + Retrieve a single page of ContentInstance records from the API. + Request is executed immediately + + :param sort_by_date: Whether to sort by ascending or descending date updated + :param sort_by_content_name: Whether to sort by ascending or descending content name + :param date_created_after: Filter by >=[date-time] + :param date_created_before: Filter by <=[date-time] + :param content_name: Filter by Regex Pattern in content name + :param content: Filter by Regex Pattern in template content + :param language: Filter by array of valid language(s) + :param content_type: Filter by array of contentType(s) + :param channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=<channel>:<status> + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ContentInstance + """ + data = values.of( + { + "SortByDate": sort_by_date, + "SortByContentName": sort_by_content_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ContentName": content_name, + "Content": content, + "Language": serialize.map(language, lambda e: e), + "ContentType": serialize.map(content_type, lambda e: e), + "ChannelEligibility": serialize.map(channel_eligibility, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ContentPage(self._version, response) + + async def page_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ContentPage: + """ + Asynchronously retrieve a single page of ContentInstance records from the API. + Request is executed immediately + + :param sort_by_date: Whether to sort by ascending or descending date updated + :param sort_by_content_name: Whether to sort by ascending or descending content name + :param date_created_after: Filter by >=[date-time] + :param date_created_before: Filter by <=[date-time] + :param content_name: Filter by Regex Pattern in content name + :param content: Filter by Regex Pattern in template content + :param language: Filter by array of valid language(s) + :param content_type: Filter by array of contentType(s) + :param channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=<channel>:<status> + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ContentInstance + """ + data = values.of( + { + "SortByDate": sort_by_date, + "SortByContentName": sort_by_content_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ContentName": content_name, + "Content": content, + "Language": serialize.map(language, lambda e: e), + "ContentType": serialize.map(content_type, lambda e: e), + "ChannelEligibility": serialize.map(channel_eligibility, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ContentPage(self._version, response) + + def get_page(self, target_url: str) -> ContentPage: + """ + Retrieve a specific page of ContentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ContentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ContentPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ContentPage: + """ + Asynchronously retrieve a specific page of ContentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ContentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ContentPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Content.V2.ContentList>" diff --git a/twilio/rest/content/v2/content_and_approvals.py b/twilio/rest/content/v2/content_and_approvals.py new file mode 100644 index 0000000000..823bcfe083 --- /dev/null +++ b/twilio/rest/content/v2/content_and_approvals.py @@ -0,0 +1,464 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ContentAndApprovalsInstance(InstanceResource): + """ + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar sid: The unique string that that we created to identify the Content resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. + :ivar friendly_name: A string name used to describe the Content resource. Not visible to the end recipient. + :ivar language: Two-letter (ISO 639-1) language code (e.g., en) identifying the language the Content resource is in. + :ivar variables: Defines the default placeholder values for variables included in the Content resource. e.g. {\"1\": \"Customer_Name\"}. + :ivar types: The [Content types](https://www.twilio.com/docs/content/content-types-overview) (e.g. twilio/text) for this Content resource. + :ivar approval_requests: The submitted information and approval request status of the Content resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.language: Optional[str] = payload.get("language") + self.variables: Optional[Dict[str, object]] = payload.get("variables") + self.types: Optional[Dict[str, object]] = payload.get("types") + self.approval_requests: Optional[Dict[str, object]] = payload.get( + "approval_requests" + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Content.V2.ContentAndApprovalsInstance>" + + +class ContentAndApprovalsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ContentAndApprovalsInstance: + """ + Build an instance of ContentAndApprovalsInstance + + :param payload: Payload response from the API + """ + return ContentAndApprovalsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Content.V2.ContentAndApprovalsPage>" + + +class ContentAndApprovalsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ContentAndApprovalsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ContentAndApprovals" + + def stream( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ContentAndApprovalsInstance]: + """ + Streams ContentAndApprovalsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=<channel>:<status> + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ContentAndApprovalsInstance]: + """ + Asynchronously streams ContentAndApprovalsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=<channel>:<status> + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ContentAndApprovalsInstance]: + """ + Lists ContentAndApprovalsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=<channel>:<status> + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ContentAndApprovalsInstance]: + """ + Asynchronously lists ContentAndApprovalsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sort_by_date: Whether to sort by ascending or descending date updated + :param str sort_by_content_name: Whether to sort by ascending or descending content name + :param datetime date_created_after: Filter by >=[date-time] + :param datetime date_created_before: Filter by <=[date-time] + :param str content_name: Filter by Regex Pattern in content name + :param str content: Filter by Regex Pattern in template content + :param List[str] language: Filter by array of valid language(s) + :param List[str] content_type: Filter by array of contentType(s) + :param List[str] channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=<channel>:<status> + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + sort_by_date=sort_by_date, + sort_by_content_name=sort_by_content_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + content_name=content_name, + content=content, + language=language, + content_type=content_type, + channel_eligibility=channel_eligibility, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ContentAndApprovalsPage: + """ + Retrieve a single page of ContentAndApprovalsInstance records from the API. + Request is executed immediately + + :param sort_by_date: Whether to sort by ascending or descending date updated + :param sort_by_content_name: Whether to sort by ascending or descending content name + :param date_created_after: Filter by >=[date-time] + :param date_created_before: Filter by <=[date-time] + :param content_name: Filter by Regex Pattern in content name + :param content: Filter by Regex Pattern in template content + :param language: Filter by array of valid language(s) + :param content_type: Filter by array of contentType(s) + :param channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=<channel>:<status> + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ContentAndApprovalsInstance + """ + data = values.of( + { + "SortByDate": sort_by_date, + "SortByContentName": sort_by_content_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ContentName": content_name, + "Content": content, + "Language": serialize.map(language, lambda e: e), + "ContentType": serialize.map(content_type, lambda e: e), + "ChannelEligibility": serialize.map(channel_eligibility, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ContentAndApprovalsPage(self._version, response) + + async def page_async( + self, + sort_by_date: Union[str, object] = values.unset, + sort_by_content_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + content_name: Union[str, object] = values.unset, + content: Union[str, object] = values.unset, + language: Union[List[str], object] = values.unset, + content_type: Union[List[str], object] = values.unset, + channel_eligibility: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ContentAndApprovalsPage: + """ + Asynchronously retrieve a single page of ContentAndApprovalsInstance records from the API. + Request is executed immediately + + :param sort_by_date: Whether to sort by ascending or descending date updated + :param sort_by_content_name: Whether to sort by ascending or descending content name + :param date_created_after: Filter by >=[date-time] + :param date_created_before: Filter by <=[date-time] + :param content_name: Filter by Regex Pattern in content name + :param content: Filter by Regex Pattern in template content + :param language: Filter by array of valid language(s) + :param content_type: Filter by array of contentType(s) + :param channel_eligibility: Filter by array of ChannelEligibility(s), where ChannelEligibility=<channel>:<status> + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ContentAndApprovalsInstance + """ + data = values.of( + { + "SortByDate": sort_by_date, + "SortByContentName": sort_by_content_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ContentName": content_name, + "Content": content, + "Language": serialize.map(language, lambda e: e), + "ContentType": serialize.map(content_type, lambda e: e), + "ChannelEligibility": serialize.map(channel_eligibility, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ContentAndApprovalsPage(self._version, response) + + def get_page(self, target_url: str) -> ContentAndApprovalsPage: + """ + Retrieve a specific page of ContentAndApprovalsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ContentAndApprovalsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ContentAndApprovalsPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ContentAndApprovalsPage: + """ + Asynchronously retrieve a specific page of ContentAndApprovalsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ContentAndApprovalsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ContentAndApprovalsPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Content.V2.ContentAndApprovalsList>" diff --git a/twilio/rest/conversations/ConversationsBase.py b/twilio/rest/conversations/ConversationsBase.py new file mode 100644 index 0000000000..8904308365 --- /dev/null +++ b/twilio/rest/conversations/ConversationsBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.conversations.v1 import V1 + + +class ConversationsBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Conversations Domain + + :returns: Domain for Conversations + """ + super().__init__(twilio, "https://conversations.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Conversations + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Conversations>" diff --git a/twilio/rest/conversations/__init__.py b/twilio/rest/conversations/__init__.py new file mode 100644 index 0000000000..d60cb426ae --- /dev/null +++ b/twilio/rest/conversations/__init__.py @@ -0,0 +1,87 @@ +from warnings import warn + +from twilio.rest.conversations.ConversationsBase import ConversationsBase +from twilio.rest.conversations.v1.address_configuration import AddressConfigurationList +from twilio.rest.conversations.v1.configuration import ConfigurationList +from twilio.rest.conversations.v1.conversation import ConversationList +from twilio.rest.conversations.v1.credential import CredentialList +from twilio.rest.conversations.v1.participant_conversation import ( + ParticipantConversationList, +) +from twilio.rest.conversations.v1.role import RoleList +from twilio.rest.conversations.v1.service import ServiceList +from twilio.rest.conversations.v1.user import UserList + + +class Conversations(ConversationsBase): + @property + def configuration(self) -> ConfigurationList: + warn( + "configuration is deprecated. Use v1.configuration instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.configuration + + @property + def address_configurations(self) -> AddressConfigurationList: + warn( + "address_configurations is deprecated. Use v1.address_configurations instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.address_configurations + + @property + def conversations(self) -> ConversationList: + warn( + "conversations is deprecated. Use v1.conversations instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.conversations + + @property + def credentials(self) -> CredentialList: + warn( + "credentials is deprecated. Use v1.credentials instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.credentials + + @property + def participant_conversations(self) -> ParticipantConversationList: + warn( + "participant_conversations is deprecated. Use v1.participant_conversations instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.participant_conversations + + @property + def roles(self) -> RoleList: + warn( + "roles is deprecated. Use v1.roles instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.roles + + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v1.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.services + + @property + def users(self) -> UserList: + warn( + "users is deprecated. Use v1.users instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.users diff --git a/twilio/rest/conversations/v1/__init__.py b/twilio/rest/conversations/v1/__init__.py new file mode 100644 index 0000000000..1ec6c22a7b --- /dev/null +++ b/twilio/rest/conversations/v1/__init__.py @@ -0,0 +1,115 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.conversations.v1.address_configuration import AddressConfigurationList +from twilio.rest.conversations.v1.configuration import ConfigurationList +from twilio.rest.conversations.v1.conversation import ConversationList +from twilio.rest.conversations.v1.conversation_with_participants import ( + ConversationWithParticipantsList, +) +from twilio.rest.conversations.v1.credential import CredentialList +from twilio.rest.conversations.v1.participant_conversation import ( + ParticipantConversationList, +) +from twilio.rest.conversations.v1.role import RoleList +from twilio.rest.conversations.v1.service import ServiceList +from twilio.rest.conversations.v1.user import UserList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Conversations + + :param domain: The Twilio.conversations domain + """ + super().__init__(domain, "v1") + self._address_configurations: Optional[AddressConfigurationList] = None + self._configuration: Optional[ConfigurationList] = None + self._conversations: Optional[ConversationList] = None + self._conversation_with_participants: Optional[ + ConversationWithParticipantsList + ] = None + self._credentials: Optional[CredentialList] = None + self._participant_conversations: Optional[ParticipantConversationList] = None + self._roles: Optional[RoleList] = None + self._services: Optional[ServiceList] = None + self._users: Optional[UserList] = None + + @property + def address_configurations(self) -> AddressConfigurationList: + if self._address_configurations is None: + self._address_configurations = AddressConfigurationList(self) + return self._address_configurations + + @property + def configuration(self) -> ConfigurationList: + if self._configuration is None: + self._configuration = ConfigurationList(self) + return self._configuration + + @property + def conversations(self) -> ConversationList: + if self._conversations is None: + self._conversations = ConversationList(self) + return self._conversations + + @property + def conversation_with_participants(self) -> ConversationWithParticipantsList: + if self._conversation_with_participants is None: + self._conversation_with_participants = ConversationWithParticipantsList( + self + ) + return self._conversation_with_participants + + @property + def credentials(self) -> CredentialList: + if self._credentials is None: + self._credentials = CredentialList(self) + return self._credentials + + @property + def participant_conversations(self) -> ParticipantConversationList: + if self._participant_conversations is None: + self._participant_conversations = ParticipantConversationList(self) + return self._participant_conversations + + @property + def roles(self) -> RoleList: + if self._roles is None: + self._roles = RoleList(self) + return self._roles + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + @property + def users(self) -> UserList: + if self._users is None: + self._users = UserList(self) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1>" diff --git a/twilio/rest/conversations/v1/address_configuration.py b/twilio/rest/conversations/v1/address_configuration.py new file mode 100644 index 0000000000..c12e3c7170 --- /dev/null +++ b/twilio/rest/conversations/v1/address_configuration.py @@ -0,0 +1,859 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AddressConfigurationInstance(InstanceResource): + + class AutoCreationType(object): + WEBHOOK = "webhook" + STUDIO = "studio" + DEFAULT = "default" + + class Method(object): + GET = "GET" + POST = "POST" + + class Type(object): + SMS = "sms" + WHATSAPP = "whatsapp" + MESSENGER = "messenger" + GBM = "gbm" + EMAIL = "email" + RCS = "rcs" + APPLE = "apple" + CHAT = "chat" + + """ + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) the address belongs to + :ivar type: Type of Address, value can be `whatsapp` or `sms`. + :ivar address: The unique address to be configured. The address can be a whatsapp address or phone number + :ivar friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :ivar auto_creation: Auto Creation configuration for the address. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar url: An absolute API resource URL for this address configuration. + :ivar address_country: An ISO 3166-1 alpha-2n country code which the address belongs to. This is currently only applicable to short code addresses. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.type: Optional[str] = payload.get("type") + self.address: Optional[str] = payload.get("address") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.auto_creation: Optional[Dict[str, object]] = payload.get("auto_creation") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.address_country: Optional[str] = payload.get("address_country") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AddressConfigurationContext] = None + + @property + def _proxy(self) -> "AddressConfigurationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AddressConfigurationContext for this AddressConfigurationInstance + """ + if self._context is None: + self._context = AddressConfigurationContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AddressConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AddressConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AddressConfigurationInstance": + """ + Fetch the AddressConfigurationInstance + + + :returns: The fetched AddressConfigurationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AddressConfigurationInstance": + """ + Asynchronous coroutine to fetch the AddressConfigurationInstance + + + :returns: The fetched AddressConfigurationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + ) -> "AddressConfigurationInstance": + """ + Update the AddressConfigurationInstance + + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + + :returns: The updated AddressConfigurationInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + ) -> "AddressConfigurationInstance": + """ + Asynchronous coroutine to update the AddressConfigurationInstance + + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + + :returns: The updated AddressConfigurationInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + auto_creation_enabled=auto_creation_enabled, + auto_creation_type=auto_creation_type, + auto_creation_conversation_service_sid=auto_creation_conversation_service_sid, + auto_creation_webhook_url=auto_creation_webhook_url, + auto_creation_webhook_method=auto_creation_webhook_method, + auto_creation_webhook_filters=auto_creation_webhook_filters, + auto_creation_studio_flow_sid=auto_creation_studio_flow_sid, + auto_creation_studio_retry_count=auto_creation_studio_retry_count, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.AddressConfigurationInstance {}>".format( + context + ) + + +class AddressConfigurationContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the AddressConfigurationContext + + :param version: Version that contains the resource + :param sid: The SID of the Address Configuration resource. This value can be either the `sid` or the `address` of the configuration + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Configuration/Addresses/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the AddressConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AddressConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AddressConfigurationInstance: + """ + Fetch the AddressConfigurationInstance + + + :returns: The fetched AddressConfigurationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AddressConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AddressConfigurationInstance: + """ + Asynchronous coroutine to fetch the AddressConfigurationInstance + + + :returns: The fetched AddressConfigurationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AddressConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + ) -> AddressConfigurationInstance: + """ + Update the AddressConfigurationInstance + + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + + :returns: The updated AddressConfigurationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "AutoCreation.Enabled": serialize.boolean_to_string( + auto_creation_enabled + ), + "AutoCreation.Type": auto_creation_type, + "AutoCreation.ConversationServiceSid": auto_creation_conversation_service_sid, + "AutoCreation.WebhookUrl": auto_creation_webhook_url, + "AutoCreation.WebhookMethod": auto_creation_webhook_method, + "AutoCreation.WebhookFilters": serialize.map( + auto_creation_webhook_filters, lambda e: e + ), + "AutoCreation.StudioFlowSid": auto_creation_studio_flow_sid, + "AutoCreation.StudioRetryCount": auto_creation_studio_retry_count, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AddressConfigurationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + ) -> AddressConfigurationInstance: + """ + Asynchronous coroutine to update the AddressConfigurationInstance + + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + + :returns: The updated AddressConfigurationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "AutoCreation.Enabled": serialize.boolean_to_string( + auto_creation_enabled + ), + "AutoCreation.Type": auto_creation_type, + "AutoCreation.ConversationServiceSid": auto_creation_conversation_service_sid, + "AutoCreation.WebhookUrl": auto_creation_webhook_url, + "AutoCreation.WebhookMethod": auto_creation_webhook_method, + "AutoCreation.WebhookFilters": serialize.map( + auto_creation_webhook_filters, lambda e: e + ), + "AutoCreation.StudioFlowSid": auto_creation_studio_flow_sid, + "AutoCreation.StudioRetryCount": auto_creation_studio_retry_count, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AddressConfigurationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.AddressConfigurationContext {}>".format( + context + ) + + +class AddressConfigurationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AddressConfigurationInstance: + """ + Build an instance of AddressConfigurationInstance + + :param payload: Payload response from the API + """ + return AddressConfigurationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.AddressConfigurationPage>" + + +class AddressConfigurationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AddressConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Configuration/Addresses" + + def create( + self, + type: "AddressConfigurationInstance.Type", + address: str, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + address_country: Union[str, object] = values.unset, + ) -> AddressConfigurationInstance: + """ + Create the AddressConfigurationInstance + + :param type: + :param address: The unique address to be configured. The address can be a whatsapp address or phone number + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + :param address_country: An ISO 3166-1 alpha-2n country code which the address belongs to. This is currently only applicable to short code addresses. + + :returns: The created AddressConfigurationInstance + """ + + data = values.of( + { + "Type": type, + "Address": address, + "FriendlyName": friendly_name, + "AutoCreation.Enabled": serialize.boolean_to_string( + auto_creation_enabled + ), + "AutoCreation.Type": auto_creation_type, + "AutoCreation.ConversationServiceSid": auto_creation_conversation_service_sid, + "AutoCreation.WebhookUrl": auto_creation_webhook_url, + "AutoCreation.WebhookMethod": auto_creation_webhook_method, + "AutoCreation.WebhookFilters": serialize.map( + auto_creation_webhook_filters, lambda e: e + ), + "AutoCreation.StudioFlowSid": auto_creation_studio_flow_sid, + "AutoCreation.StudioRetryCount": auto_creation_studio_retry_count, + "AddressCountry": address_country, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AddressConfigurationInstance(self._version, payload) + + async def create_async( + self, + type: "AddressConfigurationInstance.Type", + address: str, + friendly_name: Union[str, object] = values.unset, + auto_creation_enabled: Union[bool, object] = values.unset, + auto_creation_type: Union[ + "AddressConfigurationInstance.AutoCreationType", object + ] = values.unset, + auto_creation_conversation_service_sid: Union[str, object] = values.unset, + auto_creation_webhook_url: Union[str, object] = values.unset, + auto_creation_webhook_method: Union[ + "AddressConfigurationInstance.Method", object + ] = values.unset, + auto_creation_webhook_filters: Union[List[str], object] = values.unset, + auto_creation_studio_flow_sid: Union[str, object] = values.unset, + auto_creation_studio_retry_count: Union[int, object] = values.unset, + address_country: Union[str, object] = values.unset, + ) -> AddressConfigurationInstance: + """ + Asynchronously create the AddressConfigurationInstance + + :param type: + :param address: The unique address to be configured. The address can be a whatsapp address or phone number + :param friendly_name: The human-readable name of this configuration, limited to 256 characters. Optional. + :param auto_creation_enabled: Enable/Disable auto-creating conversations for messages to this address + :param auto_creation_type: + :param auto_creation_conversation_service_sid: Conversation Service for the auto-created conversation. If not set, the conversation is created in the default service. + :param auto_creation_webhook_url: For type `webhook`, the url for the webhook request. + :param auto_creation_webhook_method: + :param auto_creation_webhook_filters: The list of events, firing webhook event for this Conversation. Values can be any of the following: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationStateUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onDeliveryUpdated` + :param auto_creation_studio_flow_sid: For type `studio`, the studio flow SID where the webhook should be sent to. + :param auto_creation_studio_retry_count: For type `studio`, number of times to retry the webhook request + :param address_country: An ISO 3166-1 alpha-2n country code which the address belongs to. This is currently only applicable to short code addresses. + + :returns: The created AddressConfigurationInstance + """ + + data = values.of( + { + "Type": type, + "Address": address, + "FriendlyName": friendly_name, + "AutoCreation.Enabled": serialize.boolean_to_string( + auto_creation_enabled + ), + "AutoCreation.Type": auto_creation_type, + "AutoCreation.ConversationServiceSid": auto_creation_conversation_service_sid, + "AutoCreation.WebhookUrl": auto_creation_webhook_url, + "AutoCreation.WebhookMethod": auto_creation_webhook_method, + "AutoCreation.WebhookFilters": serialize.map( + auto_creation_webhook_filters, lambda e: e + ), + "AutoCreation.StudioFlowSid": auto_creation_studio_flow_sid, + "AutoCreation.StudioRetryCount": auto_creation_studio_retry_count, + "AddressCountry": address_country, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AddressConfigurationInstance(self._version, payload) + + def stream( + self, + type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AddressConfigurationInstance]: + """ + Streams AddressConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str type: Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(type=type, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AddressConfigurationInstance]: + """ + Asynchronously streams AddressConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str type: Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(type=type, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AddressConfigurationInstance]: + """ + Lists AddressConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str type: Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + type=type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AddressConfigurationInstance]: + """ + Asynchronously lists AddressConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str type: Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + type=type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AddressConfigurationPage: + """ + Retrieve a single page of AddressConfigurationInstance records from the API. + Request is executed immediately + + :param type: Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AddressConfigurationInstance + """ + data = values.of( + { + "Type": type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AddressConfigurationPage(self._version, response) + + async def page_async( + self, + type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AddressConfigurationPage: + """ + Asynchronously retrieve a single page of AddressConfigurationInstance records from the API. + Request is executed immediately + + :param type: Filter the address configurations by its type. This value can be one of: `whatsapp`, `sms`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AddressConfigurationInstance + """ + data = values.of( + { + "Type": type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AddressConfigurationPage(self._version, response) + + def get_page(self, target_url: str) -> AddressConfigurationPage: + """ + Retrieve a specific page of AddressConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AddressConfigurationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AddressConfigurationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AddressConfigurationPage: + """ + Asynchronously retrieve a specific page of AddressConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AddressConfigurationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AddressConfigurationPage(self._version, response) + + def get(self, sid: str) -> AddressConfigurationContext: + """ + Constructs a AddressConfigurationContext + + :param sid: The SID of the Address Configuration resource. This value can be either the `sid` or the `address` of the configuration + """ + return AddressConfigurationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AddressConfigurationContext: + """ + Constructs a AddressConfigurationContext + + :param sid: The SID of the Address Configuration resource. This value can be either the `sid` or the `address` of the configuration + """ + return AddressConfigurationContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.AddressConfigurationList>" diff --git a/twilio/rest/conversations/v1/configuration/__init__.py b/twilio/rest/conversations/v1/configuration/__init__.py new file mode 100644 index 0000000000..584082353f --- /dev/null +++ b/twilio/rest/conversations/v1/configuration/__init__.py @@ -0,0 +1,325 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.conversations.v1.configuration.webhook import WebhookList + + +class ConfigurationInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this configuration. + :ivar default_chat_service_sid: The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) used when creating a conversation. + :ivar default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) used when creating a conversation. + :ivar default_inactive_timer: Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :ivar default_closed_timer: Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :ivar url: An absolute API resource URL for this global configuration. + :ivar links: Contains absolute API resource URLs to access the webhook and default service configurations. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.default_chat_service_sid: Optional[str] = payload.get( + "default_chat_service_sid" + ) + self.default_messaging_service_sid: Optional[str] = payload.get( + "default_messaging_service_sid" + ) + self.default_inactive_timer: Optional[str] = payload.get( + "default_inactive_timer" + ) + self.default_closed_timer: Optional[str] = payload.get("default_closed_timer") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._context: Optional[ConfigurationContext] = None + + @property + def _proxy(self) -> "ConfigurationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConfigurationContext for this ConfigurationInstance + """ + if self._context is None: + self._context = ConfigurationContext( + self._version, + ) + return self._context + + def fetch(self) -> "ConfigurationInstance": + """ + Fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConfigurationInstance": + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + default_chat_service_sid: Union[str, object] = values.unset, + default_messaging_service_sid: Union[str, object] = values.unset, + default_inactive_timer: Union[str, object] = values.unset, + default_closed_timer: Union[str, object] = values.unset, + ) -> "ConfigurationInstance": + """ + Update the ConfigurationInstance + + :param default_chat_service_sid: The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to use when creating a conversation. + :param default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to use when creating a conversation. + :param default_inactive_timer: Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param default_closed_timer: Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + + :returns: The updated ConfigurationInstance + """ + return self._proxy.update( + default_chat_service_sid=default_chat_service_sid, + default_messaging_service_sid=default_messaging_service_sid, + default_inactive_timer=default_inactive_timer, + default_closed_timer=default_closed_timer, + ) + + async def update_async( + self, + default_chat_service_sid: Union[str, object] = values.unset, + default_messaging_service_sid: Union[str, object] = values.unset, + default_inactive_timer: Union[str, object] = values.unset, + default_closed_timer: Union[str, object] = values.unset, + ) -> "ConfigurationInstance": + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param default_chat_service_sid: The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to use when creating a conversation. + :param default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to use when creating a conversation. + :param default_inactive_timer: Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param default_closed_timer: Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + + :returns: The updated ConfigurationInstance + """ + return await self._proxy.update_async( + default_chat_service_sid=default_chat_service_sid, + default_messaging_service_sid=default_messaging_service_sid, + default_inactive_timer=default_inactive_timer, + default_closed_timer=default_closed_timer, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Conversations.V1.ConfigurationInstance>" + + +class ConfigurationContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the ConfigurationContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/Configuration" + + def fetch(self) -> ConfigurationInstance: + """ + Fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ConfigurationInstance( + self._version, + payload, + ) + + async def fetch_async(self) -> ConfigurationInstance: + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ConfigurationInstance( + self._version, + payload, + ) + + def update( + self, + default_chat_service_sid: Union[str, object] = values.unset, + default_messaging_service_sid: Union[str, object] = values.unset, + default_inactive_timer: Union[str, object] = values.unset, + default_closed_timer: Union[str, object] = values.unset, + ) -> ConfigurationInstance: + """ + Update the ConfigurationInstance + + :param default_chat_service_sid: The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to use when creating a conversation. + :param default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to use when creating a conversation. + :param default_inactive_timer: Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param default_closed_timer: Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + + :returns: The updated ConfigurationInstance + """ + + data = values.of( + { + "DefaultChatServiceSid": default_chat_service_sid, + "DefaultMessagingServiceSid": default_messaging_service_sid, + "DefaultInactiveTimer": default_inactive_timer, + "DefaultClosedTimer": default_closed_timer, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConfigurationInstance(self._version, payload) + + async def update_async( + self, + default_chat_service_sid: Union[str, object] = values.unset, + default_messaging_service_sid: Union[str, object] = values.unset, + default_inactive_timer: Union[str, object] = values.unset, + default_closed_timer: Union[str, object] = values.unset, + ) -> ConfigurationInstance: + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param default_chat_service_sid: The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to use when creating a conversation. + :param default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to use when creating a conversation. + :param default_inactive_timer: Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param default_closed_timer: Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + + :returns: The updated ConfigurationInstance + """ + + data = values.of( + { + "DefaultChatServiceSid": default_chat_service_sid, + "DefaultMessagingServiceSid": default_messaging_service_sid, + "DefaultInactiveTimer": default_inactive_timer, + "DefaultClosedTimer": default_closed_timer, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConfigurationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Conversations.V1.ConfigurationContext>" + + +class ConfigurationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._webhooks: Optional[WebhookList] = None + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + if self._webhooks is None: + self._webhooks = WebhookList(self._version) + return self._webhooks + + def get(self) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + """ + return ConfigurationContext(self._version) + + def __call__(self) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + """ + return ConfigurationContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.ConfigurationList>" diff --git a/twilio/rest/conversations/v1/configuration/webhook.py b/twilio/rest/conversations/v1/configuration/webhook.py new file mode 100644 index 0000000000..f471c879ab --- /dev/null +++ b/twilio/rest/conversations/v1/configuration/webhook.py @@ -0,0 +1,327 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WebhookInstance(InstanceResource): + + class Method(object): + GET = "GET" + POST = "POST" + + class Target(object): + WEBHOOK = "webhook" + FLEX = "flex" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar method: + :ivar filters: The list of webhook event triggers that are enabled for this Service: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onMessageAdd`, `onMessageUpdate`, `onMessageRemove`, `onConversationUpdated`, `onConversationRemoved`, `onConversationAdd`, `onConversationAdded`, `onConversationRemove`, `onConversationUpdate`, `onConversationStateUpdated`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onParticipantAdd`, `onParticipantRemove`, `onParticipantUpdate`, `onDeliveryUpdated`, `onUserAdded`, `onUserUpdate`, `onUserUpdated` + :ivar pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :ivar post_webhook_url: The absolute url the post-event webhook request should be sent to. + :ivar target: + :ivar url: An absolute API resource API resource URL for this webhook. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.method: Optional["WebhookInstance.Method"] = payload.get("method") + self.filters: Optional[List[str]] = payload.get("filters") + self.pre_webhook_url: Optional[str] = payload.get("pre_webhook_url") + self.post_webhook_url: Optional[str] = payload.get("post_webhook_url") + self.target: Optional["WebhookInstance.Target"] = payload.get("target") + self.url: Optional[str] = payload.get("url") + + self._context: Optional[WebhookContext] = None + + @property + def _proxy(self) -> "WebhookContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WebhookContext for this WebhookInstance + """ + if self._context is None: + self._context = WebhookContext( + self._version, + ) + return self._context + + def fetch(self) -> "WebhookInstance": + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WebhookInstance": + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + method: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + target: Union["WebhookInstance.Target", object] = values.unset, + ) -> "WebhookInstance": + """ + Update the WebhookInstance + + :param method: The HTTP method to be used when sending a webhook request. + :param filters: The list of webhook event triggers that are enabled for this Service: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onMessageAdd`, `onMessageUpdate`, `onMessageRemove`, `onConversationUpdated`, `onConversationRemoved`, `onConversationAdd`, `onConversationAdded`, `onConversationRemove`, `onConversationUpdate`, `onConversationStateUpdated`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onParticipantAdd`, `onParticipantRemove`, `onParticipantUpdate`, `onDeliveryUpdated`, `onUserAdded`, `onUserUpdate`, `onUserUpdated` + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param target: + + :returns: The updated WebhookInstance + """ + return self._proxy.update( + method=method, + filters=filters, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + target=target, + ) + + async def update_async( + self, + method: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + target: Union["WebhookInstance.Target", object] = values.unset, + ) -> "WebhookInstance": + """ + Asynchronous coroutine to update the WebhookInstance + + :param method: The HTTP method to be used when sending a webhook request. + :param filters: The list of webhook event triggers that are enabled for this Service: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onMessageAdd`, `onMessageUpdate`, `onMessageRemove`, `onConversationUpdated`, `onConversationRemoved`, `onConversationAdd`, `onConversationAdded`, `onConversationRemove`, `onConversationUpdate`, `onConversationStateUpdated`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onParticipantAdd`, `onParticipantRemove`, `onParticipantUpdate`, `onDeliveryUpdated`, `onUserAdded`, `onUserUpdate`, `onUserUpdated` + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param target: + + :returns: The updated WebhookInstance + """ + return await self._proxy.update_async( + method=method, + filters=filters, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + target=target, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Conversations.V1.WebhookInstance>" + + +class WebhookContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the WebhookContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/Configuration/Webhooks" + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WebhookInstance( + self._version, + payload, + ) + + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + ) + + def update( + self, + method: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + target: Union["WebhookInstance.Target", object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param method: The HTTP method to be used when sending a webhook request. + :param filters: The list of webhook event triggers that are enabled for this Service: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onMessageAdd`, `onMessageUpdate`, `onMessageRemove`, `onConversationUpdated`, `onConversationRemoved`, `onConversationAdd`, `onConversationAdded`, `onConversationRemove`, `onConversationUpdate`, `onConversationStateUpdated`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onParticipantAdd`, `onParticipantRemove`, `onParticipantUpdate`, `onDeliveryUpdated`, `onUserAdded`, `onUserUpdate`, `onUserUpdated` + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param target: + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "Method": method, + "Filters": serialize.map(filters, lambda e: e), + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "Target": target, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance(self._version, payload) + + async def update_async( + self, + method: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + target: Union["WebhookInstance.Target", object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param method: The HTTP method to be used when sending a webhook request. + :param filters: The list of webhook event triggers that are enabled for this Service: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onMessageAdd`, `onMessageUpdate`, `onMessageRemove`, `onConversationUpdated`, `onConversationRemoved`, `onConversationAdd`, `onConversationAdded`, `onConversationRemove`, `onConversationUpdate`, `onConversationStateUpdated`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved`, `onParticipantAdd`, `onParticipantRemove`, `onParticipantUpdate`, `onDeliveryUpdated`, `onUserAdded`, `onUserUpdate`, `onUserUpdated` + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param target: + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "Method": method, + "Filters": serialize.map(filters, lambda e: e), + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "Target": target, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Conversations.V1.WebhookContext>" + + +class WebhookList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the WebhookList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> WebhookContext: + """ + Constructs a WebhookContext + + """ + return WebhookContext(self._version) + + def __call__(self) -> WebhookContext: + """ + Constructs a WebhookContext + + """ + return WebhookContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.WebhookList>" diff --git a/twilio/rest/conversations/v1/conversation/__init__.py b/twilio/rest/conversations/v1/conversation/__init__.py new file mode 100644 index 0000000000..d1f08cc2d8 --- /dev/null +++ b/twilio/rest/conversations/v1/conversation/__init__.py @@ -0,0 +1,1025 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.conversations.v1.conversation.message import MessageList +from twilio.rest.conversations.v1.conversation.participant import ParticipantList +from twilio.rest.conversations.v1.conversation.webhook import WebhookList + + +class ConversationInstance(InstanceResource): + + class State(object): + INACTIVE = "inactive" + ACTIVE = "active" + CLOSED = "closed" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + :ivar messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :ivar attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar state: + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar timers: Timer date values representing state update for this conversation. + :ivar url: An absolute API resource URL for this conversation. + :ivar links: Contains absolute URLs to access the [participants](https://www.twilio.com/docs/conversations/api/conversation-participant-resource), [messages](https://www.twilio.com/docs/conversations/api/conversation-message-resource) and [webhooks](https://www.twilio.com/docs/conversations/api/conversation-scoped-webhook-resource) of this conversation. + :ivar bindings: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.state: Optional["ConversationInstance.State"] = payload.get("state") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.timers: Optional[Dict[str, object]] = payload.get("timers") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.bindings: Optional[Dict[str, object]] = payload.get("bindings") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ConversationContext] = None + + @property + def _proxy(self) -> "ConversationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConversationContext for this ConversationInstance + """ + if self._context is None: + self._context = ConversationContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "ConversationInstance": + """ + Fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConversationInstance": + """ + Asynchronous coroutine to fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> "ConversationInstance": + """ + Update the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The updated ConversationInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> "ConversationInstance": + """ + Asynchronous coroutine to update the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The updated ConversationInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + return self._proxy.participants + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + return self._proxy.webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.ConversationInstance {}>".format(context) + + +class ConversationContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ConversationContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this resource. Can also be the `unique_name` of the Conversation. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Conversations/{sid}".format(**self._solution) + + self._messages: Optional[MessageList] = None + self._participants: Optional[ParticipantList] = None + self._webhooks: Optional[WebhookList] = None + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConversationInstance: + """ + Fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ConversationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ConversationInstance: + """ + Asynchronous coroutine to fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ConversationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Update the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The updated ConversationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MessagingServiceSid": messaging_service_sid, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "UniqueName": unique_name, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Asynchronous coroutine to update the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The updated ConversationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MessagingServiceSid": messaging_service_sid, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "UniqueName": unique_name, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["sid"], + ) + return self._messages + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + if self._participants is None: + self._participants = ParticipantList( + self._version, + self._solution["sid"], + ) + return self._participants + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + if self._webhooks is None: + self._webhooks = WebhookList( + self._version, + self._solution["sid"], + ) + return self._webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.ConversationContext {}>".format(context) + + +class ConversationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConversationInstance: + """ + Build an instance of ConversationInstance + + :param payload: Payload response from the API + """ + return ConversationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.ConversationPage>" + + +class ConversationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ConversationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Conversations" + + def create( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Create the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The created ConversationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "MessagingServiceSid": messaging_service_sid, + "Attributes": attributes, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationInstance(self._version, payload) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Asynchronously create the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The created ConversationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "MessagingServiceSid": messaging_service_sid, + "Attributes": attributes, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationInstance(self._version, payload) + + def stream( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConversationInstance]: + """ + Streams ConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + start_date=start_date, + end_date=end_date, + state=state, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConversationInstance]: + """ + Asynchronously streams ConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + start_date=start_date, + end_date=end_date, + state=state, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConversationInstance]: + """ + Lists ConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + start_date=start_date, + end_date=end_date, + state=state, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConversationInstance]: + """ + Asynchronously lists ConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + start_date=start_date, + end_date=end_date, + state=state, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConversationPage: + """ + Retrieve a single page of ConversationInstance records from the API. + Request is executed immediately + + :param start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConversationInstance + """ + data = values.of( + { + "StartDate": start_date, + "EndDate": end_date, + "State": state, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConversationPage(self._version, response) + + async def page_async( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConversationPage: + """ + Asynchronously retrieve a single page of ConversationInstance records from the API. + Request is executed immediately + + :param start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConversationInstance + """ + data = values.of( + { + "StartDate": start_date, + "EndDate": end_date, + "State": state, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConversationPage(self._version, response) + + def get_page(self, target_url: str) -> ConversationPage: + """ + Retrieve a specific page of ConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConversationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ConversationPage: + """ + Asynchronously retrieve a specific page of ConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConversationPage(self._version, response) + + def get(self, sid: str) -> ConversationContext: + """ + Constructs a ConversationContext + + :param sid: A 34 character string that uniquely identifies this resource. Can also be the `unique_name` of the Conversation. + """ + return ConversationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ConversationContext: + """ + Constructs a ConversationContext + + :param sid: A 34 character string that uniquely identifies this resource. Can also be the `unique_name` of the Conversation. + """ + return ConversationContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.ConversationList>" diff --git a/twilio/rest/conversations/v1/conversation/message/__init__.py b/twilio/rest/conversations/v1/conversation/message/__init__.py new file mode 100644 index 0000000000..04e7fdf252 --- /dev/null +++ b/twilio/rest/conversations/v1/conversation/message/__init__.py @@ -0,0 +1,912 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.conversations.v1.conversation.message.delivery_receipt import ( + DeliveryReceiptList, +) + + +class MessageInstance(InstanceResource): + + class OrderType(object): + ASC = "asc" + DESC = "desc" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this message. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar index: The index of the message within the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource). Indices may skip numbers, but will always be in order of when the message was received. + :ivar author: The channel specific identifier of the message's author. Defaults to `system`. + :ivar body: The content of the message, can be up to 1,600 characters long. + :ivar media: An array of objects that describe the Message's media, if the message contains media. Each object contains these fields: `content_type` with the MIME type of the media, `filename` with the name of the media, `sid` with the SID of the Media resource, and `size` with the media object's file size in bytes. If the Message has no media, this value is `null`. + :ivar attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar participant_sid: The unique ID of messages's author participant. Null in case of `system` sent message. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :ivar url: An absolute API resource API URL for this message. + :ivar delivery: An object that contains the summary of delivery statuses for the message to non-chat participants. + :ivar links: Contains an absolute API resource URL to access the delivery & read receipts of this message. + :ivar content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conversation_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.sid: Optional[str] = payload.get("sid") + self.index: Optional[int] = deserialize.integer(payload.get("index")) + self.author: Optional[str] = payload.get("author") + self.body: Optional[str] = payload.get("body") + self.media: Optional[List[Dict[str, object]]] = payload.get("media") + self.attributes: Optional[str] = payload.get("attributes") + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.delivery: Optional[Dict[str, object]] = payload.get("delivery") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.content_sid: Optional[str] = payload.get("content_sid") + + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid or self.sid, + } + self._context: Optional[MessageContext] = None + + @property + def _proxy(self) -> "MessageContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The updated MessageInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Asynchronous coroutine to update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The updated MessageInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, + ) + + @property + def delivery_receipts(self) -> DeliveryReceiptList: + """ + Access the delivery_receipts + """ + return self._proxy.delivery_receipts + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.MessageInstance {}>".format(context) + + +class MessageContext(InstanceContext): + + def __init__(self, version: Version, conversation_sid: str, sid: str): + """ + Initialize the MessageContext + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid, + } + self._uri = "/Conversations/{conversation_sid}/Messages/{sid}".format( + **self._solution + ) + + self._delivery_receipts: Optional[DeliveryReceiptList] = None + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Author": author, + "Body": body, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "Subject": subject, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Author": author, + "Body": body, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "Subject": subject, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + @property + def delivery_receipts(self) -> DeliveryReceiptList: + """ + Access the delivery_receipts + """ + if self._delivery_receipts is None: + self._delivery_receipts = DeliveryReceiptList( + self._version, + self._solution["conversation_sid"], + self._solution["sid"], + ) + return self._delivery_receipts + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.MessageContext {}>".format(context) + + +class MessagePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance + + :param payload: Payload response from the API + """ + return MessageInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.MessagePage>" + + +class MessageList(ListResource): + + def __init__(self, version: Version, conversation_sid: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for messages. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + } + self._uri = "/Conversations/{conversation_sid}/Messages".format( + **self._solution + ) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + content_sid: Union[str, object] = values.unset, + content_variables: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param media_sid: The Media SID to be attached to the new Message. + :param content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. + :param content_variables: A structurally valid JSON string that contains values to resolve Rich Content template variables. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The created MessageInstance + """ + + data = values.of( + { + "Author": author, + "Body": body, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MediaSid": media_sid, + "ContentSid": content_sid, + "ContentVariables": content_variables, + "Subject": subject, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + content_sid: Union[str, object] = values.unset, + content_variables: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param media_sid: The Media SID to be attached to the new Message. + :param content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. + :param content_variables: A structurally valid JSON string that contains values to resolve Rich Content template variables. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The created MessageInstance + """ + + data = values.of( + { + "Author": author, + "Body": body, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MediaSid": media_sid, + "ContentSid": content_sid, + "ContentVariables": content_variables, + "Subject": subject, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: + """ + Streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(order=order, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInstance]: + """ + Asynchronously streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(order=order, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + order=order, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Asynchronously lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + order=order, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + async def page_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MessagePage: + """ + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MessagePage: + """ + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) + + def get(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return MessageContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return MessageContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.MessageList>" diff --git a/twilio/rest/conversations/v1/conversation/message/delivery_receipt.py b/twilio/rest/conversations/v1/conversation/message/delivery_receipt.py new file mode 100644 index 0000000000..2ed297e059 --- /dev/null +++ b/twilio/rest/conversations/v1/conversation/message/delivery_receipt.py @@ -0,0 +1,482 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DeliveryReceiptInstance(InstanceResource): + + class DeliveryStatus(object): + READ = "read" + FAILED = "failed" + DELIVERED = "delivered" + UNDELIVERED = "undelivered" + SENT = "sent" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this participant. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar message_sid: The SID of the message within a [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) the delivery receipt belongs to + :ivar channel_message_sid: A messaging channel-specific identifier for the message delivered to participant e.g. `SMxx` for SMS, `WAxx` for Whatsapp etc. + :ivar participant_sid: The unique ID of the participant the delivery receipt belongs to. + :ivar status: + :ivar error_code: The message [delivery error code](https://www.twilio.com/docs/sms/api/message-resource#delivery-related-errors) for a `failed` status, + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. `null` if the delivery receipt has not been updated. + :ivar url: An absolute API resource URL for this delivery receipt. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conversation_sid: str, + message_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.sid: Optional[str] = payload.get("sid") + self.message_sid: Optional[str] = payload.get("message_sid") + self.channel_message_sid: Optional[str] = payload.get("channel_message_sid") + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.status: Optional["DeliveryReceiptInstance.DeliveryStatus"] = payload.get( + "status" + ) + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "conversation_sid": conversation_sid, + "message_sid": message_sid, + "sid": sid or self.sid, + } + self._context: Optional[DeliveryReceiptContext] = None + + @property + def _proxy(self) -> "DeliveryReceiptContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DeliveryReceiptContext for this DeliveryReceiptInstance + """ + if self._context is None: + self._context = DeliveryReceiptContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "DeliveryReceiptInstance": + """ + Fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DeliveryReceiptInstance": + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.DeliveryReceiptInstance {}>".format(context) + + +class DeliveryReceiptContext(InstanceContext): + + def __init__( + self, version: Version, conversation_sid: str, message_sid: str, sid: str + ): + """ + Initialize the DeliveryReceiptContext + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :param message_sid: The SID of the message within a [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) the delivery receipt belongs to. + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + "message_sid": message_sid, + "sid": sid, + } + self._uri = "/Conversations/{conversation_sid}/Messages/{message_sid}/Receipts/{sid}".format( + **self._solution + ) + + def fetch(self) -> DeliveryReceiptInstance: + """ + Fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DeliveryReceiptInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> DeliveryReceiptInstance: + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DeliveryReceiptInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.DeliveryReceiptContext {}>".format(context) + + +class DeliveryReceiptPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DeliveryReceiptInstance: + """ + Build an instance of DeliveryReceiptInstance + + :param payload: Payload response from the API + """ + return DeliveryReceiptInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.DeliveryReceiptPage>" + + +class DeliveryReceiptList(ListResource): + + def __init__(self, version: Version, conversation_sid: str, message_sid: str): + """ + Initialize the DeliveryReceiptList + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :param message_sid: The SID of the message within a [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) the delivery receipt belongs to. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + "message_sid": message_sid, + } + self._uri = ( + "/Conversations/{conversation_sid}/Messages/{message_sid}/Receipts".format( + **self._solution + ) + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DeliveryReceiptInstance]: + """ + Streams DeliveryReceiptInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DeliveryReceiptInstance]: + """ + Asynchronously streams DeliveryReceiptInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeliveryReceiptInstance]: + """ + Lists DeliveryReceiptInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeliveryReceiptInstance]: + """ + Asynchronously lists DeliveryReceiptInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DeliveryReceiptPage: + """ + Retrieve a single page of DeliveryReceiptInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DeliveryReceiptInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DeliveryReceiptPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DeliveryReceiptPage: + """ + Asynchronously retrieve a single page of DeliveryReceiptInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DeliveryReceiptInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DeliveryReceiptPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DeliveryReceiptPage: + """ + Retrieve a specific page of DeliveryReceiptInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DeliveryReceiptInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DeliveryReceiptPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DeliveryReceiptPage: + """ + Asynchronously retrieve a specific page of DeliveryReceiptInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DeliveryReceiptInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DeliveryReceiptPage(self._version, response, self._solution) + + def get(self, sid: str) -> DeliveryReceiptContext: + """ + Constructs a DeliveryReceiptContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return DeliveryReceiptContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> DeliveryReceiptContext: + """ + Constructs a DeliveryReceiptContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return DeliveryReceiptContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.DeliveryReceiptList>" diff --git a/twilio/rest/conversations/v1/conversation/participant.py b/twilio/rest/conversations/v1/conversation/participant.py new file mode 100644 index 0000000000..deb652641a --- /dev/null +++ b/twilio/rest/conversations/v1/conversation/participant.py @@ -0,0 +1,895 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ParticipantInstance(InstanceResource): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this participant. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this participant. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :ivar attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar messaging_binding: Information about how this participant exchanges messages with the conversation. A JSON parameter consisting of type and address fields of the participant. + :ivar role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar url: An absolute API resource URL for this participant. + :ivar last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :ivar last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conversation_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.sid: Optional[str] = payload.get("sid") + self.identity: Optional[str] = payload.get("identity") + self.attributes: Optional[str] = payload.get("attributes") + self.messaging_binding: Optional[Dict[str, object]] = payload.get( + "messaging_binding" + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.last_read_message_index: Optional[int] = deserialize.integer( + payload.get("last_read_message_index") + ) + self.last_read_timestamp: Optional[str] = payload.get("last_read_timestamp") + + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid or self.sid, + } + self._context: Optional[ParticipantContext] = None + + @property + def _proxy(self) -> "ParticipantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ParticipantContext for this ParticipantInstance + """ + if self._context is None: + self._context = ParticipantContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "ParticipantInstance": + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ParticipantInstance": + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> "ParticipantInstance": + """ + Update the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: The updated ParticipantInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + identity=identity, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> "ParticipantInstance": + """ + Asynchronous coroutine to update the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: The updated ParticipantInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + identity=identity, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.ParticipantInstance {}>".format(context) + + +class ParticipantContext(InstanceContext): + + def __init__(self, version: Version, conversation_sid: str, sid: str): + """ + Initialize the ParticipantContext + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this participant. + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid, + } + self._uri = "/Conversations/{conversation_sid}/Participants/{sid}".format( + **self._solution + ) + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Update the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: The updated ParticipantInstance + """ + + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "RoleSid": role_sid, + "MessagingBinding.ProxyAddress": messaging_binding_proxy_address, + "MessagingBinding.ProjectedAddress": messaging_binding_projected_address, + "Identity": identity, + "LastReadMessageIndex": last_read_message_index, + "LastReadTimestamp": last_read_timestamp, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + identity: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronous coroutine to update the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: The updated ParticipantInstance + """ + + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "RoleSid": role_sid, + "MessagingBinding.ProxyAddress": messaging_binding_proxy_address, + "MessagingBinding.ProjectedAddress": messaging_binding_projected_address, + "Identity": identity, + "LastReadMessageIndex": last_read_message_index, + "LastReadTimestamp": last_read_timestamp, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.ParticipantContext {}>".format(context) + + +class ParticipantPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: + """ + Build an instance of ParticipantInstance + + :param payload: Payload response from the API + """ + return ParticipantInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.ParticipantPage>" + + +class ParticipantList(ListResource): + + def __init__(self, version: Version, conversation_sid: str): + """ + Initialize the ParticipantList + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for participants. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + } + self._uri = "/Conversations/{conversation_sid}/Participants".format( + **self._solution + ) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + identity: Union[str, object] = values.unset, + messaging_binding_address: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Create the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param messaging_binding_address: The address of the participant's device, e.g. a phone or WhatsApp number. Together with the Proxy address, this determines a participant uniquely. This field (with proxy_address) is only null when the participant is interacting from an SDK endpoint (see the 'identity' field). + :param messaging_binding_proxy_address: The address of the Twilio phone number (or WhatsApp number) that the participant is in contact with. This field, together with participant address, is only null when the participant is interacting from an SDK endpoint (see the 'identity' field). + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. Communication mask for the Conversation participant with Identity. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + + :returns: The created ParticipantInstance + """ + + data = values.of( + { + "Identity": identity, + "MessagingBinding.Address": messaging_binding_address, + "MessagingBinding.ProxyAddress": messaging_binding_proxy_address, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MessagingBinding.ProjectedAddress": messaging_binding_projected_address, + "RoleSid": role_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + identity: Union[str, object] = values.unset, + messaging_binding_address: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronously create the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param messaging_binding_address: The address of the participant's device, e.g. a phone or WhatsApp number. Together with the Proxy address, this determines a participant uniquely. This field (with proxy_address) is only null when the participant is interacting from an SDK endpoint (see the 'identity' field). + :param messaging_binding_proxy_address: The address of the Twilio phone number (or WhatsApp number) that the participant is in contact with. This field, together with participant address, is only null when the participant is interacting from an SDK endpoint (see the 'identity' field). + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. Communication mask for the Conversation participant with Identity. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + + :returns: The created ParticipantInstance + """ + + data = values.of( + { + "Identity": identity, + "MessagingBinding.Address": messaging_binding_address, + "MessagingBinding.ProxyAddress": messaging_binding_proxy_address, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MessagingBinding.ProjectedAddress": messaging_binding_projected_address, + "RoleSid": role_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantInstance]: + """ + Streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ParticipantInstance]: + """ + Asynchronously streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Asynchronously lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Asynchronously retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ParticipantPage: + """ + Retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ParticipantPage: + """ + Asynchronously retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + def get(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return ParticipantContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return ParticipantContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.ParticipantList>" diff --git a/twilio/rest/conversations/v1/conversation/webhook.py b/twilio/rest/conversations/v1/conversation/webhook.py new file mode 100644 index 0000000000..837f88c26f --- /dev/null +++ b/twilio/rest/conversations/v1/conversation/webhook.py @@ -0,0 +1,758 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class WebhookInstance(InstanceResource): + + class Method(object): + GET = "GET" + POST = "POST" + + class Target(object): + WEBHOOK = "webhook" + TRIGGER = "trigger" + STUDIO = "studio" + + """ + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this webhook. + :ivar target: The target of this webhook: `webhook`, `studio`, `trigger` + :ivar url: An absolute API resource URL for this webhook. + :ivar configuration: The configuration of this webhook. Is defined based on target. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conversation_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.target: Optional[str] = payload.get("target") + self.url: Optional[str] = payload.get("url") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid or self.sid, + } + self._context: Optional[WebhookContext] = None + + @property + def _proxy(self) -> "WebhookContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WebhookContext for this WebhookInstance + """ + if self._context is None: + self._context = WebhookContext( + self._version, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "WebhookInstance": + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WebhookInstance": + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> "WebhookInstance": + """ + Update the WebhookInstance + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: The updated WebhookInstance + """ + return self._proxy.update( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> "WebhookInstance": + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: The updated WebhookInstance + """ + return await self._proxy.update_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.WebhookInstance {}>".format(context) + + +class WebhookContext(InstanceContext): + + def __init__(self, version: Version, conversation_sid: str, sid: str): + """ + Initialize the WebhookContext + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this webhook. + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid, + } + self._uri = "/Conversations/{conversation_sid}/Webhooks/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.WebhookContext {}>".format(context) + + +class WebhookPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: + """ + Build an instance of WebhookInstance + + :param payload: Payload response from the API + """ + return WebhookInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.WebhookPage>" + + +class WebhookList(ListResource): + + def __init__(self, version: Version, conversation_sid: str): + """ + Initialize the WebhookList + + :param version: Version that contains the resource + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this webhook. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + } + self._uri = "/Conversations/{conversation_sid}/Webhooks".format( + **self._solution + ) + + def create( + self, + target: "WebhookInstance.Target", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_replay_after: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Create the WebhookInstance + + :param target: + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + :param configuration_replay_after: The message index for which and it's successors the webhook will be replayed. Not set by default + + :returns: The created WebhookInstance + """ + + data = values.of( + { + "Target": target, + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.ReplayAfter": configuration_replay_after, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + async def create_async( + self, + target: "WebhookInstance.Target", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_replay_after: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronously create the WebhookInstance + + :param target: + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + :param configuration_replay_after: The message index for which and it's successors the webhook will be replayed. Not set by default + + :returns: The created WebhookInstance + """ + + data = values.of( + { + "Target": target, + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.ReplayAfter": configuration_replay_after, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, payload, conversation_sid=self._solution["conversation_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WebhookInstance]: + """ + Streams WebhookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WebhookInstance]: + """ + Asynchronously streams WebhookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: + """ + Lists WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: + """ + Asynchronously lists WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebhookPage: + """ + Retrieve a single page of WebhookInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebhookInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebhookPage: + """ + Asynchronously retrieve a single page of WebhookInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebhookInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> WebhookPage: + """ + Retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WebhookPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> WebhookPage: + """ + Asynchronously retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WebhookPage(self._version, response, self._solution) + + def get(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return WebhookContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __call__(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return WebhookContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.WebhookList>" diff --git a/twilio/rest/conversations/v1/conversation_with_participants.py b/twilio/rest/conversations/v1/conversation_with_participants.py new file mode 100644 index 0000000000..a818a29ca4 --- /dev/null +++ b/twilio/rest/conversations/v1/conversation_with_participants.py @@ -0,0 +1,251 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ConversationWithParticipantsInstance(InstanceResource): + + class State(object): + INACTIVE = "inactive" + ACTIVE = "active" + CLOSED = "closed" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + :ivar messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :ivar attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar state: + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar timers: Timer date values representing state update for this conversation. + :ivar links: Contains absolute URLs to access the [participants](https://www.twilio.com/docs/conversations/api/conversation-participant-resource), [messages](https://www.twilio.com/docs/conversations/api/conversation-message-resource) and [webhooks](https://www.twilio.com/docs/conversations/api/conversation-scoped-webhook-resource) of this conversation. + :ivar bindings: + :ivar url: An absolute API resource URL for this conversation. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.state: Optional["ConversationWithParticipantsInstance.State"] = ( + payload.get("state") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.timers: Optional[Dict[str, object]] = payload.get("timers") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.bindings: Optional[Dict[str, object]] = payload.get("bindings") + self.url: Optional[str] = payload.get("url") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Conversations.V1.ConversationWithParticipantsInstance>" + + +class ConversationWithParticipantsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ConversationWithParticipantsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ConversationWithParticipants" + + def create( + self, + x_twilio_webhook_enabled: Union[ + "ConversationWithParticipantsInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union[ + "ConversationWithParticipantsInstance.State", object + ] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + participant: Union[List[str], object] = values.unset, + ) -> ConversationWithParticipantsInstance: + """ + Create the ConversationWithParticipantsInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + :param participant: The participant to be added to the conversation in JSON format. The JSON object attributes are as parameters in [Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). The maximum number of participants that can be added in a single request is 10. + + :returns: The created ConversationWithParticipantsInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "MessagingServiceSid": messaging_service_sid, + "Attributes": attributes, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + "Participant": serialize.map(participant, lambda e: e), + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationWithParticipantsInstance(self._version, payload) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationWithParticipantsInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union[ + "ConversationWithParticipantsInstance.State", object + ] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + participant: Union[List[str], object] = values.unset, + ) -> ConversationWithParticipantsInstance: + """ + Asynchronously create the ConversationWithParticipantsInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + :param participant: The participant to be added to the conversation in JSON format. The JSON object attributes are as parameters in [Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). The maximum number of participants that can be added in a single request is 10. + + :returns: The created ConversationWithParticipantsInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "MessagingServiceSid": messaging_service_sid, + "Attributes": attributes, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + "Participant": serialize.map(participant, lambda e: e), + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationWithParticipantsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.ConversationWithParticipantsList>" diff --git a/twilio/rest/conversations/v1/credential.py b/twilio/rest/conversations/v1/credential.py new file mode 100644 index 0000000000..f382458ba7 --- /dev/null +++ b/twilio/rest/conversations/v1/credential.py @@ -0,0 +1,723 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CredentialInstance(InstanceResource): + + class PushType(object): + APN = "apn" + GCM = "gcm" + FCM = "fcm" + + """ + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this credential. + :ivar friendly_name: The human-readable name of this credential, limited to 64 characters. Optional. + :ivar type: + :ivar sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar url: An absolute API resource URL for this credential. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushType"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None + + @property + def _proxy(self) -> "CredentialContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CredentialInstance": + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialInstance": + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + type: Union["CredentialInstance.PushType", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Update the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + return self._proxy.update( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_async( + self, + type: Union["CredentialInstance.PushType", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Asynchronous coroutine to update the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + return await self._proxy.update_async( + type=type, + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.CredentialInstance {}>".format(context) + + +class CredentialContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CredentialContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + type: Union["CredentialInstance.PushType", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Update the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + type: Union["CredentialInstance.PushType", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.CredentialContext {}>".format(context) + + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance + + :param payload: Payload response from the API + """ + return CredentialInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.CredentialPage>" + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Credentials" + + def create( + self, + type: "CredentialInstance.PushType", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + async def create_async( + self, + type: "CredentialInstance.PushType", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL encoded representation of the certificate. For example, `-----BEGIN CERTIFICATE----- MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEF.....A== -----END CERTIFICATE-----`. + :param private_key: [APN only] The URL encoded representation of the private key. For example, `-----BEGIN RSA PRIVATE KEY----- MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fG... -----END RSA PRIVATE KEY-----`. + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The API key for the project that was obtained from the Google Developer console for your GCM Service application credential. + :param secret: [FCM only] The **Server key** of your project from the Firebase console, found under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialInstance]: + """ + Streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: + """ + Asynchronously streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Asynchronously lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Asynchronously retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + def get_page(self, target_url: str) -> CredentialPage: + """ + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CredentialPage: + """ + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) + + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return CredentialContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return CredentialContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.CredentialList>" diff --git a/twilio/rest/conversations/v1/participant_conversation.py b/twilio/rest/conversations/v1/participant_conversation.py new file mode 100644 index 0000000000..0938bd5421 --- /dev/null +++ b/twilio/rest/conversations/v1/participant_conversation.py @@ -0,0 +1,366 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ParticipantConversationInstance(InstanceResource): + + class State(object): + INACTIVE = "inactive" + ACTIVE = "active" + CLOSED = "closed" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + :ivar participant_sid: The unique ID of the [Participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). + :ivar participant_user_sid: The unique string that identifies the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). + :ivar participant_identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :ivar participant_messaging_binding: Information about how this participant exchanges messages with the conversation. A JSON parameter consisting of type and address fields of the participant. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) this Participant belongs to. + :ivar conversation_unique_name: An application-defined string that uniquely identifies the Conversation resource. + :ivar conversation_friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :ivar conversation_attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar conversation_date_created: The date that this conversation was created, given in ISO 8601 format. + :ivar conversation_date_updated: The date that this conversation was last updated, given in ISO 8601 format. + :ivar conversation_created_by: Identity of the creator of this Conversation. + :ivar conversation_state: + :ivar conversation_timers: Timer date values representing state update for this conversation. + :ivar links: Contains absolute URLs to access the [participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) and [conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) of this conversation. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.participant_user_sid: Optional[str] = payload.get("participant_user_sid") + self.participant_identity: Optional[str] = payload.get("participant_identity") + self.participant_messaging_binding: Optional[Dict[str, object]] = payload.get( + "participant_messaging_binding" + ) + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.conversation_unique_name: Optional[str] = payload.get( + "conversation_unique_name" + ) + self.conversation_friendly_name: Optional[str] = payload.get( + "conversation_friendly_name" + ) + self.conversation_attributes: Optional[str] = payload.get( + "conversation_attributes" + ) + self.conversation_date_created: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("conversation_date_created")) + ) + self.conversation_date_updated: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("conversation_date_updated")) + ) + self.conversation_created_by: Optional[str] = payload.get( + "conversation_created_by" + ) + self.conversation_state: Optional["ParticipantConversationInstance.State"] = ( + payload.get("conversation_state") + ) + self.conversation_timers: Optional[Dict[str, object]] = payload.get( + "conversation_timers" + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Conversations.V1.ParticipantConversationInstance>" + + +class ParticipantConversationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantConversationInstance: + """ + Build an instance of ParticipantConversationInstance + + :param payload: Payload response from the API + """ + return ParticipantConversationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.ParticipantConversationPage>" + + +class ParticipantConversationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ParticipantConversationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ParticipantConversations" + + def stream( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantConversationInstance]: + """ + Streams ParticipantConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + identity=identity, address=address, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ParticipantConversationInstance]: + """ + Asynchronously streams ParticipantConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + identity=identity, address=address, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantConversationInstance]: + """ + Lists ParticipantConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + address=address, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantConversationInstance]: + """ + Asynchronously lists ParticipantConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + address=address, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantConversationPage: + """ + Retrieve a single page of ParticipantConversationInstance records from the API. + Request is executed immediately + + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantConversationInstance + """ + data = values.of( + { + "Identity": identity, + "Address": address, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantConversationPage(self._version, response) + + async def page_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantConversationPage: + """ + Asynchronously retrieve a single page of ParticipantConversationInstance records from the API. + Request is executed immediately + + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantConversationInstance + """ + data = values.of( + { + "Identity": identity, + "Address": address, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantConversationPage(self._version, response) + + def get_page(self, target_url: str) -> ParticipantConversationPage: + """ + Retrieve a specific page of ParticipantConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantConversationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantConversationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ParticipantConversationPage: + """ + Asynchronously retrieve a specific page of ParticipantConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantConversationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantConversationPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.ParticipantConversationList>" diff --git a/twilio/rest/conversations/v1/role.py b/twilio/rest/conversations/v1/role.py new file mode 100644 index 0000000000..229e9b7dd4 --- /dev/null +++ b/twilio/rest/conversations/v1/role.py @@ -0,0 +1,610 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RoleInstance(InstanceResource): + + class RoleType(object): + CONVERSATION = "conversation" + SERVICE = "service" + + """ + :ivar sid: The unique string that we created to identify the Role resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Role resource. + :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Role resource is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar permissions: An array of the permissions the role has been granted. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: An absolute API resource URL for this user role. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["RoleInstance.RoleType"] = payload.get("type") + self.permissions: Optional[List[str]] = payload.get("permissions") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[RoleContext] = None + + @property + def _proxy(self) -> "RoleContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoleContext for this RoleInstance + """ + if self._context is None: + self._context = RoleContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RoleInstance": + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RoleInstance": + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return await self._proxy.fetch_async() + + def update(self, permission: List[str]) -> "RoleInstance": + """ + Update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + return self._proxy.update( + permission=permission, + ) + + async def update_async(self, permission: List[str]) -> "RoleInstance": + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + return await self._proxy.update_async( + permission=permission, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.RoleInstance {}>".format(context) + + +class RoleContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the RoleContext + + :param version: Version that contains the resource + :param sid: The SID of the Role resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Roles/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RoleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RoleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update(self, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.RoleContext {}>".format(context) + + +class RolePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: + """ + Build an instance of RoleInstance + + :param payload: Payload response from the API + """ + return RoleInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.RolePage>" + + +class RoleList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RoleList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Roles" + + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance(self._version, payload) + + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoleInstance]: + """ + Streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoleInstance]: + """ + Asynchronously streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Asynchronously lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Asynchronously retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response) + + def get_page(self, target_url: str) -> RolePage: + """ + Retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RolePage(self._version, response) + + async def get_page_async(self, target_url: str) -> RolePage: + """ + Asynchronously retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RolePage(self._version, response) + + def get(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: The SID of the Role resource to update. + """ + return RoleContext(self._version, sid=sid) + + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: The SID of the Role resource to update. + """ + return RoleContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.RoleList>" diff --git a/twilio/rest/conversations/v1/service/__init__.py b/twilio/rest/conversations/v1/service/__init__.py new file mode 100644 index 0000000000..3b92c87934 --- /dev/null +++ b/twilio/rest/conversations/v1/service/__init__.py @@ -0,0 +1,667 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.conversations.v1.service.binding import BindingList +from twilio.rest.conversations.v1.service.configuration import ConfigurationList +from twilio.rest.conversations.v1.service.conversation import ConversationList +from twilio.rest.conversations.v1.service.conversation_with_participants import ( + ConversationWithParticipantsList, +) +from twilio.rest.conversations.v1.service.participant_conversation import ( + ParticipantConversationList, +) +from twilio.rest.conversations.v1.service.role import RoleList +from twilio.rest.conversations.v1.service.user import UserList + + +class ServiceInstance(InstanceResource): + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this service. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar friendly_name: The human-readable name of this service, limited to 256 characters. Optional. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar url: An absolute API resource URL for this service. + :ivar links: Contains absolute API resource URLs to access conversations, users, roles, bindings and configuration of this service. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + return self._proxy.bindings + + @property + def configuration(self) -> ConfigurationList: + """ + Access the configuration + """ + return self._proxy.configuration + + @property + def conversations(self) -> ConversationList: + """ + Access the conversations + """ + return self._proxy.conversations + + @property + def conversation_with_participants(self) -> ConversationWithParticipantsList: + """ + Access the conversation_with_participants + """ + return self._proxy.conversation_with_participants + + @property + def participant_conversations(self) -> ParticipantConversationList: + """ + Access the participant_conversations + """ + return self._proxy.participant_conversations + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + return self._proxy.users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.ServiceInstance {}>".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._bindings: Optional[BindingList] = None + self._configuration: Optional[ConfigurationList] = None + self._conversations: Optional[ConversationList] = None + self._conversation_with_participants: Optional[ + ConversationWithParticipantsList + ] = None + self._participant_conversations: Optional[ParticipantConversationList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + if self._bindings is None: + self._bindings = BindingList( + self._version, + self._solution["sid"], + ) + return self._bindings + + @property + def configuration(self) -> ConfigurationList: + """ + Access the configuration + """ + if self._configuration is None: + self._configuration = ConfigurationList( + self._version, + self._solution["sid"], + ) + return self._configuration + + @property + def conversations(self) -> ConversationList: + """ + Access the conversations + """ + if self._conversations is None: + self._conversations = ConversationList( + self._version, + self._solution["sid"], + ) + return self._conversations + + @property + def conversation_with_participants(self) -> ConversationWithParticipantsList: + """ + Access the conversation_with_participants + """ + if self._conversation_with_participants is None: + self._conversation_with_participants = ConversationWithParticipantsList( + self._version, + self._solution["sid"], + ) + return self._conversation_with_participants + + @property + def participant_conversations(self) -> ParticipantConversationList: + """ + Access the participant_conversations + """ + if self._participant_conversations is None: + self._participant_conversations = ParticipantConversationList( + self._version, + self._solution["sid"], + ) + return self._participant_conversations + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + if self._roles is None: + self._roles = RoleList( + self._version, + self._solution["sid"], + ) + return self._roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + if self._users is None: + self._users = UserList( + self._version, + self._solution["sid"], + ) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.ServiceContext {}>".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.ServicePage>" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create(self, friendly_name: str) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: The human-readable name of this service, limited to 256 characters. Optional. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async(self, friendly_name: str) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: The human-readable name of this service, limited to 256 characters. Optional. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.ServiceList>" diff --git a/twilio/rest/conversations/v1/service/binding.py b/twilio/rest/conversations/v1/service/binding.py new file mode 100644 index 0000000000..363dab91d0 --- /dev/null +++ b/twilio/rest/conversations/v1/service/binding.py @@ -0,0 +1,536 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class BindingInstance(InstanceResource): + + class BindingType(object): + APN = "apn" + GCM = "gcm" + FCM = "fcm" + + """ + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this binding. + :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Binding resource is associated with. + :ivar credential_sid: The SID of the [Credential](https://www.twilio.com/docs/conversations/api/credential-resource) for the binding. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar endpoint: The unique endpoint identifier for the Binding. The format of this value depends on the `binding_type`. + :ivar identity: The application-defined string that uniquely identifies the [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more info. + :ivar binding_type: + :ivar message_types: The [Conversation message types](https://www.twilio.com/docs/chat/push-notification-configuration#push-types) the binding is subscribed to. + :ivar url: An absolute API resource URL for this binding. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + chat_service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.credential_sid: Optional[str] = payload.get("credential_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.endpoint: Optional[str] = payload.get("endpoint") + self.identity: Optional[str] = payload.get("identity") + self.binding_type: Optional["BindingInstance.BindingType"] = payload.get( + "binding_type" + ) + self.message_types: Optional[List[str]] = payload.get("message_types") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "chat_service_sid": chat_service_sid, + "sid": sid or self.sid, + } + self._context: Optional[BindingContext] = None + + @property + def _proxy(self) -> "BindingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BindingContext for this BindingInstance + """ + if self._context is None: + self._context = BindingContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "BindingInstance": + """ + Fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BindingInstance": + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.BindingInstance {}>".format(context) + + +class BindingContext(InstanceContext): + + def __init__(self, version: Version, chat_service_sid: str, sid: str): + """ + Initialize the BindingContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Binding resource is associated with. + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "sid": sid, + } + self._uri = "/Services/{chat_service_sid}/Bindings/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> BindingInstance: + """ + Fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return BindingInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> BindingInstance: + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return BindingInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.BindingContext {}>".format(context) + + +class BindingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: + """ + Build an instance of BindingInstance + + :param payload: Payload response from the API + """ + return BindingInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.BindingPage>" + + +class BindingList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the BindingList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Binding resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._uri = "/Services/{chat_service_sid}/Bindings".format(**self._solution) + + def stream( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BindingInstance]: + """ + Streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BindingInstance]: + """ + Asynchronously streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BindingInstance]: + """ + Lists BindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BindingInstance]: + """ + Asynchronously lists BindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["BindingInstance.BindingType"] binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param List[str] identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BindingPage: + """ + Retrieve a single page of BindingInstance records from the API. + Request is executed immediately + + :param binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BindingInstance + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BindingPage(self._version, response, self._solution) + + async def page_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BindingPage: + """ + Asynchronously retrieve a single page of BindingInstance records from the API. + Request is executed immediately + + :param binding_type: The push technology used by the Binding resources to read. Can be: `apn`, `gcm`, or `fcm`. See [push notification configuration](https://www.twilio.com/docs/chat/push-notification-configuration) for more info. + :param identity: The identity of a [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource) this binding belongs to. See [access tokens](https://www.twilio.com/docs/conversations/create-tokens) for more details. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BindingInstance + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BindingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> BindingPage: + """ + Retrieve a specific page of BindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BindingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BindingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> BindingPage: + """ + Asynchronously retrieve a specific page of BindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BindingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BindingPage(self._version, response, self._solution) + + def get(self, sid: str) -> BindingContext: + """ + Constructs a BindingContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return BindingContext( + self._version, chat_service_sid=self._solution["chat_service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> BindingContext: + """ + Constructs a BindingContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return BindingContext( + self._version, chat_service_sid=self._solution["chat_service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.BindingList>" diff --git a/twilio/rest/conversations/v1/service/configuration/__init__.py b/twilio/rest/conversations/v1/service/configuration/__init__.py new file mode 100644 index 0000000000..e37c8888c8 --- /dev/null +++ b/twilio/rest/conversations/v1/service/configuration/__init__.py @@ -0,0 +1,375 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.conversations.v1.service.configuration.notification import ( + NotificationList, +) +from twilio.rest.conversations.v1.service.configuration.webhook import WebhookList + + +class ConfigurationInstance(InstanceResource): + """ + :ivar chat_service_sid: The unique string that we created to identify the Service configuration resource. + :ivar default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :ivar default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :ivar default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :ivar url: An absolute API resource URL for this service configuration. + :ivar links: Contains an absolute API resource URL to access the push notifications configuration of this service. + :ivar reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], chat_service_sid: str + ): + super().__init__(version) + + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.default_conversation_creator_role_sid: Optional[str] = payload.get( + "default_conversation_creator_role_sid" + ) + self.default_conversation_role_sid: Optional[str] = payload.get( + "default_conversation_role_sid" + ) + self.default_chat_service_role_sid: Optional[str] = payload.get( + "default_chat_service_role_sid" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.reachability_enabled: Optional[bool] = payload.get("reachability_enabled") + + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._context: Optional[ConfigurationContext] = None + + @property + def _proxy(self) -> "ConfigurationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConfigurationContext for this ConfigurationInstance + """ + if self._context is None: + self._context = ConfigurationContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + ) + return self._context + + def fetch(self) -> "ConfigurationInstance": + """ + Fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConfigurationInstance": + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + default_conversation_creator_role_sid: Union[str, object] = values.unset, + default_conversation_role_sid: Union[str, object] = values.unset, + default_chat_service_role_sid: Union[str, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + ) -> "ConfigurationInstance": + """ + Update the ConfigurationInstance + + :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + + :returns: The updated ConfigurationInstance + """ + return self._proxy.update( + default_conversation_creator_role_sid=default_conversation_creator_role_sid, + default_conversation_role_sid=default_conversation_role_sid, + default_chat_service_role_sid=default_chat_service_role_sid, + reachability_enabled=reachability_enabled, + ) + + async def update_async( + self, + default_conversation_creator_role_sid: Union[str, object] = values.unset, + default_conversation_role_sid: Union[str, object] = values.unset, + default_chat_service_role_sid: Union[str, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + ) -> "ConfigurationInstance": + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + + :returns: The updated ConfigurationInstance + """ + return await self._proxy.update_async( + default_conversation_creator_role_sid=default_conversation_creator_role_sid, + default_conversation_role_sid=default_conversation_role_sid, + default_chat_service_role_sid=default_chat_service_role_sid, + reachability_enabled=reachability_enabled, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.ConfigurationInstance {}>".format(context) + + +class ConfigurationContext(InstanceContext): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the ConfigurationContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the Service configuration resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._uri = "/Services/{chat_service_sid}/Configuration".format( + **self._solution + ) + + def fetch(self) -> ConfigurationInstance: + """ + Fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ConfigurationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + + async def fetch_async(self) -> ConfigurationInstance: + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ConfigurationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + + def update( + self, + default_conversation_creator_role_sid: Union[str, object] = values.unset, + default_conversation_role_sid: Union[str, object] = values.unset, + default_chat_service_role_sid: Union[str, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + ) -> ConfigurationInstance: + """ + Update the ConfigurationInstance + + :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + + :returns: The updated ConfigurationInstance + """ + + data = values.of( + { + "DefaultConversationCreatorRoleSid": default_conversation_creator_role_sid, + "DefaultConversationRoleSid": default_conversation_role_sid, + "DefaultChatServiceRoleSid": default_chat_service_role_sid, + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConfigurationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def update_async( + self, + default_conversation_creator_role_sid: Union[str, object] = values.unset, + default_conversation_role_sid: Union[str, object] = values.unset, + default_chat_service_role_sid: Union[str, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + ) -> ConfigurationInstance: + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator when they join a new conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :param reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. + + :returns: The updated ConfigurationInstance + """ + + data = values.of( + { + "DefaultConversationCreatorRoleSid": default_conversation_creator_role_sid, + "DefaultConversationRoleSid": default_conversation_role_sid, + "DefaultChatServiceRoleSid": default_chat_service_role_sid, + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConfigurationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.ConfigurationContext {}>".format(context) + + +class ConfigurationList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the ConfigurationList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the Service configuration resource to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + + self._notifications: Optional[NotificationList] = None + self._webhooks: Optional[WebhookList] = None + + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + if self._notifications is None: + self._notifications = NotificationList( + self._version, chat_service_sid=self._solution["chat_service_sid"] + ) + return self._notifications + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + if self._webhooks is None: + self._webhooks = WebhookList( + self._version, chat_service_sid=self._solution["chat_service_sid"] + ) + return self._webhooks + + def get(self) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + """ + return ConfigurationContext( + self._version, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __call__(self) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + """ + return ConfigurationContext( + self._version, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.ConfigurationList>" diff --git a/twilio/rest/conversations/v1/service/configuration/notification.py b/twilio/rest/conversations/v1/service/configuration/notification.py new file mode 100644 index 0000000000..6aced28115 --- /dev/null +++ b/twilio/rest/conversations/v1/service/configuration/notification.py @@ -0,0 +1,463 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NotificationInstance(InstanceResource): + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this configuration. + :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Configuration applies to. + :ivar new_message: The Push Notification configuration for New Messages. + :ivar added_to_conversation: The Push Notification configuration for being added to a Conversation. + :ivar removed_from_conversation: The Push Notification configuration for being removed from a Conversation. + :ivar log_enabled: Weather the notification logging is enabled. + :ivar url: An absolute API resource URL for this configuration. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], chat_service_sid: str + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.new_message: Optional[Dict[str, object]] = payload.get("new_message") + self.added_to_conversation: Optional[Dict[str, object]] = payload.get( + "added_to_conversation" + ) + self.removed_from_conversation: Optional[Dict[str, object]] = payload.get( + "removed_from_conversation" + ) + self.log_enabled: Optional[bool] = payload.get("log_enabled") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._context: Optional[NotificationContext] = None + + @property + def _proxy(self) -> "NotificationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NotificationContext for this NotificationInstance + """ + if self._context is None: + self._context = NotificationContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + ) + return self._context + + def fetch(self) -> "NotificationInstance": + """ + Fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "NotificationInstance": + """ + Asynchronous coroutine to fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + log_enabled: Union[bool, object] = values.unset, + new_message_enabled: Union[bool, object] = values.unset, + new_message_template: Union[str, object] = values.unset, + new_message_sound: Union[str, object] = values.unset, + new_message_badge_count_enabled: Union[bool, object] = values.unset, + added_to_conversation_enabled: Union[bool, object] = values.unset, + added_to_conversation_template: Union[str, object] = values.unset, + added_to_conversation_sound: Union[str, object] = values.unset, + removed_from_conversation_enabled: Union[bool, object] = values.unset, + removed_from_conversation_template: Union[str, object] = values.unset, + removed_from_conversation_sound: Union[str, object] = values.unset, + new_message_with_media_enabled: Union[bool, object] = values.unset, + new_message_with_media_template: Union[str, object] = values.unset, + ) -> "NotificationInstance": + """ + Update the NotificationInstance + + :param log_enabled: Weather the notification logging is enabled. + :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. + :param new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_sound: The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation. The default is `false`. + :param added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation. The default is `false`. + :param removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. + :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. + + :returns: The updated NotificationInstance + """ + return self._proxy.update( + log_enabled=log_enabled, + new_message_enabled=new_message_enabled, + new_message_template=new_message_template, + new_message_sound=new_message_sound, + new_message_badge_count_enabled=new_message_badge_count_enabled, + added_to_conversation_enabled=added_to_conversation_enabled, + added_to_conversation_template=added_to_conversation_template, + added_to_conversation_sound=added_to_conversation_sound, + removed_from_conversation_enabled=removed_from_conversation_enabled, + removed_from_conversation_template=removed_from_conversation_template, + removed_from_conversation_sound=removed_from_conversation_sound, + new_message_with_media_enabled=new_message_with_media_enabled, + new_message_with_media_template=new_message_with_media_template, + ) + + async def update_async( + self, + log_enabled: Union[bool, object] = values.unset, + new_message_enabled: Union[bool, object] = values.unset, + new_message_template: Union[str, object] = values.unset, + new_message_sound: Union[str, object] = values.unset, + new_message_badge_count_enabled: Union[bool, object] = values.unset, + added_to_conversation_enabled: Union[bool, object] = values.unset, + added_to_conversation_template: Union[str, object] = values.unset, + added_to_conversation_sound: Union[str, object] = values.unset, + removed_from_conversation_enabled: Union[bool, object] = values.unset, + removed_from_conversation_template: Union[str, object] = values.unset, + removed_from_conversation_sound: Union[str, object] = values.unset, + new_message_with_media_enabled: Union[bool, object] = values.unset, + new_message_with_media_template: Union[str, object] = values.unset, + ) -> "NotificationInstance": + """ + Asynchronous coroutine to update the NotificationInstance + + :param log_enabled: Weather the notification logging is enabled. + :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. + :param new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_sound: The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation. The default is `false`. + :param added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation. The default is `false`. + :param removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. + :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. + + :returns: The updated NotificationInstance + """ + return await self._proxy.update_async( + log_enabled=log_enabled, + new_message_enabled=new_message_enabled, + new_message_template=new_message_template, + new_message_sound=new_message_sound, + new_message_badge_count_enabled=new_message_badge_count_enabled, + added_to_conversation_enabled=added_to_conversation_enabled, + added_to_conversation_template=added_to_conversation_template, + added_to_conversation_sound=added_to_conversation_sound, + removed_from_conversation_enabled=removed_from_conversation_enabled, + removed_from_conversation_template=removed_from_conversation_template, + removed_from_conversation_sound=removed_from_conversation_sound, + new_message_with_media_enabled=new_message_with_media_enabled, + new_message_with_media_template=new_message_with_media_template, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.NotificationInstance {}>".format(context) + + +class NotificationContext(InstanceContext): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the NotificationContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Configuration applies to. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._uri = "/Services/{chat_service_sid}/Configuration/Notifications".format( + **self._solution + ) + + def fetch(self) -> NotificationInstance: + """ + Fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return NotificationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + + async def fetch_async(self) -> NotificationInstance: + """ + Asynchronous coroutine to fetch the NotificationInstance + + + :returns: The fetched NotificationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return NotificationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + + def update( + self, + log_enabled: Union[bool, object] = values.unset, + new_message_enabled: Union[bool, object] = values.unset, + new_message_template: Union[str, object] = values.unset, + new_message_sound: Union[str, object] = values.unset, + new_message_badge_count_enabled: Union[bool, object] = values.unset, + added_to_conversation_enabled: Union[bool, object] = values.unset, + added_to_conversation_template: Union[str, object] = values.unset, + added_to_conversation_sound: Union[str, object] = values.unset, + removed_from_conversation_enabled: Union[bool, object] = values.unset, + removed_from_conversation_template: Union[str, object] = values.unset, + removed_from_conversation_sound: Union[str, object] = values.unset, + new_message_with_media_enabled: Union[bool, object] = values.unset, + new_message_with_media_template: Union[str, object] = values.unset, + ) -> NotificationInstance: + """ + Update the NotificationInstance + + :param log_enabled: Weather the notification logging is enabled. + :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. + :param new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_sound: The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation. The default is `false`. + :param added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation. The default is `false`. + :param removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. + :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. + + :returns: The updated NotificationInstance + """ + + data = values.of( + { + "LogEnabled": serialize.boolean_to_string(log_enabled), + "NewMessage.Enabled": serialize.boolean_to_string(new_message_enabled), + "NewMessage.Template": new_message_template, + "NewMessage.Sound": new_message_sound, + "NewMessage.BadgeCountEnabled": serialize.boolean_to_string( + new_message_badge_count_enabled + ), + "AddedToConversation.Enabled": serialize.boolean_to_string( + added_to_conversation_enabled + ), + "AddedToConversation.Template": added_to_conversation_template, + "AddedToConversation.Sound": added_to_conversation_sound, + "RemovedFromConversation.Enabled": serialize.boolean_to_string( + removed_from_conversation_enabled + ), + "RemovedFromConversation.Template": removed_from_conversation_template, + "RemovedFromConversation.Sound": removed_from_conversation_sound, + "NewMessage.WithMedia.Enabled": serialize.boolean_to_string( + new_message_with_media_enabled + ), + "NewMessage.WithMedia.Template": new_message_with_media_template, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NotificationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def update_async( + self, + log_enabled: Union[bool, object] = values.unset, + new_message_enabled: Union[bool, object] = values.unset, + new_message_template: Union[str, object] = values.unset, + new_message_sound: Union[str, object] = values.unset, + new_message_badge_count_enabled: Union[bool, object] = values.unset, + added_to_conversation_enabled: Union[bool, object] = values.unset, + added_to_conversation_template: Union[str, object] = values.unset, + added_to_conversation_sound: Union[str, object] = values.unset, + removed_from_conversation_enabled: Union[bool, object] = values.unset, + removed_from_conversation_template: Union[str, object] = values.unset, + removed_from_conversation_sound: Union[str, object] = values.unset, + new_message_with_media_enabled: Union[bool, object] = values.unset, + new_message_with_media_template: Union[str, object] = values.unset, + ) -> NotificationInstance: + """ + Asynchronous coroutine to update the NotificationInstance + + :param log_enabled: Weather the notification logging is enabled. + :param new_message_enabled: Whether to send a notification when a new message is added to a conversation. The default is `false`. + :param new_message_template: The template to use to create the notification text displayed when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_sound: The name of the sound to play when a new message is added to a conversation and `new_message.enabled` is `true`. + :param new_message_badge_count_enabled: Whether the new message badge is enabled. The default is `false`. + :param added_to_conversation_enabled: Whether to send a notification when a participant is added to a conversation. The default is `false`. + :param added_to_conversation_template: The template to use to create the notification text displayed when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param added_to_conversation_sound: The name of the sound to play when a participant is added to a conversation and `added_to_conversation.enabled` is `true`. + :param removed_from_conversation_enabled: Whether to send a notification to a user when they are removed from a conversation. The default is `false`. + :param removed_from_conversation_template: The template to use to create the notification text displayed to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param removed_from_conversation_sound: The name of the sound to play to a user when they are removed from a conversation and `removed_from_conversation.enabled` is `true`. + :param new_message_with_media_enabled: Whether to send a notification when a new message with media/file attachments is added to a conversation. The default is `false`. + :param new_message_with_media_template: The template to use to create the notification text displayed when a new message with media/file attachments is added to a conversation and `new_message.attachments.enabled` is `true`. + + :returns: The updated NotificationInstance + """ + + data = values.of( + { + "LogEnabled": serialize.boolean_to_string(log_enabled), + "NewMessage.Enabled": serialize.boolean_to_string(new_message_enabled), + "NewMessage.Template": new_message_template, + "NewMessage.Sound": new_message_sound, + "NewMessage.BadgeCountEnabled": serialize.boolean_to_string( + new_message_badge_count_enabled + ), + "AddedToConversation.Enabled": serialize.boolean_to_string( + added_to_conversation_enabled + ), + "AddedToConversation.Template": added_to_conversation_template, + "AddedToConversation.Sound": added_to_conversation_sound, + "RemovedFromConversation.Enabled": serialize.boolean_to_string( + removed_from_conversation_enabled + ), + "RemovedFromConversation.Template": removed_from_conversation_template, + "RemovedFromConversation.Sound": removed_from_conversation_sound, + "NewMessage.WithMedia.Enabled": serialize.boolean_to_string( + new_message_with_media_enabled + ), + "NewMessage.WithMedia.Template": new_message_with_media_template, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NotificationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.NotificationContext {}>".format(context) + + +class NotificationList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the NotificationList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Configuration applies to. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + + def get(self) -> NotificationContext: + """ + Constructs a NotificationContext + + """ + return NotificationContext( + self._version, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __call__(self) -> NotificationContext: + """ + Constructs a NotificationContext + + """ + return NotificationContext( + self._version, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.NotificationList>" diff --git a/twilio/rest/conversations/v1/service/configuration/webhook.py b/twilio/rest/conversations/v1/service/configuration/webhook.py new file mode 100644 index 0000000000..706f410550 --- /dev/null +++ b/twilio/rest/conversations/v1/service/configuration/webhook.py @@ -0,0 +1,340 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WebhookInstance(InstanceResource): + + class Method(object): + GET = "GET" + POST = "POST" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this service. + :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + :ivar pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :ivar post_webhook_url: The absolute url the post-event webhook request should be sent to. + :ivar filters: The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. + :ivar method: + :ivar url: An absolute API resource URL for this webhook. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], chat_service_sid: str + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.pre_webhook_url: Optional[str] = payload.get("pre_webhook_url") + self.post_webhook_url: Optional[str] = payload.get("post_webhook_url") + self.filters: Optional[List[str]] = payload.get("filters") + self.method: Optional["WebhookInstance.Method"] = payload.get("method") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._context: Optional[WebhookContext] = None + + @property + def _proxy(self) -> "WebhookContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WebhookContext for this WebhookInstance + """ + if self._context is None: + self._context = WebhookContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + ) + return self._context + + def fetch(self) -> "WebhookInstance": + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WebhookInstance": + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + method: Union[str, object] = values.unset, + ) -> "WebhookInstance": + """ + Update the WebhookInstance + + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param filters: The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. + :param method: The HTTP method to be used when sending a webhook request. One of `GET` or `POST`. + + :returns: The updated WebhookInstance + """ + return self._proxy.update( + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + filters=filters, + method=method, + ) + + async def update_async( + self, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + method: Union[str, object] = values.unset, + ) -> "WebhookInstance": + """ + Asynchronous coroutine to update the WebhookInstance + + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param filters: The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. + :param method: The HTTP method to be used when sending a webhook request. One of `GET` or `POST`. + + :returns: The updated WebhookInstance + """ + return await self._proxy.update_async( + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + filters=filters, + method=method, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.WebhookInstance {}>".format(context) + + +class WebhookContext(InstanceContext): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the WebhookContext + + :param version: Version that contains the resource + :param chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._uri = "/Services/{chat_service_sid}/Configuration/Webhooks".format( + **self._solution + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + ) + + def update( + self, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + method: Union[str, object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param filters: The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. + :param method: The HTTP method to be used when sending a webhook request. One of `GET` or `POST`. + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "Filters": serialize.map(filters, lambda e: e), + "Method": method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def update_async( + self, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + filters: Union[List[str], object] = values.unset, + method: Union[str, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param pre_webhook_url: The absolute url the pre-event webhook request should be sent to. + :param post_webhook_url: The absolute url the post-event webhook request should be sent to. + :param filters: The list of events that your configured webhook targets will receive. Events not configured here will not fire. Possible values are `onParticipantAdd`, `onParticipantAdded`, `onDeliveryUpdated`, `onConversationUpdated`, `onConversationRemove`, `onParticipantRemove`, `onConversationUpdate`, `onMessageAdd`, `onMessageRemoved`, `onParticipantUpdated`, `onConversationAdded`, `onMessageAdded`, `onConversationAdd`, `onConversationRemoved`, `onParticipantUpdate`, `onMessageRemove`, `onMessageUpdated`, `onParticipantRemoved`, `onMessageUpdate` or `onConversationStateUpdated`. + :param method: The HTTP method to be used when sending a webhook request. One of `GET` or `POST`. + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "Filters": serialize.map(filters, lambda e: e), + "Method": method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.WebhookContext {}>".format(context) + + +class WebhookList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the WebhookList + + :param version: Version that contains the resource + :param chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + + def get(self) -> WebhookContext: + """ + Constructs a WebhookContext + + """ + return WebhookContext( + self._version, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __call__(self) -> WebhookContext: + """ + Constructs a WebhookContext + + """ + return WebhookContext( + self._version, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.WebhookList>" diff --git a/twilio/rest/conversations/v1/service/conversation/__init__.py b/twilio/rest/conversations/v1/service/conversation/__init__.py new file mode 100644 index 0000000000..0f28c4dfe2 --- /dev/null +++ b/twilio/rest/conversations/v1/service/conversation/__init__.py @@ -0,0 +1,1069 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.conversations.v1.service.conversation.message import MessageList +from twilio.rest.conversations.v1.service.conversation.participant import ( + ParticipantList, +) +from twilio.rest.conversations.v1.service.conversation.webhook import WebhookList + + +class ConversationInstance(InstanceResource): + + class State(object): + INACTIVE = "inactive" + ACTIVE = "active" + CLOSED = "closed" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + :ivar messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :ivar attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar state: + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar timers: Timer date values representing state update for this conversation. + :ivar url: An absolute API resource URL for this conversation. + :ivar links: Contains absolute URLs to access the [participants](https://www.twilio.com/docs/conversations/api/conversation-participant-resource), [messages](https://www.twilio.com/docs/conversations/api/conversation-message-resource) and [webhooks](https://www.twilio.com/docs/conversations/api/conversation-scoped-webhook-resource) of this conversation. + :ivar bindings: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + chat_service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.state: Optional["ConversationInstance.State"] = payload.get("state") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.timers: Optional[Dict[str, object]] = payload.get("timers") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.bindings: Optional[Dict[str, object]] = payload.get("bindings") + + self._solution = { + "chat_service_sid": chat_service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ConversationContext] = None + + @property + def _proxy(self) -> "ConversationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConversationContext for this ConversationInstance + """ + if self._context is None: + self._context = ConversationContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "ConversationInstance": + """ + Fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConversationInstance": + """ + Asynchronous coroutine to fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> "ConversationInstance": + """ + Update the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The updated ConversationInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> "ConversationInstance": + """ + Asynchronous coroutine to update the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The updated ConversationInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + messaging_service_sid=messaging_service_sid, + state=state, + timers_inactive=timers_inactive, + timers_closed=timers_closed, + unique_name=unique_name, + bindings_email_address=bindings_email_address, + bindings_email_name=bindings_email_name, + ) + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + return self._proxy.participants + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + return self._proxy.webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.ConversationInstance {}>".format(context) + + +class ConversationContext(InstanceContext): + + def __init__(self, version: Version, chat_service_sid: str, sid: str): + """ + Initialize the ConversationContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Conversation resource is associated with. + :param sid: A 34 character string that uniquely identifies this resource. Can also be the `unique_name` of the Conversation. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "sid": sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations/{sid}".format( + **self._solution + ) + + self._messages: Optional[MessageList] = None + self._participants: Optional[ParticipantList] = None + self._webhooks: Optional[WebhookList] = None + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConversationInstance: + """ + Fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ConversationInstance: + """ + Asynchronous coroutine to fetch the ConversationInstance + + + :returns: The fetched ConversationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Update the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The updated ConversationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MessagingServiceSid": messaging_service_sid, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "UniqueName": unique_name, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Asynchronous coroutine to update the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The updated ConversationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MessagingServiceSid": messaging_service_sid, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "UniqueName": unique_name, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["chat_service_sid"], + self._solution["sid"], + ) + return self._messages + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + if self._participants is None: + self._participants = ParticipantList( + self._version, + self._solution["chat_service_sid"], + self._solution["sid"], + ) + return self._participants + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + if self._webhooks is None: + self._webhooks = WebhookList( + self._version, + self._solution["chat_service_sid"], + self._solution["sid"], + ) + return self._webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.ConversationContext {}>".format(context) + + +class ConversationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConversationInstance: + """ + Build an instance of ConversationInstance + + :param payload: Payload response from the API + """ + return ConversationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.ConversationPage>" + + +class ConversationList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the ConversationList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Conversation resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations".format( + **self._solution + ) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Create the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The created ConversationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "MessagingServiceSid": messaging_service_sid, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> ConversationInstance: + """ + Asynchronously create the ConversationInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + + :returns: The created ConversationInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "MessagingServiceSid": messaging_service_sid, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def stream( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConversationInstance]: + """ + Streams ConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + start_date=start_date, + end_date=end_date, + state=state, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConversationInstance]: + """ + Asynchronously streams ConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + start_date=start_date, + end_date=end_date, + state=state, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConversationInstance]: + """ + Lists ConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + start_date=start_date, + end_date=end_date, + state=state, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConversationInstance]: + """ + Asynchronously lists ConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param str end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param "ConversationInstance.State" state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + start_date=start_date, + end_date=end_date, + state=state, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConversationPage: + """ + Retrieve a single page of ConversationInstance records from the API. + Request is executed immediately + + :param start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConversationInstance + """ + data = values.of( + { + "StartDate": start_date, + "EndDate": end_date, + "State": state, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConversationPage(self._version, response, self._solution) + + async def page_async( + self, + start_date: Union[str, object] = values.unset, + end_date: Union[str, object] = values.unset, + state: Union["ConversationInstance.State", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConversationPage: + """ + Asynchronously retrieve a single page of ConversationInstance records from the API. + Request is executed immediately + + :param start_date: Specifies the beginning of the date range for filtering Conversations based on their creation date. Conversations that were created on or after this date will be included in the results. The date must be in ISO8601 format, specifically starting at the beginning of the specified date (YYYY-MM-DDT00:00:00Z), for precise filtering. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param end_date: Defines the end of the date range for filtering conversations by their creation date. Only conversations that were created on or before this date will appear in the results. The date must be in ISO8601 format, specifically capturing up to the end of the specified date (YYYY-MM-DDT23:59:59Z), to ensure that conversations from the entire end day are included. This parameter can be combined with other filters. If this filter is used, the returned list is sorted by latest conversation creation date in descending order. + :param state: State for sorting and filtering list of Conversations. Can be `active`, `inactive` or `closed` + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConversationInstance + """ + data = values.of( + { + "StartDate": start_date, + "EndDate": end_date, + "State": state, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConversationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ConversationPage: + """ + Retrieve a specific page of ConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConversationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ConversationPage: + """ + Asynchronously retrieve a specific page of ConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConversationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConversationPage(self._version, response, self._solution) + + def get(self, sid: str) -> ConversationContext: + """ + Constructs a ConversationContext + + :param sid: A 34 character string that uniquely identifies this resource. Can also be the `unique_name` of the Conversation. + """ + return ConversationContext( + self._version, chat_service_sid=self._solution["chat_service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ConversationContext: + """ + Constructs a ConversationContext + + :param sid: A 34 character string that uniquely identifies this resource. Can also be the `unique_name` of the Conversation. + """ + return ConversationContext( + self._version, chat_service_sid=self._solution["chat_service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.ConversationList>" diff --git a/twilio/rest/conversations/v1/service/conversation/message/__init__.py b/twilio/rest/conversations/v1/service/conversation/message/__init__.py new file mode 100644 index 0000000000..c4123afd34 --- /dev/null +++ b/twilio/rest/conversations/v1/service/conversation/message/__init__.py @@ -0,0 +1,943 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.conversations.v1.service.conversation.message.delivery_receipt import ( + DeliveryReceiptList, +) + + +class MessageInstance(InstanceResource): + + class OrderType(object): + ASC = "asc" + DESC = "desc" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this message. + :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar index: The index of the message within the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource). + :ivar author: The channel specific identifier of the message's author. Defaults to `system`. + :ivar body: The content of the message, can be up to 1,600 characters long. + :ivar media: An array of objects that describe the Message's media, if the message contains media. Each object contains these fields: `content_type` with the MIME type of the media, `filename` with the name of the media, `sid` with the SID of the Media resource, and `size` with the media object's file size in bytes. If the Message has no media, this value is `null`. + :ivar attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar participant_sid: The unique ID of messages's author participant. Null in case of `system` sent message. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :ivar delivery: An object that contains the summary of delivery statuses for the message to non-chat participants. + :ivar url: An absolute API resource URL for this message. + :ivar links: Contains an absolute API resource URL to access the delivery & read receipts of this message. + :ivar content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + chat_service_sid: str, + conversation_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.sid: Optional[str] = payload.get("sid") + self.index: Optional[int] = deserialize.integer(payload.get("index")) + self.author: Optional[str] = payload.get("author") + self.body: Optional[str] = payload.get("body") + self.media: Optional[List[Dict[str, object]]] = payload.get("media") + self.attributes: Optional[str] = payload.get("attributes") + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.delivery: Optional[Dict[str, object]] = payload.get("delivery") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.content_sid: Optional[str] = payload.get("content_sid") + + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + "sid": sid or self.sid, + } + self._context: Optional[MessageContext] = None + + @property + def _proxy(self) -> "MessageContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The updated MessageInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Asynchronous coroutine to update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The updated MessageInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + author=author, + body=body, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + subject=subject, + ) + + @property + def delivery_receipts(self) -> DeliveryReceiptList: + """ + Access the delivery_receipts + """ + return self._proxy.delivery_receipts + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.MessageInstance {}>".format(context) + + +class MessageContext(InstanceContext): + + def __init__( + self, version: Version, chat_service_sid: str, conversation_sid: str, sid: str + ): + """ + Initialize the MessageContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + "sid": sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations/{conversation_sid}/Messages/{sid}".format( + **self._solution + ) + + self._delivery_receipts: Optional[DeliveryReceiptList] = None + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Author": author, + "Body": body, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "Subject": subject, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Author": author, + "Body": body, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "Subject": subject, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + @property + def delivery_receipts(self) -> DeliveryReceiptList: + """ + Access the delivery_receipts + """ + if self._delivery_receipts is None: + self._delivery_receipts = DeliveryReceiptList( + self._version, + self._solution["chat_service_sid"], + self._solution["conversation_sid"], + self._solution["sid"], + ) + return self._delivery_receipts + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.MessageContext {}>".format(context) + + +class MessagePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance + + :param payload: Payload response from the API + """ + return MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.MessagePage>" + + +class MessageList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str, conversation_sid: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for messages. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations/{conversation_sid}/Messages".format( + **self._solution + ) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + content_sid: Union[str, object] = values.unset, + content_variables: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param media_sid: The Media SID to be attached to the new Message. + :param content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. + :param content_variables: A structurally valid JSON string that contains values to resolve Rich Content template variables. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The created MessageInstance + """ + + data = values.of( + { + "Author": author, + "Body": body, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MediaSid": media_sid, + "ContentSid": content_sid, + "ContentVariables": content_variables, + "Subject": subject, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + author: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + content_sid: Union[str, object] = values.unset, + content_variables: Union[str, object] = values.unset, + subject: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param author: The channel specific identifier of the message's author. Defaults to `system`. + :param body: The content of the message, can be up to 1,600 characters long. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. `null` if the message has not been edited. + :param attributes: A string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param media_sid: The Media SID to be attached to the new Message. + :param content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. + :param content_variables: A structurally valid JSON string that contains values to resolve Rich Content template variables. + :param subject: The subject of the message, can be up to 256 characters long. + + :returns: The created MessageInstance + """ + + data = values.of( + { + "Author": author, + "Body": body, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MediaSid": media_sid, + "ContentSid": content_sid, + "ContentVariables": content_variables, + "Subject": subject, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: + """ + Streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(order=order, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInstance]: + """ + Asynchronously streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(order=order, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + order=order, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Asynchronously lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + order=order, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + async def page_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: The sort order of the returned messages. Can be: `asc` (ascending) or `desc` (descending), with `asc` as the default. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MessagePage: + """ + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MessagePage: + """ + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) + + def get(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return MessageContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return MessageContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.MessageList>" diff --git a/twilio/rest/conversations/v1/service/conversation/message/delivery_receipt.py b/twilio/rest/conversations/v1/service/conversation/message/delivery_receipt.py new file mode 100644 index 0000000000..939b631271 --- /dev/null +++ b/twilio/rest/conversations/v1/service/conversation/message/delivery_receipt.py @@ -0,0 +1,505 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DeliveryReceiptInstance(InstanceResource): + + class DeliveryStatus(object): + READ = "read" + FAILED = "failed" + DELIVERED = "delivered" + UNDELIVERED = "undelivered" + SENT = "sent" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this participant. + :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Message resource is associated with. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :ivar message_sid: The SID of the message within a [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) the delivery receipt belongs to + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar channel_message_sid: A messaging channel-specific identifier for the message delivered to participant e.g. `SMxx` for SMS, `WAxx` for Whatsapp etc. + :ivar participant_sid: The unique ID of the participant the delivery receipt belongs to. + :ivar status: + :ivar error_code: The message [delivery error code](https://www.twilio.com/docs/sms/api/message-resource#delivery-related-errors) for a `failed` status, + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. `null` if the delivery receipt has not been updated. + :ivar url: An absolute API resource URL for this delivery receipt. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + chat_service_sid: str, + conversation_sid: str, + message_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.message_sid: Optional[str] = payload.get("message_sid") + self.sid: Optional[str] = payload.get("sid") + self.channel_message_sid: Optional[str] = payload.get("channel_message_sid") + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.status: Optional["DeliveryReceiptInstance.DeliveryStatus"] = payload.get( + "status" + ) + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + "message_sid": message_sid, + "sid": sid or self.sid, + } + self._context: Optional[DeliveryReceiptContext] = None + + @property + def _proxy(self) -> "DeliveryReceiptContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DeliveryReceiptContext for this DeliveryReceiptInstance + """ + if self._context is None: + self._context = DeliveryReceiptContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "DeliveryReceiptInstance": + """ + Fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DeliveryReceiptInstance": + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.DeliveryReceiptInstance {}>".format(context) + + +class DeliveryReceiptContext(InstanceContext): + + def __init__( + self, + version: Version, + chat_service_sid: str, + conversation_sid: str, + message_sid: str, + sid: str, + ): + """ + Initialize the DeliveryReceiptContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Message resource is associated with. + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :param message_sid: The SID of the message within a [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) the delivery receipt belongs to. + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + "message_sid": message_sid, + "sid": sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations/{conversation_sid}/Messages/{message_sid}/Receipts/{sid}".format( + **self._solution + ) + + def fetch(self) -> DeliveryReceiptInstance: + """ + Fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DeliveryReceiptInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> DeliveryReceiptInstance: + """ + Asynchronous coroutine to fetch the DeliveryReceiptInstance + + + :returns: The fetched DeliveryReceiptInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DeliveryReceiptInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.DeliveryReceiptContext {}>".format(context) + + +class DeliveryReceiptPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DeliveryReceiptInstance: + """ + Build an instance of DeliveryReceiptInstance + + :param payload: Payload response from the API + """ + return DeliveryReceiptInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.DeliveryReceiptPage>" + + +class DeliveryReceiptList(ListResource): + + def __init__( + self, + version: Version, + chat_service_sid: str, + conversation_sid: str, + message_sid: str, + ): + """ + Initialize the DeliveryReceiptList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Message resource is associated with. + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this message. + :param message_sid: The SID of the message within a [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) the delivery receipt belongs to. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + "message_sid": message_sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations/{conversation_sid}/Messages/{message_sid}/Receipts".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DeliveryReceiptInstance]: + """ + Streams DeliveryReceiptInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DeliveryReceiptInstance]: + """ + Asynchronously streams DeliveryReceiptInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeliveryReceiptInstance]: + """ + Lists DeliveryReceiptInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeliveryReceiptInstance]: + """ + Asynchronously lists DeliveryReceiptInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DeliveryReceiptPage: + """ + Retrieve a single page of DeliveryReceiptInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DeliveryReceiptInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DeliveryReceiptPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DeliveryReceiptPage: + """ + Asynchronously retrieve a single page of DeliveryReceiptInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DeliveryReceiptInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DeliveryReceiptPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DeliveryReceiptPage: + """ + Retrieve a specific page of DeliveryReceiptInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DeliveryReceiptInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DeliveryReceiptPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DeliveryReceiptPage: + """ + Asynchronously retrieve a specific page of DeliveryReceiptInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DeliveryReceiptInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DeliveryReceiptPage(self._version, response, self._solution) + + def get(self, sid: str) -> DeliveryReceiptContext: + """ + Constructs a DeliveryReceiptContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return DeliveryReceiptContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> DeliveryReceiptContext: + """ + Constructs a DeliveryReceiptContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return DeliveryReceiptContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.DeliveryReceiptList>" diff --git a/twilio/rest/conversations/v1/service/conversation/participant.py b/twilio/rest/conversations/v1/service/conversation/participant.py new file mode 100644 index 0000000000..03a3cead7e --- /dev/null +++ b/twilio/rest/conversations/v1/service/conversation/participant.py @@ -0,0 +1,925 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ParticipantInstance(InstanceResource): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this participant. + :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this participant. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :ivar attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :ivar messaging_binding: Information about how this participant exchanges messages with the conversation. A JSON parameter consisting of type and address fields of the participant. + :ivar role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :ivar date_created: The date on which this resource was created. + :ivar date_updated: The date on which this resource was last updated. + :ivar url: An absolute API resource URL for this participant. + :ivar last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :ivar last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + chat_service_sid: str, + conversation_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.sid: Optional[str] = payload.get("sid") + self.identity: Optional[str] = payload.get("identity") + self.attributes: Optional[str] = payload.get("attributes") + self.messaging_binding: Optional[Dict[str, object]] = payload.get( + "messaging_binding" + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.last_read_message_index: Optional[int] = deserialize.integer( + payload.get("last_read_message_index") + ) + self.last_read_timestamp: Optional[str] = payload.get("last_read_timestamp") + + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + "sid": sid or self.sid, + } + self._context: Optional[ParticipantContext] = None + + @property + def _proxy(self) -> "ParticipantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ParticipantContext for this ParticipantInstance + """ + if self._context is None: + self._context = ParticipantContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "ParticipantInstance": + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ParticipantInstance": + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + identity: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> "ParticipantInstance": + """ + Update the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: The updated ParticipantInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + identity=identity, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + identity: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> "ParticipantInstance": + """ + Asynchronous coroutine to update the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: The updated ParticipantInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + date_created=date_created, + date_updated=date_updated, + identity=identity, + attributes=attributes, + role_sid=role_sid, + messaging_binding_proxy_address=messaging_binding_proxy_address, + messaging_binding_projected_address=messaging_binding_projected_address, + last_read_message_index=last_read_message_index, + last_read_timestamp=last_read_timestamp, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.ParticipantInstance {}>".format(context) + + +class ParticipantContext(InstanceContext): + + def __init__( + self, version: Version, chat_service_sid: str, conversation_sid: str, sid: str + ): + """ + Initialize the ParticipantContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this participant. + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + "sid": sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations/{conversation_sid}/Participants/{sid}".format( + **self._solution + ) + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + identity: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Update the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: The updated ParticipantInstance + """ + + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Identity": identity, + "Attributes": attributes, + "RoleSid": role_sid, + "MessagingBinding.ProxyAddress": messaging_binding_proxy_address, + "MessagingBinding.ProjectedAddress": messaging_binding_projected_address, + "LastReadMessageIndex": last_read_message_index, + "LastReadTimestamp": last_read_timestamp, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + identity: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + last_read_timestamp: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronous coroutine to update the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + :param messaging_binding_proxy_address: The address of the Twilio phone number that the participant is in contact with. 'null' value will remove it. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. 'null' value will remove it. + :param last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + :param last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. + + :returns: The updated ParticipantInstance + """ + + data = values.of( + { + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Identity": identity, + "Attributes": attributes, + "RoleSid": role_sid, + "MessagingBinding.ProxyAddress": messaging_binding_proxy_address, + "MessagingBinding.ProjectedAddress": messaging_binding_projected_address, + "LastReadMessageIndex": last_read_message_index, + "LastReadTimestamp": last_read_timestamp, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.ParticipantContext {}>".format(context) + + +class ParticipantPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: + """ + Build an instance of ParticipantInstance + + :param payload: Payload response from the API + """ + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.ParticipantPage>" + + +class ParticipantList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str, conversation_sid: str): + """ + Initialize the ParticipantList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for participants. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations/{conversation_sid}/Participants".format( + **self._solution + ) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + identity: Union[str, object] = values.unset, + messaging_binding_address: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Create the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param messaging_binding_address: The address of the participant's device, e.g. a phone or WhatsApp number. Together with the Proxy address, this determines a participant uniquely. This field (with `proxy_address`) is only null when the participant is interacting from an SDK endpoint (see the `identity` field). + :param messaging_binding_proxy_address: The address of the Twilio phone number (or WhatsApp number) that the participant is in contact with. This field, together with participant address, is only null when the participant is interacting from an SDK endpoint (see the `identity` field). + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + + :returns: The created ParticipantInstance + """ + + data = values.of( + { + "Identity": identity, + "MessagingBinding.Address": messaging_binding_address, + "MessagingBinding.ProxyAddress": messaging_binding_proxy_address, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MessagingBinding.ProjectedAddress": messaging_binding_projected_address, + "RoleSid": role_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ParticipantInstance.WebhookEnabledType", object + ] = values.unset, + identity: Union[str, object] = values.unset, + messaging_binding_address: Union[str, object] = values.unset, + messaging_binding_proxy_address: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + messaging_binding_projected_address: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronously create the ParticipantInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the [Conversation SDK](https://www.twilio.com/docs/conversations/sdk-overview) to communicate. Limited to 256 characters. + :param messaging_binding_address: The address of the participant's device, e.g. a phone or WhatsApp number. Together with the Proxy address, this determines a participant uniquely. This field (with `proxy_address`) is only null when the participant is interacting from an SDK endpoint (see the `identity` field). + :param messaging_binding_proxy_address: The address of the Twilio phone number (or WhatsApp number) that the participant is in contact with. This field, together with participant address, is only null when the participant is interacting from an SDK endpoint (see the `identity` field). + :param date_created: The date on which this resource was created. + :param date_updated: The date on which this resource was last updated. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set `{}` will be returned. + :param messaging_binding_projected_address: The address of the Twilio phone number that is used in Group MMS. + :param role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. + + :returns: The created ParticipantInstance + """ + + data = values.of( + { + "Identity": identity, + "MessagingBinding.Address": messaging_binding_address, + "MessagingBinding.ProxyAddress": messaging_binding_proxy_address, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + "MessagingBinding.ProjectedAddress": messaging_binding_projected_address, + "RoleSid": role_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantInstance]: + """ + Streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ParticipantInstance]: + """ + Asynchronously streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Asynchronously lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Asynchronously retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ParticipantPage: + """ + Retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ParticipantPage: + """ + Asynchronously retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + def get(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return ParticipantContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return ParticipantContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.ParticipantList>" diff --git a/twilio/rest/conversations/v1/service/conversation/webhook.py b/twilio/rest/conversations/v1/service/conversation/webhook.py new file mode 100644 index 0000000000..08ec93ce4e --- /dev/null +++ b/twilio/rest/conversations/v1/service/conversation/webhook.py @@ -0,0 +1,788 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class WebhookInstance(InstanceResource): + + class Method(object): + GET = "GET" + POST = "POST" + + class Target(object): + WEBHOOK = "webhook" + TRIGGER = "trigger" + STUDIO = "studio" + + """ + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this webhook. + :ivar target: The target of this webhook: `webhook`, `studio`, `trigger` + :ivar url: An absolute API resource URL for this webhook. + :ivar configuration: The configuration of this webhook. Is defined based on target. + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + chat_service_sid: str, + conversation_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.target: Optional[str] = payload.get("target") + self.url: Optional[str] = payload.get("url") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + "sid": sid or self.sid, + } + self._context: Optional[WebhookContext] = None + + @property + def _proxy(self) -> "WebhookContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WebhookContext for this WebhookInstance + """ + if self._context is None: + self._context = WebhookContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "WebhookInstance": + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WebhookInstance": + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> "WebhookInstance": + """ + Update the WebhookInstance + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: The updated WebhookInstance + """ + return self._proxy.update( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> "WebhookInstance": + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: The updated WebhookInstance + """ + return await self._proxy.update_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.WebhookInstance {}>".format(context) + + +class WebhookContext(InstanceContext): + + def __init__( + self, version: Version, chat_service_sid: str, conversation_sid: str, sid: str + ): + """ + Initialize the WebhookContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this webhook. + :param sid: A 34 character string that uniquely identifies this resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + "sid": sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations/{conversation_sid}/Webhooks/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.WebhookContext {}>".format(context) + + +class WebhookPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: + """ + Build an instance of WebhookInstance + + :param payload: Payload response from the API + """ + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.WebhookPage>" + + +class WebhookList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str, conversation_sid: str): + """ + Initialize the WebhookList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. + :param conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this webhook. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "conversation_sid": conversation_sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations/{conversation_sid}/Webhooks".format( + **self._solution + ) + + def create( + self, + target: "WebhookInstance.Target", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_replay_after: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Create the WebhookInstance + + :param target: + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + :param configuration_replay_after: The message index for which and it's successors the webhook will be replayed. Not set by default + + :returns: The created WebhookInstance + """ + + data = values.of( + { + "Target": target, + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.ReplayAfter": configuration_replay_after, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + async def create_async( + self, + target: "WebhookInstance.Target", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_replay_after: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronously create the WebhookInstance + + :param target: + :param configuration_url: The absolute url the webhook request should be sent to. + :param configuration_method: + :param configuration_filters: The list of events, firing webhook event for this Conversation. + :param configuration_triggers: The list of keywords, firing webhook event for this Conversation. + :param configuration_flow_sid: The studio flow SID, where the webhook should be sent to. + :param configuration_replay_after: The message index for which and it's successors the webhook will be replayed. Not set by default + + :returns: The created WebhookInstance + """ + + data = values.of( + { + "Target": target, + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.ReplayAfter": configuration_replay_after, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WebhookInstance]: + """ + Streams WebhookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WebhookInstance]: + """ + Asynchronously streams WebhookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: + """ + Lists WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: + """ + Asynchronously lists WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebhookPage: + """ + Retrieve a single page of WebhookInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebhookInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebhookPage: + """ + Asynchronously retrieve a single page of WebhookInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebhookInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> WebhookPage: + """ + Retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WebhookPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> WebhookPage: + """ + Asynchronously retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WebhookPage(self._version, response, self._solution) + + def get(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return WebhookContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: A 34 character string that uniquely identifies this resource. + """ + return WebhookContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.WebhookList>" diff --git a/twilio/rest/conversations/v1/service/conversation_with_participants.py b/twilio/rest/conversations/v1/service/conversation_with_participants.py new file mode 100644 index 0000000000..ff82a8ce35 --- /dev/null +++ b/twilio/rest/conversations/v1/service/conversation_with_participants.py @@ -0,0 +1,272 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ConversationWithParticipantsInstance(InstanceResource): + + class State(object): + INACTIVE = "inactive" + ACTIVE = "active" + CLOSED = "closed" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + :ivar messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :ivar attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar state: + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar timers: Timer date values representing state update for this conversation. + :ivar links: Contains absolute URLs to access the [participants](https://www.twilio.com/docs/conversations/api/conversation-participant-resource), [messages](https://www.twilio.com/docs/conversations/api/conversation-message-resource) and [webhooks](https://www.twilio.com/docs/conversations/api/conversation-scoped-webhook-resource) of this conversation. + :ivar bindings: + :ivar url: An absolute API resource URL for this conversation. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], chat_service_sid: str + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.state: Optional["ConversationWithParticipantsInstance.State"] = ( + payload.get("state") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.timers: Optional[Dict[str, object]] = payload.get("timers") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.bindings: Optional[Dict[str, object]] = payload.get("bindings") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "chat_service_sid": chat_service_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return ( + "<Twilio.Conversations.V1.ConversationWithParticipantsInstance {}>".format( + context + ) + ) + + +class ConversationWithParticipantsList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the ConversationWithParticipantsList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Conversation resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._uri = "/Services/{chat_service_sid}/ConversationWithParticipants".format( + **self._solution + ) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "ConversationWithParticipantsInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union[ + "ConversationWithParticipantsInstance.State", object + ] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + participant: Union[List[str], object] = values.unset, + ) -> ConversationWithParticipantsInstance: + """ + Create the ConversationWithParticipantsInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + :param participant: The participant to be added to the conversation in JSON format. The JSON object attributes are as parameters in [Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). The maximum number of participants that can be added in a single request is 10. + + :returns: The created ConversationWithParticipantsInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "MessagingServiceSid": messaging_service_sid, + "Attributes": attributes, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + "Participant": serialize.map(participant, lambda e: e), + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationWithParticipantsInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ConversationWithParticipantsInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + state: Union[ + "ConversationWithParticipantsInstance.State", object + ] = values.unset, + timers_inactive: Union[str, object] = values.unset, + timers_closed: Union[str, object] = values.unset, + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + participant: Union[List[str], object] = values.unset, + ) -> ConversationWithParticipantsInstance: + """ + Asynchronously create the ConversationWithParticipantsInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used to address the resource in place of the resource's `sid` in the URL. + :param date_created: The date that this resource was created. + :param date_updated: The date that this resource was last updated. + :param messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :param attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \\\"{}\\\" will be returned. + :param state: + :param timers_inactive: ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. + :param timers_closed: ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. + :param bindings_email_address: The default email address that will be used when sending outbound emails in this conversation. + :param bindings_email_name: The default name that will be used when sending outbound emails in this conversation. + :param participant: The participant to be added to the conversation in JSON format. The JSON object attributes are as parameters in [Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). The maximum number of participants that can be added in a single request is 10. + + :returns: The created ConversationWithParticipantsInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "MessagingServiceSid": messaging_service_sid, + "Attributes": attributes, + "State": state, + "Timers.Inactive": timers_inactive, + "Timers.Closed": timers_closed, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, + "Participant": serialize.map(participant, lambda e: e), + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConversationWithParticipantsInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.ConversationWithParticipantsList>" diff --git a/twilio/rest/conversations/v1/service/participant_conversation.py b/twilio/rest/conversations/v1/service/participant_conversation.py new file mode 100644 index 0000000000..8ec561a7d9 --- /dev/null +++ b/twilio/rest/conversations/v1/service/participant_conversation.py @@ -0,0 +1,383 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ParticipantConversationInstance(InstanceResource): + + class State(object): + INACTIVE = "inactive" + ACTIVE = "active" + CLOSED = "closed" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + :ivar participant_sid: The unique ID of the [Participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource). + :ivar participant_user_sid: The unique string that identifies the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). + :ivar participant_identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :ivar participant_messaging_binding: Information about how this participant exchanges messages with the conversation. A JSON parameter consisting of type and address fields of the participant. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) this Participant belongs to. + :ivar conversation_unique_name: An application-defined string that uniquely identifies the Conversation resource. + :ivar conversation_friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :ivar conversation_attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar conversation_date_created: The date that this conversation was created, given in ISO 8601 format. + :ivar conversation_date_updated: The date that this conversation was last updated, given in ISO 8601 format. + :ivar conversation_created_by: Identity of the creator of this Conversation. + :ivar conversation_state: + :ivar conversation_timers: Timer date values representing state update for this conversation. + :ivar links: Contains absolute URLs to access the [participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) and [conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) of this conversation. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], chat_service_sid: str + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.participant_user_sid: Optional[str] = payload.get("participant_user_sid") + self.participant_identity: Optional[str] = payload.get("participant_identity") + self.participant_messaging_binding: Optional[Dict[str, object]] = payload.get( + "participant_messaging_binding" + ) + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.conversation_unique_name: Optional[str] = payload.get( + "conversation_unique_name" + ) + self.conversation_friendly_name: Optional[str] = payload.get( + "conversation_friendly_name" + ) + self.conversation_attributes: Optional[str] = payload.get( + "conversation_attributes" + ) + self.conversation_date_created: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("conversation_date_created")) + ) + self.conversation_date_updated: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("conversation_date_updated")) + ) + self.conversation_created_by: Optional[str] = payload.get( + "conversation_created_by" + ) + self.conversation_state: Optional["ParticipantConversationInstance.State"] = ( + payload.get("conversation_state") + ) + self.conversation_timers: Optional[Dict[str, object]] = payload.get( + "conversation_timers" + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "chat_service_sid": chat_service_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.ParticipantConversationInstance {}>".format( + context + ) + + +class ParticipantConversationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantConversationInstance: + """ + Build an instance of ParticipantConversationInstance + + :param payload: Payload response from the API + """ + return ParticipantConversationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.ParticipantConversationPage>" + + +class ParticipantConversationList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the ParticipantConversationList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant Conversations resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._uri = "/Services/{chat_service_sid}/ParticipantConversations".format( + **self._solution + ) + + def stream( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantConversationInstance]: + """ + Streams ParticipantConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + identity=identity, address=address, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ParticipantConversationInstance]: + """ + Asynchronously streams ParticipantConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + identity=identity, address=address, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantConversationInstance]: + """ + Lists ParticipantConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + address=address, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantConversationInstance]: + """ + Asynchronously lists ParticipantConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param str address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + address=address, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantConversationPage: + """ + Retrieve a single page of ParticipantConversationInstance records from the API. + Request is executed immediately + + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantConversationInstance + """ + data = values.of( + { + "Identity": identity, + "Address": address, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantConversationPage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[str, object] = values.unset, + address: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantConversationPage: + """ + Asynchronously retrieve a single page of ParticipantConversationInstance records from the API. + Request is executed immediately + + :param identity: A unique string identifier for the conversation participant as [Conversation User](https://www.twilio.com/docs/conversations/api/user-resource). This parameter is non-null if (and only if) the participant is using the Conversations SDK to communicate. Limited to 256 characters. + :param address: A unique string identifier for the conversation participant who's not a Conversation User. This parameter could be found in messaging_binding.address field of Participant resource. It should be url-encoded. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantConversationInstance + """ + data = values.of( + { + "Identity": identity, + "Address": address, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantConversationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ParticipantConversationPage: + """ + Retrieve a specific page of ParticipantConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantConversationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantConversationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ParticipantConversationPage: + """ + Asynchronously retrieve a specific page of ParticipantConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantConversationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantConversationPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.ParticipantConversationList>" diff --git a/twilio/rest/conversations/v1/service/role.py b/twilio/rest/conversations/v1/service/role.py new file mode 100644 index 0000000000..0884fb008b --- /dev/null +++ b/twilio/rest/conversations/v1/service/role.py @@ -0,0 +1,645 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RoleInstance(InstanceResource): + + class RoleType(object): + CONVERSATION = "conversation" + SERVICE = "service" + + """ + :ivar sid: The unique string that we created to identify the Role resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Role resource. + :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Role resource is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar permissions: An array of the permissions the role has been granted. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: An absolute API resource URL for this user role. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + chat_service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["RoleInstance.RoleType"] = payload.get("type") + self.permissions: Optional[List[str]] = payload.get("permissions") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "chat_service_sid": chat_service_sid, + "sid": sid or self.sid, + } + self._context: Optional[RoleContext] = None + + @property + def _proxy(self) -> "RoleContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoleContext for this RoleInstance + """ + if self._context is None: + self._context = RoleContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RoleInstance": + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RoleInstance": + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return await self._proxy.fetch_async() + + def update(self, permission: List[str]) -> "RoleInstance": + """ + Update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + return self._proxy.update( + permission=permission, + ) + + async def update_async(self, permission: List[str]) -> "RoleInstance": + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + return await self._proxy.update_async( + permission=permission, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.RoleInstance {}>".format(context) + + +class RoleContext(InstanceContext): + + def __init__(self, version: Version, chat_service_sid: str, sid: str): + """ + Initialize the RoleContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to update the Role resource in. + :param sid: The SID of the Role resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "sid": sid, + } + self._uri = "/Services/{chat_service_sid}/Roles/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + def update(self, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: A permission that you grant to the role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. Note that the update action replaces all previously assigned permissions with those defined in the update action. To remove a permission, do not include it in the subsequent update action. The values for this parameter depend on the role's `type`. + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.RoleContext {}>".format(context) + + +class RolePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: + """ + Build an instance of RoleInstance + + :param payload: Payload response from the API + """ + return RoleInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.RolePage>" + + +class RoleList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the RoleList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to read the Role resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._uri = "/Services/{chat_service_sid}/Roles".format(**self._solution) + + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: A descriptive string that you create to describe the new resource. It can be up to 64 characters long. + :param type: + :param permission: A permission that you grant to the new role. Only one permission can be granted per parameter. To assign more than one permission, repeat this parameter for each permission value. The values for this parameter depend on the role's `type`. + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoleInstance]: + """ + Streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoleInstance]: + """ + Asynchronously streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Asynchronously lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Asynchronously retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RolePage: + """ + Retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RolePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RolePage: + """ + Asynchronously retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RolePage(self._version, response, self._solution) + + def get(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: The SID of the Role resource to update. + """ + return RoleContext( + self._version, chat_service_sid=self._solution["chat_service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: The SID of the Role resource to update. + """ + return RoleContext( + self._version, chat_service_sid=self._solution["chat_service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.RoleList>" diff --git a/twilio/rest/conversations/v1/service/user/__init__.py b/twilio/rest/conversations/v1/service/user/__init__.py new file mode 100644 index 0000000000..b8cda74c8c --- /dev/null +++ b/twilio/rest/conversations/v1/service/user/__init__.py @@ -0,0 +1,818 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.conversations.v1.service.user.user_conversation import ( + UserConversationList, +) + + +class UserInstance(InstanceResource): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: The unique string that we created to identify the User resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the User resource. + :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the User resource is associated with. + :ivar role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) assigned to the user. + :ivar identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :ivar is_online: Whether the User is actively connected to this Conversations Service and online. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service's `reachability_enabled` is `false`, if the User has never been online for this Conversations Service, even if the Service's `reachability_enabled` is `true`. + :ivar is_notifiable: Whether the User has a potentially valid Push Notification registration (APN or GCM) for this Conversations Service. If at least one registration exists, `true`; otherwise `false`. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service's `reachability_enabled` is `false`, and if the User has never had a notification registration, even if the Service's `reachability_enabled` is `true`. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: An absolute API resource URL for this user. + :ivar links: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + chat_service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.role_sid: Optional[str] = payload.get("role_sid") + self.identity: Optional[str] = payload.get("identity") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.attributes: Optional[str] = payload.get("attributes") + self.is_online: Optional[bool] = payload.get("is_online") + self.is_notifiable: Optional[bool] = payload.get("is_notifiable") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "chat_service_sid": chat_service_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserContext] = None + + @property + def _proxy(self) -> "UserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The updated UserInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The updated UserInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + + @property + def user_conversations(self) -> UserConversationList: + """ + Access the user_conversations + """ + return self._proxy.user_conversations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.UserInstance {}>".format(context) + + +class UserContext(InstanceContext): + + def __init__(self, version: Version, chat_service_sid: str, sid: str): + """ + Initialize the UserContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the User resource is associated with. + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "sid": sid, + } + self._uri = "/Services/{chat_service_sid}/Users/{sid}".format(**self._solution) + + self._user_conversations: Optional[UserConversationList] = None + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The updated UserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": attributes, + "RoleSid": role_sid, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The updated UserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": attributes, + "RoleSid": role_sid, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], + ) + + @property + def user_conversations(self) -> UserConversationList: + """ + Access the user_conversations + """ + if self._user_conversations is None: + self._user_conversations = UserConversationList( + self._version, + self._solution["chat_service_sid"], + self._solution["sid"], + ) + return self._user_conversations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.UserContext {}>".format(context) + + +class UserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance + + :param payload: Payload response from the API + """ + return UserInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.UserPage>" + + +class UserList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the UserList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) to read the User resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._uri = "/Services/{chat_service_sid}/Users".format(**self._solution) + + def create( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Create the UserInstance + + :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "FriendlyName": friendly_name, + "Attributes": attributes, + "RoleSid": role_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "FriendlyName": friendly_name, + "Attributes": attributes, + "RoleSid": role_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserInstance]: + """ + Streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserInstance]: + """ + Asynchronously streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Asynchronously lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserPage: + """ + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserPage: + """ + Asynchronously retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserPage(self._version, response, self._solution) + + def get(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + return UserContext( + self._version, chat_service_sid=self._solution["chat_service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + return UserContext( + self._version, chat_service_sid=self._solution["chat_service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.UserList>" diff --git a/twilio/rest/conversations/v1/service/user/user_conversation.py b/twilio/rest/conversations/v1/service/user/user_conversation.py new file mode 100644 index 0000000000..4f1727f8e8 --- /dev/null +++ b/twilio/rest/conversations/v1/service/user/user_conversation.py @@ -0,0 +1,684 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UserConversationInstance(InstanceResource): + + class NotificationLevel(object): + DEFAULT = "default" + MUTED = "muted" + + class State(object): + INACTIVE = "inactive" + ACTIVE = "active" + CLOSED = "closed" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this User Conversation. + :ivar unread_messages_count: The number of unread Messages in the Conversation for the Participant. + :ivar last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + :ivar participant_sid: The unique ID of the [participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) the user conversation belongs to. + :ivar user_sid: The unique string that identifies the [User resource](https://www.twilio.com/docs/conversations/api/user-resource). + :ivar friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :ivar conversation_state: + :ivar timers: Timer date values representing state update for this conversation. + :ivar attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar date_created: The date that this conversation was created, given in ISO 8601 format. + :ivar date_updated: The date that this conversation was last updated, given in ISO 8601 format. + :ivar created_by: Identity of the creator of this Conversation. + :ivar notification_level: + :ivar unique_name: An application-defined string that uniquely identifies the Conversation resource. It can be used to address the resource in place of the resource's `conversation_sid` in the URL. + :ivar url: + :ivar links: Contains absolute URLs to access the [participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) and [conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) of this conversation. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + chat_service_sid: str, + user_sid: str, + conversation_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.unread_messages_count: Optional[int] = deserialize.integer( + payload.get("unread_messages_count") + ) + self.last_read_message_index: Optional[int] = deserialize.integer( + payload.get("last_read_message_index") + ) + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.user_sid: Optional[str] = payload.get("user_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.conversation_state: Optional["UserConversationInstance.State"] = ( + payload.get("conversation_state") + ) + self.timers: Optional[Dict[str, object]] = payload.get("timers") + self.attributes: Optional[str] = payload.get("attributes") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + self.notification_level: Optional[ + "UserConversationInstance.NotificationLevel" + ] = payload.get("notification_level") + self.unique_name: Optional[str] = payload.get("unique_name") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "chat_service_sid": chat_service_sid, + "user_sid": user_sid, + "conversation_sid": conversation_sid or self.conversation_sid, + } + self._context: Optional[UserConversationContext] = None + + @property + def _proxy(self) -> "UserConversationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserConversationContext for this UserConversationInstance + """ + if self._context is None: + self._context = UserConversationContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserConversationInstance": + """ + Fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserConversationInstance": + """ + Asynchronous coroutine to fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> "UserConversationInstance": + """ + Update the UserConversationInstance + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: The updated UserConversationInstance + """ + return self._proxy.update( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + + async def update_async( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> "UserConversationInstance": + """ + Asynchronous coroutine to update the UserConversationInstance + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: The updated UserConversationInstance + """ + return await self._proxy.update_async( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.UserConversationInstance {}>".format(context) + + +class UserConversationContext(InstanceContext): + + def __init__( + self, + version: Version, + chat_service_sid: str, + user_sid: str, + conversation_sid: str, + ): + """ + Initialize the UserConversationContext + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Conversation resource is associated with. + :param user_sid: The unique SID identifier of the [User resource](https://www.twilio.com/docs/conversations/api/user-resource). This value can be either the `sid` or the `identity` of the User resource. + :param conversation_sid: The unique SID identifier of the Conversation. This value can be either the `sid` or the `unique_name` of the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource). + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "user_sid": user_sid, + "conversation_sid": conversation_sid, + } + self._uri = "/Services/{chat_service_sid}/Users/{user_sid}/Conversations/{conversation_sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the UserConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserConversationInstance: + """ + Fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + async def fetch_async(self) -> UserConversationInstance: + """ + Asynchronous coroutine to fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def update( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> UserConversationInstance: + """ + Update the UserConversationInstance + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: The updated UserConversationInstance + """ + + data = values.of( + { + "NotificationLevel": notification_level, + "LastReadTimestamp": serialize.iso8601_datetime(last_read_timestamp), + "LastReadMessageIndex": last_read_message_index, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + async def update_async( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> UserConversationInstance: + """ + Asynchronous coroutine to update the UserConversationInstance + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: The updated UserConversationInstance + """ + + data = values.of( + { + "NotificationLevel": notification_level, + "LastReadTimestamp": serialize.iso8601_datetime(last_read_timestamp), + "LastReadMessageIndex": last_read_message_index, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.UserConversationContext {}>".format(context) + + +class UserConversationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserConversationInstance: + """ + Build an instance of UserConversationInstance + + :param payload: Payload response from the API + """ + return UserConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.UserConversationPage>" + + +class UserConversationList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str, user_sid: str): + """ + Initialize the UserConversationList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Conversation resource is associated with. + :param user_sid: The unique SID identifier of the [User resource](https://www.twilio.com/docs/conversations/api/user-resource). This value can be either the `sid` or the `identity` of the User resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + "user_sid": user_sid, + } + self._uri = ( + "/Services/{chat_service_sid}/Users/{user_sid}/Conversations".format( + **self._solution + ) + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserConversationInstance]: + """ + Streams UserConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserConversationInstance]: + """ + Asynchronously streams UserConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserConversationInstance]: + """ + Lists UserConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserConversationInstance]: + """ + Asynchronously lists UserConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserConversationPage: + """ + Retrieve a single page of UserConversationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserConversationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserConversationPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserConversationPage: + """ + Asynchronously retrieve a single page of UserConversationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserConversationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserConversationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserConversationPage: + """ + Retrieve a specific page of UserConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserConversationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserConversationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserConversationPage: + """ + Asynchronously retrieve a specific page of UserConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserConversationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserConversationPage(self._version, response, self._solution) + + def get(self, conversation_sid: str) -> UserConversationContext: + """ + Constructs a UserConversationContext + + :param conversation_sid: The unique SID identifier of the Conversation. This value can be either the `sid` or the `unique_name` of the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource). + """ + return UserConversationContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=conversation_sid, + ) + + def __call__(self, conversation_sid: str) -> UserConversationContext: + """ + Constructs a UserConversationContext + + :param conversation_sid: The unique SID identifier of the Conversation. This value can be either the `sid` or the `unique_name` of the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource). + """ + return UserConversationContext( + self._version, + chat_service_sid=self._solution["chat_service_sid"], + user_sid=self._solution["user_sid"], + conversation_sid=conversation_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.UserConversationList>" diff --git a/twilio/rest/conversations/v1/user/__init__.py b/twilio/rest/conversations/v1/user/__init__.py new file mode 100644 index 0000000000..fe5d12f095 --- /dev/null +++ b/twilio/rest/conversations/v1/user/__init__.py @@ -0,0 +1,780 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.conversations.v1.user.user_conversation import UserConversationList + + +class UserInstance(InstanceResource): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: The unique string that we created to identify the User resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the User resource. + :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the User resource is associated with. + :ivar role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) assigned to the user. + :ivar identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :ivar is_online: Whether the User is actively connected to this Conversations Service and online. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service's `reachability_enabled` is `false`, if the User has never been online for this Conversations Service, even if the Service's `reachability_enabled` is `true`. + :ivar is_notifiable: Whether the User has a potentially valid Push Notification registration (APN or GCM) for this Conversations Service. If at least one registration exists, `true`; otherwise `false`. This value is only returned by Fetch actions that return a single resource and `null` is always returned by a Read action. This value is `null` if the Service's `reachability_enabled` is `false`, and if the User has never had a notification registration, even if the Service's `reachability_enabled` is `true`. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: An absolute API resource URL for this user. + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.role_sid: Optional[str] = payload.get("role_sid") + self.identity: Optional[str] = payload.get("identity") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.attributes: Optional[str] = payload.get("attributes") + self.is_online: Optional[bool] = payload.get("is_online") + self.is_notifiable: Optional[bool] = payload.get("is_notifiable") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[UserContext] = None + + @property + def _proxy(self) -> "UserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The updated UserInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The updated UserInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + attributes=attributes, + role_sid=role_sid, + ) + + @property + def user_conversations(self) -> UserConversationList: + """ + Access the user_conversations + """ + return self._proxy.user_conversations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.UserInstance {}>".format(context) + + +class UserContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the UserContext + + :param version: Version that contains the resource + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Users/{sid}".format(**self._solution) + + self._user_conversations: Optional[UserConversationList] = None + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The updated UserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": attributes, + "RoleSid": role_sid, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The updated UserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": attributes, + "RoleSid": role_sid, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def user_conversations(self) -> UserConversationList: + """ + Access the user_conversations + """ + if self._user_conversations is None: + self._user_conversations = UserConversationList( + self._version, + self._solution["sid"], + ) + return self._user_conversations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.UserContext {}>".format(context) + + +class UserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance + + :param payload: Payload response from the API + """ + return UserInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.UserPage>" + + +class UserList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the UserList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Users" + + def create( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Create the UserInstance + + :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "FriendlyName": friendly_name, + "Attributes": attributes, + "RoleSid": role_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance(self._version, payload) + + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + role_sid: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: The application-defined string that uniquely identifies the resource's User within the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource). This value is often a username or an email address, and is case-sensitive. + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The JSON Object string that stores application-specific data. If attributes have not been set, `{}` is returned. + :param role_sid: The SID of a service-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the user. + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "FriendlyName": friendly_name, + "Attributes": attributes, + "RoleSid": role_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserInstance]: + """ + Streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserInstance]: + """ + Asynchronously streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Asynchronously lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response) + + def get_page(self, target_url: str) -> UserPage: + """ + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response) + + async def get_page_async(self, target_url: str) -> UserPage: + """ + Asynchronously retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserPage(self._version, response) + + def get(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + return UserContext(self._version, sid=sid) + + def __call__(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + return UserContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.UserList>" diff --git a/twilio/rest/conversations/v1/user/user_conversation.py b/twilio/rest/conversations/v1/user/user_conversation.py new file mode 100644 index 0000000000..16ce2c2418 --- /dev/null +++ b/twilio/rest/conversations/v1/user/user_conversation.py @@ -0,0 +1,658 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UserConversationInstance(InstanceResource): + + class NotificationLevel(object): + DEFAULT = "default" + MUTED = "muted" + + class State(object): + INACTIVE = "inactive" + ACTIVE = "active" + CLOSED = "closed" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this User Conversation. + :ivar unread_messages_count: The number of unread Messages in the Conversation for the Participant. + :ivar last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + :ivar participant_sid: The unique ID of the [participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) the user conversation belongs to. + :ivar user_sid: The unique string that identifies the [User resource](https://www.twilio.com/docs/conversations/api/user-resource). + :ivar friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :ivar conversation_state: + :ivar timers: Timer date values representing state update for this conversation. + :ivar attributes: An optional string metadata field you can use to store any data you wish. The string value must contain structurally valid JSON if specified. **Note** that if the attributes are not set \"{}\" will be returned. + :ivar date_created: The date that this conversation was created, given in ISO 8601 format. + :ivar date_updated: The date that this conversation was last updated, given in ISO 8601 format. + :ivar created_by: Identity of the creator of this Conversation. + :ivar notification_level: + :ivar unique_name: An application-defined string that uniquely identifies the Conversation resource. It can be used to address the resource in place of the resource's `conversation_sid` in the URL. + :ivar url: + :ivar links: Contains absolute URLs to access the [participant](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) and [conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) of this conversation. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + user_sid: str, + conversation_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.unread_messages_count: Optional[int] = deserialize.integer( + payload.get("unread_messages_count") + ) + self.last_read_message_index: Optional[int] = deserialize.integer( + payload.get("last_read_message_index") + ) + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.user_sid: Optional[str] = payload.get("user_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.conversation_state: Optional["UserConversationInstance.State"] = ( + payload.get("conversation_state") + ) + self.timers: Optional[Dict[str, object]] = payload.get("timers") + self.attributes: Optional[str] = payload.get("attributes") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + self.notification_level: Optional[ + "UserConversationInstance.NotificationLevel" + ] = payload.get("notification_level") + self.unique_name: Optional[str] = payload.get("unique_name") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "user_sid": user_sid, + "conversation_sid": conversation_sid or self.conversation_sid, + } + self._context: Optional[UserConversationContext] = None + + @property + def _proxy(self) -> "UserConversationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserConversationContext for this UserConversationInstance + """ + if self._context is None: + self._context = UserConversationContext( + self._version, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserConversationInstance": + """ + Fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserConversationInstance": + """ + Asynchronous coroutine to fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> "UserConversationInstance": + """ + Update the UserConversationInstance + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: The updated UserConversationInstance + """ + return self._proxy.update( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + + async def update_async( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> "UserConversationInstance": + """ + Asynchronous coroutine to update the UserConversationInstance + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: The updated UserConversationInstance + """ + return await self._proxy.update_async( + notification_level=notification_level, + last_read_timestamp=last_read_timestamp, + last_read_message_index=last_read_message_index, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.UserConversationInstance {}>".format(context) + + +class UserConversationContext(InstanceContext): + + def __init__(self, version: Version, user_sid: str, conversation_sid: str): + """ + Initialize the UserConversationContext + + :param version: Version that contains the resource + :param user_sid: The unique SID identifier of the [User resource](https://www.twilio.com/docs/conversations/api/user-resource). This value can be either the `sid` or the `identity` of the User resource. + :param conversation_sid: The unique SID identifier of the Conversation. This value can be either the `sid` or the `unique_name` of the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource). + """ + super().__init__(version) + + # Path Solution + self._solution = { + "user_sid": user_sid, + "conversation_sid": conversation_sid, + } + self._uri = "/Users/{user_sid}/Conversations/{conversation_sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the UserConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserConversationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserConversationInstance: + """ + Fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + async def fetch_async(self) -> UserConversationInstance: + """ + Asynchronous coroutine to fetch the UserConversationInstance + + + :returns: The fetched UserConversationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def update( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> UserConversationInstance: + """ + Update the UserConversationInstance + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: The updated UserConversationInstance + """ + + data = values.of( + { + "NotificationLevel": notification_level, + "LastReadTimestamp": serialize.iso8601_datetime(last_read_timestamp), + "LastReadMessageIndex": last_read_message_index, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + async def update_async( + self, + notification_level: Union[ + "UserConversationInstance.NotificationLevel", object + ] = values.unset, + last_read_timestamp: Union[datetime, object] = values.unset, + last_read_message_index: Union[int, object] = values.unset, + ) -> UserConversationInstance: + """ + Asynchronous coroutine to update the UserConversationInstance + + :param notification_level: + :param last_read_timestamp: The date of the last message read in conversation by the user, given in ISO 8601 format. + :param last_read_message_index: The index of the last Message in the Conversation that the Participant has read. + + :returns: The updated UserConversationInstance + """ + + data = values.of( + { + "NotificationLevel": notification_level, + "LastReadTimestamp": serialize.iso8601_datetime(last_read_timestamp), + "LastReadMessageIndex": last_read_message_index, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Conversations.V1.UserConversationContext {}>".format(context) + + +class UserConversationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserConversationInstance: + """ + Build an instance of UserConversationInstance + + :param payload: Payload response from the API + """ + return UserConversationInstance( + self._version, payload, user_sid=self._solution["user_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.UserConversationPage>" + + +class UserConversationList(ListResource): + + def __init__(self, version: Version, user_sid: str): + """ + Initialize the UserConversationList + + :param version: Version that contains the resource + :param user_sid: The unique SID identifier of the [User resource](https://www.twilio.com/docs/conversations/api/user-resource). This value can be either the `sid` or the `identity` of the User resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "user_sid": user_sid, + } + self._uri = "/Users/{user_sid}/Conversations".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserConversationInstance]: + """ + Streams UserConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserConversationInstance]: + """ + Asynchronously streams UserConversationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserConversationInstance]: + """ + Lists UserConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserConversationInstance]: + """ + Asynchronously lists UserConversationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserConversationPage: + """ + Retrieve a single page of UserConversationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserConversationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserConversationPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserConversationPage: + """ + Asynchronously retrieve a single page of UserConversationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserConversationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserConversationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserConversationPage: + """ + Retrieve a specific page of UserConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserConversationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserConversationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserConversationPage: + """ + Asynchronously retrieve a specific page of UserConversationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserConversationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserConversationPage(self._version, response, self._solution) + + def get(self, conversation_sid: str) -> UserConversationContext: + """ + Constructs a UserConversationContext + + :param conversation_sid: The unique SID identifier of the Conversation. This value can be either the `sid` or the `unique_name` of the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource). + """ + return UserConversationContext( + self._version, + user_sid=self._solution["user_sid"], + conversation_sid=conversation_sid, + ) + + def __call__(self, conversation_sid: str) -> UserConversationContext: + """ + Constructs a UserConversationContext + + :param conversation_sid: The unique SID identifier of the Conversation. This value can be either the `sid` or the `unique_name` of the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource). + """ + return UserConversationContext( + self._version, + user_sid=self._solution["user_sid"], + conversation_sid=conversation_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Conversations.V1.UserConversationList>" diff --git a/twilio/rest/events/EventsBase.py b/twilio/rest/events/EventsBase.py new file mode 100644 index 0000000000..eb2251ae4e --- /dev/null +++ b/twilio/rest/events/EventsBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.events.v1 import V1 + + +class EventsBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Events Domain + + :returns: Domain for Events + """ + super().__init__(twilio, "https://events.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Events + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Events>" diff --git a/twilio/rest/events/__init__.py b/twilio/rest/events/__init__.py new file mode 100644 index 0000000000..c359cfe9c1 --- /dev/null +++ b/twilio/rest/events/__init__.py @@ -0,0 +1,45 @@ +from warnings import warn + +from twilio.rest.events.EventsBase import EventsBase +from twilio.rest.events.v1.event_type import EventTypeList +from twilio.rest.events.v1.schema import SchemaList +from twilio.rest.events.v1.sink import SinkList +from twilio.rest.events.v1.subscription import SubscriptionList + + +class Events(EventsBase): + @property + def event_types(self) -> EventTypeList: + warn( + "event_types is deprecated. Use v1.event_types instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.event_types + + @property + def schemas(self) -> SchemaList: + warn( + "schemas is deprecated. Use v1.schemas instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.schemas + + @property + def sinks(self) -> SinkList: + warn( + "sinks is deprecated. Use v1.sinks instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.sinks + + @property + def subscriptions(self) -> SubscriptionList: + warn( + "subscriptions is deprecated. Use v1.subscriptions instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.subscriptions diff --git a/twilio/rest/events/v1/__init__.py b/twilio/rest/events/v1/__init__.py new file mode 100644 index 0000000000..6b91355444 --- /dev/null +++ b/twilio/rest/events/v1/__init__.py @@ -0,0 +1,67 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Events + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.events.v1.event_type import EventTypeList +from twilio.rest.events.v1.schema import SchemaList +from twilio.rest.events.v1.sink import SinkList +from twilio.rest.events.v1.subscription import SubscriptionList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Events + + :param domain: The Twilio.events domain + """ + super().__init__(domain, "v1") + self._event_types: Optional[EventTypeList] = None + self._schemas: Optional[SchemaList] = None + self._sinks: Optional[SinkList] = None + self._subscriptions: Optional[SubscriptionList] = None + + @property + def event_types(self) -> EventTypeList: + if self._event_types is None: + self._event_types = EventTypeList(self) + return self._event_types + + @property + def schemas(self) -> SchemaList: + if self._schemas is None: + self._schemas = SchemaList(self) + return self._schemas + + @property + def sinks(self) -> SinkList: + if self._sinks is None: + self._sinks = SinkList(self) + return self._sinks + + @property + def subscriptions(self) -> SubscriptionList: + if self._subscriptions is None: + self._subscriptions = SubscriptionList(self) + return self._subscriptions + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Events.V1>" diff --git a/twilio/rest/events/v1/event_type.py b/twilio/rest/events/v1/event_type.py new file mode 100644 index 0000000000..7eaaeb03ba --- /dev/null +++ b/twilio/rest/events/v1/event_type.py @@ -0,0 +1,437 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Events + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EventTypeInstance(InstanceResource): + """ + :ivar type: A string that uniquely identifies this Event Type. + :ivar schema_id: A string that uniquely identifies the Schema this Event Type adheres to. + :ivar date_created: The date that this Event Type was created, given in ISO 8601 format. + :ivar date_updated: The date that this Event Type was updated, given in ISO 8601 format. + :ivar description: A human readable description for this Event Type. + :ivar status: A string that describes how this Event Type can be used. For example: `available`, `deprecated`, `restricted`, `discontinued`. When the status is `available`, the Event Type can be used normally. + :ivar documentation_url: The URL to the documentation or to the most relevant Twilio Changelog entry of this Event Type. + :ivar url: The URL of this resource. + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], type: Optional[str] = None + ): + super().__init__(version) + + self.type: Optional[str] = payload.get("type") + self.schema_id: Optional[str] = payload.get("schema_id") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.description: Optional[str] = payload.get("description") + self.status: Optional[str] = payload.get("status") + self.documentation_url: Optional[str] = payload.get("documentation_url") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "type": type or self.type, + } + self._context: Optional[EventTypeContext] = None + + @property + def _proxy(self) -> "EventTypeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EventTypeContext for this EventTypeInstance + """ + if self._context is None: + self._context = EventTypeContext( + self._version, + type=self._solution["type"], + ) + return self._context + + def fetch(self) -> "EventTypeInstance": + """ + Fetch the EventTypeInstance + + + :returns: The fetched EventTypeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EventTypeInstance": + """ + Asynchronous coroutine to fetch the EventTypeInstance + + + :returns: The fetched EventTypeInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Events.V1.EventTypeInstance {}>".format(context) + + +class EventTypeContext(InstanceContext): + + def __init__(self, version: Version, type: str): + """ + Initialize the EventTypeContext + + :param version: Version that contains the resource + :param type: A string that uniquely identifies this Event Type. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "type": type, + } + self._uri = "/Types/{type}".format(**self._solution) + + def fetch(self) -> EventTypeInstance: + """ + Fetch the EventTypeInstance + + + :returns: The fetched EventTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EventTypeInstance( + self._version, + payload, + type=self._solution["type"], + ) + + async def fetch_async(self) -> EventTypeInstance: + """ + Asynchronous coroutine to fetch the EventTypeInstance + + + :returns: The fetched EventTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EventTypeInstance( + self._version, + payload, + type=self._solution["type"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Events.V1.EventTypeContext {}>".format(context) + + +class EventTypePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EventTypeInstance: + """ + Build an instance of EventTypeInstance + + :param payload: Payload response from the API + """ + return EventTypeInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Events.V1.EventTypePage>" + + +class EventTypeList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the EventTypeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Types" + + def stream( + self, + schema_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EventTypeInstance]: + """ + Streams EventTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str schema_id: A string parameter filtering the results to return only the Event Types using a given schema. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(schema_id=schema_id, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + schema_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EventTypeInstance]: + """ + Asynchronously streams EventTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str schema_id: A string parameter filtering the results to return only the Event Types using a given schema. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(schema_id=schema_id, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + schema_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventTypeInstance]: + """ + Lists EventTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str schema_id: A string parameter filtering the results to return only the Event Types using a given schema. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + schema_id=schema_id, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + schema_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventTypeInstance]: + """ + Asynchronously lists EventTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str schema_id: A string parameter filtering the results to return only the Event Types using a given schema. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + schema_id=schema_id, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + schema_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventTypePage: + """ + Retrieve a single page of EventTypeInstance records from the API. + Request is executed immediately + + :param schema_id: A string parameter filtering the results to return only the Event Types using a given schema. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventTypeInstance + """ + data = values.of( + { + "SchemaId": schema_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventTypePage(self._version, response) + + async def page_async( + self, + schema_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventTypePage: + """ + Asynchronously retrieve a single page of EventTypeInstance records from the API. + Request is executed immediately + + :param schema_id: A string parameter filtering the results to return only the Event Types using a given schema. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventTypeInstance + """ + data = values.of( + { + "SchemaId": schema_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventTypePage(self._version, response) + + def get_page(self, target_url: str) -> EventTypePage: + """ + Retrieve a specific page of EventTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventTypeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EventTypePage(self._version, response) + + async def get_page_async(self, target_url: str) -> EventTypePage: + """ + Asynchronously retrieve a specific page of EventTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventTypeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EventTypePage(self._version, response) + + def get(self, type: str) -> EventTypeContext: + """ + Constructs a EventTypeContext + + :param type: A string that uniquely identifies this Event Type. + """ + return EventTypeContext(self._version, type=type) + + def __call__(self, type: str) -> EventTypeContext: + """ + Constructs a EventTypeContext + + :param type: A string that uniquely identifies this Event Type. + """ + return EventTypeContext(self._version, type=type) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Events.V1.EventTypeList>" diff --git a/twilio/rest/events/v1/schema/__init__.py b/twilio/rest/events/v1/schema/__init__.py new file mode 100644 index 0000000000..2c7ffa6b28 --- /dev/null +++ b/twilio/rest/events/v1/schema/__init__.py @@ -0,0 +1,221 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Events + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.events.v1.schema.schema_version import SchemaVersionList + + +class SchemaInstance(InstanceResource): + """ + :ivar id: The unique identifier of the schema. Each schema can have multiple versions, that share the same id. + :ivar url: The URL of this resource. + :ivar links: Contains a dictionary of URL links to nested resources of this schema. + :ivar latest_version_date_created: The date that the latest schema version was created, given in ISO 8601 format. + :ivar latest_version: The latest version published of this schema. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], id: Optional[str] = None + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.latest_version_date_created: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("latest_version_date_created")) + ) + self.latest_version: Optional[int] = deserialize.integer( + payload.get("latest_version") + ) + + self._solution = { + "id": id or self.id, + } + self._context: Optional[SchemaContext] = None + + @property + def _proxy(self) -> "SchemaContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SchemaContext for this SchemaInstance + """ + if self._context is None: + self._context = SchemaContext( + self._version, + id=self._solution["id"], + ) + return self._context + + def fetch(self) -> "SchemaInstance": + """ + Fetch the SchemaInstance + + + :returns: The fetched SchemaInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SchemaInstance": + """ + Asynchronous coroutine to fetch the SchemaInstance + + + :returns: The fetched SchemaInstance + """ + return await self._proxy.fetch_async() + + @property + def versions(self) -> SchemaVersionList: + """ + Access the versions + """ + return self._proxy.versions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Events.V1.SchemaInstance {}>".format(context) + + +class SchemaContext(InstanceContext): + + def __init__(self, version: Version, id: str): + """ + Initialize the SchemaContext + + :param version: Version that contains the resource + :param id: The unique identifier of the schema. Each schema can have multiple versions, that share the same id. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Schemas/{id}".format(**self._solution) + + self._versions: Optional[SchemaVersionList] = None + + def fetch(self) -> SchemaInstance: + """ + Fetch the SchemaInstance + + + :returns: The fetched SchemaInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SchemaInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_async(self) -> SchemaInstance: + """ + Asynchronous coroutine to fetch the SchemaInstance + + + :returns: The fetched SchemaInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SchemaInstance( + self._version, + payload, + id=self._solution["id"], + ) + + @property + def versions(self) -> SchemaVersionList: + """ + Access the versions + """ + if self._versions is None: + self._versions = SchemaVersionList( + self._version, + self._solution["id"], + ) + return self._versions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Events.V1.SchemaContext {}>".format(context) + + +class SchemaList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SchemaList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, id: str) -> SchemaContext: + """ + Constructs a SchemaContext + + :param id: The unique identifier of the schema. Each schema can have multiple versions, that share the same id. + """ + return SchemaContext(self._version, id=id) + + def __call__(self, id: str) -> SchemaContext: + """ + Constructs a SchemaContext + + :param id: The unique identifier of the schema. Each schema can have multiple versions, that share the same id. + """ + return SchemaContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Events.V1.SchemaList>" diff --git a/twilio/rest/events/v1/schema/schema_version.py b/twilio/rest/events/v1/schema/schema_version.py new file mode 100644 index 0000000000..be000b9c0b --- /dev/null +++ b/twilio/rest/events/v1/schema/schema_version.py @@ -0,0 +1,432 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Events + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SchemaVersionInstance(InstanceResource): + """ + :ivar id: The unique identifier of the schema. Each schema can have multiple versions, that share the same id. + :ivar schema_version: The version of this schema. + :ivar date_created: The date the schema version was created, given in ISO 8601 format. + :ivar url: The URL of this resource. + :ivar raw: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + id: str, + schema_version: Optional[int] = None, + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.schema_version: Optional[int] = deserialize.integer( + payload.get("schema_version") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + self.raw: Optional[str] = payload.get("raw") + + self._solution = { + "id": id, + "schema_version": schema_version or self.schema_version, + } + self._context: Optional[SchemaVersionContext] = None + + @property + def _proxy(self) -> "SchemaVersionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SchemaVersionContext for this SchemaVersionInstance + """ + if self._context is None: + self._context = SchemaVersionContext( + self._version, + id=self._solution["id"], + schema_version=self._solution["schema_version"], + ) + return self._context + + def fetch(self) -> "SchemaVersionInstance": + """ + Fetch the SchemaVersionInstance + + + :returns: The fetched SchemaVersionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SchemaVersionInstance": + """ + Asynchronous coroutine to fetch the SchemaVersionInstance + + + :returns: The fetched SchemaVersionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Events.V1.SchemaVersionInstance {}>".format(context) + + +class SchemaVersionContext(InstanceContext): + + def __init__(self, version: Version, id: str, schema_version: int): + """ + Initialize the SchemaVersionContext + + :param version: Version that contains the resource + :param id: The unique identifier of the schema. Each schema can have multiple versions, that share the same id. + :param schema_version: The version of the schema + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + "schema_version": schema_version, + } + self._uri = "/Schemas/{id}/Versions/{schema_version}".format(**self._solution) + + def fetch(self) -> SchemaVersionInstance: + """ + Fetch the SchemaVersionInstance + + + :returns: The fetched SchemaVersionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SchemaVersionInstance( + self._version, + payload, + id=self._solution["id"], + schema_version=self._solution["schema_version"], + ) + + async def fetch_async(self) -> SchemaVersionInstance: + """ + Asynchronous coroutine to fetch the SchemaVersionInstance + + + :returns: The fetched SchemaVersionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SchemaVersionInstance( + self._version, + payload, + id=self._solution["id"], + schema_version=self._solution["schema_version"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Events.V1.SchemaVersionContext {}>".format(context) + + +class SchemaVersionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SchemaVersionInstance: + """ + Build an instance of SchemaVersionInstance + + :param payload: Payload response from the API + """ + return SchemaVersionInstance(self._version, payload, id=self._solution["id"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Events.V1.SchemaVersionPage>" + + +class SchemaVersionList(ListResource): + + def __init__(self, version: Version, id: str): + """ + Initialize the SchemaVersionList + + :param version: Version that contains the resource + :param id: The unique identifier of the schema. Each schema can have multiple versions, that share the same id. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Schemas/{id}/Versions".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SchemaVersionInstance]: + """ + Streams SchemaVersionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SchemaVersionInstance]: + """ + Asynchronously streams SchemaVersionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SchemaVersionInstance]: + """ + Lists SchemaVersionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SchemaVersionInstance]: + """ + Asynchronously lists SchemaVersionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SchemaVersionPage: + """ + Retrieve a single page of SchemaVersionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SchemaVersionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SchemaVersionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SchemaVersionPage: + """ + Asynchronously retrieve a single page of SchemaVersionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SchemaVersionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SchemaVersionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SchemaVersionPage: + """ + Retrieve a specific page of SchemaVersionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SchemaVersionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SchemaVersionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SchemaVersionPage: + """ + Asynchronously retrieve a specific page of SchemaVersionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SchemaVersionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SchemaVersionPage(self._version, response, self._solution) + + def get(self, schema_version: int) -> SchemaVersionContext: + """ + Constructs a SchemaVersionContext + + :param schema_version: The version of the schema + """ + return SchemaVersionContext( + self._version, id=self._solution["id"], schema_version=schema_version + ) + + def __call__(self, schema_version: int) -> SchemaVersionContext: + """ + Constructs a SchemaVersionContext + + :param schema_version: The version of the schema + """ + return SchemaVersionContext( + self._version, id=self._solution["id"], schema_version=schema_version + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Events.V1.SchemaVersionList>" diff --git a/twilio/rest/events/v1/sink/__init__.py b/twilio/rest/events/v1/sink/__init__.py new file mode 100644 index 0000000000..3771f83bbc --- /dev/null +++ b/twilio/rest/events/v1/sink/__init__.py @@ -0,0 +1,703 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Events + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.events.v1.sink.sink_test import SinkTestList +from twilio.rest.events.v1.sink.sink_validate import SinkValidateList + + +class SinkInstance(InstanceResource): + + class SinkType(object): + KINESIS = "kinesis" + WEBHOOK = "webhook" + SEGMENT = "segment" + EMAIL = "email" + + class Status(object): + INITIALIZED = "initialized" + VALIDATING = "validating" + ACTIVE = "active" + FAILED = "failed" + + """ + :ivar date_created: The date that this Sink was created, given in ISO 8601 format. + :ivar date_updated: The date that this Sink was updated, given in ISO 8601 format. + :ivar description: A human readable description for the Sink + :ivar sid: A 34 character string that uniquely identifies this Sink. + :ivar sink_configuration: The information required for Twilio to connect to the provided Sink encoded as JSON. + :ivar sink_type: + :ivar status: + :ivar url: The URL of this resource. + :ivar links: Contains a dictionary of URL links to nested resources of this Sink. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.description: Optional[str] = payload.get("description") + self.sid: Optional[str] = payload.get("sid") + self.sink_configuration: Optional[Dict[str, object]] = payload.get( + "sink_configuration" + ) + self.sink_type: Optional["SinkInstance.SinkType"] = payload.get("sink_type") + self.status: Optional["SinkInstance.Status"] = payload.get("status") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SinkContext] = None + + @property + def _proxy(self) -> "SinkContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SinkContext for this SinkInstance + """ + if self._context is None: + self._context = SinkContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SinkInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SinkInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SinkInstance": + """ + Fetch the SinkInstance + + + :returns: The fetched SinkInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SinkInstance": + """ + Asynchronous coroutine to fetch the SinkInstance + + + :returns: The fetched SinkInstance + """ + return await self._proxy.fetch_async() + + def update(self, description: str) -> "SinkInstance": + """ + Update the SinkInstance + + :param description: A human readable description for the Sink **This value should not contain PII.** + + :returns: The updated SinkInstance + """ + return self._proxy.update( + description=description, + ) + + async def update_async(self, description: str) -> "SinkInstance": + """ + Asynchronous coroutine to update the SinkInstance + + :param description: A human readable description for the Sink **This value should not contain PII.** + + :returns: The updated SinkInstance + """ + return await self._proxy.update_async( + description=description, + ) + + @property + def sink_test(self) -> SinkTestList: + """ + Access the sink_test + """ + return self._proxy.sink_test + + @property + def sink_validate(self) -> SinkValidateList: + """ + Access the sink_validate + """ + return self._proxy.sink_validate + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Events.V1.SinkInstance {}>".format(context) + + +class SinkContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SinkContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this Sink. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Sinks/{sid}".format(**self._solution) + + self._sink_test: Optional[SinkTestList] = None + self._sink_validate: Optional[SinkValidateList] = None + + def delete(self) -> bool: + """ + Deletes the SinkInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SinkInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SinkInstance: + """ + Fetch the SinkInstance + + + :returns: The fetched SinkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SinkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SinkInstance: + """ + Asynchronous coroutine to fetch the SinkInstance + + + :returns: The fetched SinkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SinkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update(self, description: str) -> SinkInstance: + """ + Update the SinkInstance + + :param description: A human readable description for the Sink **This value should not contain PII.** + + :returns: The updated SinkInstance + """ + + data = values.of( + { + "Description": description, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SinkInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async(self, description: str) -> SinkInstance: + """ + Asynchronous coroutine to update the SinkInstance + + :param description: A human readable description for the Sink **This value should not contain PII.** + + :returns: The updated SinkInstance + """ + + data = values.of( + { + "Description": description, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SinkInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def sink_test(self) -> SinkTestList: + """ + Access the sink_test + """ + if self._sink_test is None: + self._sink_test = SinkTestList( + self._version, + self._solution["sid"], + ) + return self._sink_test + + @property + def sink_validate(self) -> SinkValidateList: + """ + Access the sink_validate + """ + if self._sink_validate is None: + self._sink_validate = SinkValidateList( + self._version, + self._solution["sid"], + ) + return self._sink_validate + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Events.V1.SinkContext {}>".format(context) + + +class SinkPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SinkInstance: + """ + Build an instance of SinkInstance + + :param payload: Payload response from the API + """ + return SinkInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Events.V1.SinkPage>" + + +class SinkList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SinkList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Sinks" + + def create( + self, + description: str, + sink_configuration: object, + sink_type: "SinkInstance.SinkType", + ) -> SinkInstance: + """ + Create the SinkInstance + + :param description: A human readable description for the Sink **This value should not contain PII.** + :param sink_configuration: The information required for Twilio to connect to the provided Sink encoded as JSON. + :param sink_type: + + :returns: The created SinkInstance + """ + + data = values.of( + { + "Description": description, + "SinkConfiguration": serialize.object(sink_configuration), + "SinkType": sink_type, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SinkInstance(self._version, payload) + + async def create_async( + self, + description: str, + sink_configuration: object, + sink_type: "SinkInstance.SinkType", + ) -> SinkInstance: + """ + Asynchronously create the SinkInstance + + :param description: A human readable description for the Sink **This value should not contain PII.** + :param sink_configuration: The information required for Twilio to connect to the provided Sink encoded as JSON. + :param sink_type: + + :returns: The created SinkInstance + """ + + data = values.of( + { + "Description": description, + "SinkConfiguration": serialize.object(sink_configuration), + "SinkType": sink_type, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SinkInstance(self._version, payload) + + def stream( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SinkInstance]: + """ + Streams SinkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool in_use: A boolean query parameter filtering the results to return sinks used/not used by a subscription. + :param str status: A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(in_use=in_use, status=status, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SinkInstance]: + """ + Asynchronously streams SinkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool in_use: A boolean query parameter filtering the results to return sinks used/not used by a subscription. + :param str status: A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + in_use=in_use, status=status, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SinkInstance]: + """ + Lists SinkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool in_use: A boolean query parameter filtering the results to return sinks used/not used by a subscription. + :param str status: A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + in_use=in_use, + status=status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SinkInstance]: + """ + Asynchronously lists SinkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool in_use: A boolean query parameter filtering the results to return sinks used/not used by a subscription. + :param str status: A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + in_use=in_use, + status=status, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SinkPage: + """ + Retrieve a single page of SinkInstance records from the API. + Request is executed immediately + + :param in_use: A boolean query parameter filtering the results to return sinks used/not used by a subscription. + :param status: A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SinkInstance + """ + data = values.of( + { + "InUse": serialize.boolean_to_string(in_use), + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SinkPage(self._version, response) + + async def page_async( + self, + in_use: Union[bool, object] = values.unset, + status: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SinkPage: + """ + Asynchronously retrieve a single page of SinkInstance records from the API. + Request is executed immediately + + :param in_use: A boolean query parameter filtering the results to return sinks used/not used by a subscription. + :param status: A String query parameter filtering the results by status `initialized`, `validating`, `active` or `failed`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SinkInstance + """ + data = values.of( + { + "InUse": serialize.boolean_to_string(in_use), + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SinkPage(self._version, response) + + def get_page(self, target_url: str) -> SinkPage: + """ + Retrieve a specific page of SinkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SinkInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SinkPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SinkPage: + """ + Asynchronously retrieve a specific page of SinkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SinkInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SinkPage(self._version, response) + + def get(self, sid: str) -> SinkContext: + """ + Constructs a SinkContext + + :param sid: A 34 character string that uniquely identifies this Sink. + """ + return SinkContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SinkContext: + """ + Constructs a SinkContext + + :param sid: A 34 character string that uniquely identifies this Sink. + """ + return SinkContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Events.V1.SinkList>" diff --git a/twilio/rest/events/v1/sink/sink_test.py b/twilio/rest/events/v1/sink/sink_test.py new file mode 100644 index 0000000000..566106efca --- /dev/null +++ b/twilio/rest/events/v1/sink/sink_test.py @@ -0,0 +1,105 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Events + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SinkTestInstance(InstanceResource): + """ + :ivar result: Feedback indicating whether the test event was generated. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sid: str): + super().__init__(version) + + self.result: Optional[str] = payload.get("result") + + self._solution = { + "sid": sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Events.V1.SinkTestInstance {}>".format(context) + + +class SinkTestList(ListResource): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SinkTestList + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies the Sink to be Tested. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Sinks/{sid}/Test".format(**self._solution) + + def create(self) -> SinkTestInstance: + """ + Create the SinkTestInstance + + + :returns: The created SinkTestInstance + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = self._version.create(method="POST", uri=self._uri, headers=headers) + + return SinkTestInstance(self._version, payload, sid=self._solution["sid"]) + + async def create_async(self) -> SinkTestInstance: + """ + Asynchronously create the SinkTestInstance + + + :returns: The created SinkTestInstance + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, headers=headers + ) + + return SinkTestInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Events.V1.SinkTestList>" diff --git a/twilio/rest/events/v1/sink/sink_validate.py b/twilio/rest/events/v1/sink/sink_validate.py new file mode 100644 index 0000000000..53eef814c0 --- /dev/null +++ b/twilio/rest/events/v1/sink/sink_validate.py @@ -0,0 +1,123 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Events + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SinkValidateInstance(InstanceResource): + """ + :ivar result: Feedback indicating whether the given Sink was validated. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sid: str): + super().__init__(version) + + self.result: Optional[str] = payload.get("result") + + self._solution = { + "sid": sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Events.V1.SinkValidateInstance {}>".format(context) + + +class SinkValidateList(ListResource): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SinkValidateList + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies the Sink being validated. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Sinks/{sid}/Validate".format(**self._solution) + + def create(self, test_id: str) -> SinkValidateInstance: + """ + Create the SinkValidateInstance + + :param test_id: A 34 character string that uniquely identifies the test event for a Sink being validated. + + :returns: The created SinkValidateInstance + """ + + data = values.of( + { + "TestId": test_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SinkValidateInstance(self._version, payload, sid=self._solution["sid"]) + + async def create_async(self, test_id: str) -> SinkValidateInstance: + """ + Asynchronously create the SinkValidateInstance + + :param test_id: A 34 character string that uniquely identifies the test event for a Sink being validated. + + :returns: The created SinkValidateInstance + """ + + data = values.of( + { + "TestId": test_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SinkValidateInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Events.V1.SinkValidateList>" diff --git a/twilio/rest/events/v1/subscription/__init__.py b/twilio/rest/events/v1/subscription/__init__.py new file mode 100644 index 0000000000..872c9ed7d0 --- /dev/null +++ b/twilio/rest/events/v1/subscription/__init__.py @@ -0,0 +1,665 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Events + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.events.v1.subscription.subscribed_event import SubscribedEventList + + +class SubscriptionInstance(InstanceResource): + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar sid: A 34 character string that uniquely identifies this Subscription. + :ivar date_created: The date that this Subscription was created, given in ISO 8601 format. + :ivar date_updated: The date that this Subscription was updated, given in ISO 8601 format. + :ivar description: A human readable description for the Subscription + :ivar sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + :ivar url: The URL of this resource. + :ivar links: Contains a dictionary of URL links to nested resources of this Subscription. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.description: Optional[str] = payload.get("description") + self.sink_sid: Optional[str] = payload.get("sink_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SubscriptionContext] = None + + @property + def _proxy(self) -> "SubscriptionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SubscriptionContext for this SubscriptionInstance + """ + if self._context is None: + self._context = SubscriptionContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SubscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SubscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SubscriptionInstance": + """ + Fetch the SubscriptionInstance + + + :returns: The fetched SubscriptionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SubscriptionInstance": + """ + Asynchronous coroutine to fetch the SubscriptionInstance + + + :returns: The fetched SubscriptionInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + description: Union[str, object] = values.unset, + sink_sid: Union[str, object] = values.unset, + ) -> "SubscriptionInstance": + """ + Update the SubscriptionInstance + + :param description: A human readable description for the Subscription. + :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + + :returns: The updated SubscriptionInstance + """ + return self._proxy.update( + description=description, + sink_sid=sink_sid, + ) + + async def update_async( + self, + description: Union[str, object] = values.unset, + sink_sid: Union[str, object] = values.unset, + ) -> "SubscriptionInstance": + """ + Asynchronous coroutine to update the SubscriptionInstance + + :param description: A human readable description for the Subscription. + :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + + :returns: The updated SubscriptionInstance + """ + return await self._proxy.update_async( + description=description, + sink_sid=sink_sid, + ) + + @property + def subscribed_events(self) -> SubscribedEventList: + """ + Access the subscribed_events + """ + return self._proxy.subscribed_events + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Events.V1.SubscriptionInstance {}>".format(context) + + +class SubscriptionContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SubscriptionContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this Subscription. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Subscriptions/{sid}".format(**self._solution) + + self._subscribed_events: Optional[SubscribedEventList] = None + + def delete(self) -> bool: + """ + Deletes the SubscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SubscriptionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SubscriptionInstance: + """ + Fetch the SubscriptionInstance + + + :returns: The fetched SubscriptionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SubscriptionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SubscriptionInstance: + """ + Asynchronous coroutine to fetch the SubscriptionInstance + + + :returns: The fetched SubscriptionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SubscriptionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + description: Union[str, object] = values.unset, + sink_sid: Union[str, object] = values.unset, + ) -> SubscriptionInstance: + """ + Update the SubscriptionInstance + + :param description: A human readable description for the Subscription. + :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + + :returns: The updated SubscriptionInstance + """ + + data = values.of( + { + "Description": description, + "SinkSid": sink_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SubscriptionInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + description: Union[str, object] = values.unset, + sink_sid: Union[str, object] = values.unset, + ) -> SubscriptionInstance: + """ + Asynchronous coroutine to update the SubscriptionInstance + + :param description: A human readable description for the Subscription. + :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + + :returns: The updated SubscriptionInstance + """ + + data = values.of( + { + "Description": description, + "SinkSid": sink_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SubscriptionInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def subscribed_events(self) -> SubscribedEventList: + """ + Access the subscribed_events + """ + if self._subscribed_events is None: + self._subscribed_events = SubscribedEventList( + self._version, + self._solution["sid"], + ) + return self._subscribed_events + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Events.V1.SubscriptionContext {}>".format(context) + + +class SubscriptionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SubscriptionInstance: + """ + Build an instance of SubscriptionInstance + + :param payload: Payload response from the API + """ + return SubscriptionInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Events.V1.SubscriptionPage>" + + +class SubscriptionList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SubscriptionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Subscriptions" + + def create( + self, description: str, sink_sid: str, types: List[object] + ) -> SubscriptionInstance: + """ + Create the SubscriptionInstance + + :param description: A human readable description for the Subscription **This value should not contain PII.** + :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + :param types: An array of objects containing the subscribed Event Types + + :returns: The created SubscriptionInstance + """ + + data = values.of( + { + "Description": description, + "SinkSid": sink_sid, + "Types": serialize.map(types, lambda e: serialize.object(e)), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SubscriptionInstance(self._version, payload) + + async def create_async( + self, description: str, sink_sid: str, types: List[object] + ) -> SubscriptionInstance: + """ + Asynchronously create the SubscriptionInstance + + :param description: A human readable description for the Subscription **This value should not contain PII.** + :param sink_sid: The SID of the sink that events selected by this subscription should be sent to. Sink must be active for the subscription to be created. + :param types: An array of objects containing the subscribed Event Types + + :returns: The created SubscriptionInstance + """ + + data = values.of( + { + "Description": description, + "SinkSid": sink_sid, + "Types": serialize.map(types, lambda e: serialize.object(e)), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SubscriptionInstance(self._version, payload) + + def stream( + self, + sink_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SubscriptionInstance]: + """ + Streams SubscriptionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sink_sid: The SID of the sink that the list of Subscriptions should be filtered by. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(sink_sid=sink_sid, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + sink_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SubscriptionInstance]: + """ + Asynchronously streams SubscriptionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sink_sid: The SID of the sink that the list of Subscriptions should be filtered by. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(sink_sid=sink_sid, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + sink_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SubscriptionInstance]: + """ + Lists SubscriptionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sink_sid: The SID of the sink that the list of Subscriptions should be filtered by. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + sink_sid=sink_sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + sink_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SubscriptionInstance]: + """ + Asynchronously lists SubscriptionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sink_sid: The SID of the sink that the list of Subscriptions should be filtered by. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + sink_sid=sink_sid, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + sink_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SubscriptionPage: + """ + Retrieve a single page of SubscriptionInstance records from the API. + Request is executed immediately + + :param sink_sid: The SID of the sink that the list of Subscriptions should be filtered by. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SubscriptionInstance + """ + data = values.of( + { + "SinkSid": sink_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SubscriptionPage(self._version, response) + + async def page_async( + self, + sink_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SubscriptionPage: + """ + Asynchronously retrieve a single page of SubscriptionInstance records from the API. + Request is executed immediately + + :param sink_sid: The SID of the sink that the list of Subscriptions should be filtered by. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SubscriptionInstance + """ + data = values.of( + { + "SinkSid": sink_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SubscriptionPage(self._version, response) + + def get_page(self, target_url: str) -> SubscriptionPage: + """ + Retrieve a specific page of SubscriptionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SubscriptionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SubscriptionPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SubscriptionPage: + """ + Asynchronously retrieve a specific page of SubscriptionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SubscriptionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SubscriptionPage(self._version, response) + + def get(self, sid: str) -> SubscriptionContext: + """ + Constructs a SubscriptionContext + + :param sid: A 34 character string that uniquely identifies this Subscription. + """ + return SubscriptionContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SubscriptionContext: + """ + Constructs a SubscriptionContext + + :param sid: A 34 character string that uniquely identifies this Subscription. + """ + return SubscriptionContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Events.V1.SubscriptionList>" diff --git a/twilio/rest/events/v1/subscription/subscribed_event.py b/twilio/rest/events/v1/subscription/subscribed_event.py new file mode 100644 index 0000000000..dae60ac206 --- /dev/null +++ b/twilio/rest/events/v1/subscription/subscribed_event.py @@ -0,0 +1,641 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Events + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SubscribedEventInstance(InstanceResource): + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar type: Type of event being subscribed to. + :ivar schema_version: The schema version that the Subscription should use. + :ivar subscription_sid: The unique SID identifier of the Subscription. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + subscription_sid: str, + type: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.type: Optional[str] = payload.get("type") + self.schema_version: Optional[int] = deserialize.integer( + payload.get("schema_version") + ) + self.subscription_sid: Optional[str] = payload.get("subscription_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "subscription_sid": subscription_sid, + "type": type or self.type, + } + self._context: Optional[SubscribedEventContext] = None + + @property + def _proxy(self) -> "SubscribedEventContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SubscribedEventContext for this SubscribedEventInstance + """ + if self._context is None: + self._context = SubscribedEventContext( + self._version, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SubscribedEventInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SubscribedEventInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SubscribedEventInstance": + """ + Fetch the SubscribedEventInstance + + + :returns: The fetched SubscribedEventInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SubscribedEventInstance": + """ + Asynchronous coroutine to fetch the SubscribedEventInstance + + + :returns: The fetched SubscribedEventInstance + """ + return await self._proxy.fetch_async() + + def update( + self, schema_version: Union[int, object] = values.unset + ) -> "SubscribedEventInstance": + """ + Update the SubscribedEventInstance + + :param schema_version: The schema version that the Subscription should use. + + :returns: The updated SubscribedEventInstance + """ + return self._proxy.update( + schema_version=schema_version, + ) + + async def update_async( + self, schema_version: Union[int, object] = values.unset + ) -> "SubscribedEventInstance": + """ + Asynchronous coroutine to update the SubscribedEventInstance + + :param schema_version: The schema version that the Subscription should use. + + :returns: The updated SubscribedEventInstance + """ + return await self._proxy.update_async( + schema_version=schema_version, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Events.V1.SubscribedEventInstance {}>".format(context) + + +class SubscribedEventContext(InstanceContext): + + def __init__(self, version: Version, subscription_sid: str, type: str): + """ + Initialize the SubscribedEventContext + + :param version: Version that contains the resource + :param subscription_sid: The unique SID identifier of the Subscription. + :param type: Type of event being subscribed to. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "subscription_sid": subscription_sid, + "type": type, + } + self._uri = "/Subscriptions/{subscription_sid}/SubscribedEvents/{type}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the SubscribedEventInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SubscribedEventInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SubscribedEventInstance: + """ + Fetch the SubscribedEventInstance + + + :returns: The fetched SubscribedEventInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + + async def fetch_async(self) -> SubscribedEventInstance: + """ + Asynchronous coroutine to fetch the SubscribedEventInstance + + + :returns: The fetched SubscribedEventInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + + def update( + self, schema_version: Union[int, object] = values.unset + ) -> SubscribedEventInstance: + """ + Update the SubscribedEventInstance + + :param schema_version: The schema version that the Subscription should use. + + :returns: The updated SubscribedEventInstance + """ + + data = values.of( + { + "SchemaVersion": schema_version, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + + async def update_async( + self, schema_version: Union[int, object] = values.unset + ) -> SubscribedEventInstance: + """ + Asynchronous coroutine to update the SubscribedEventInstance + + :param schema_version: The schema version that the Subscription should use. + + :returns: The updated SubscribedEventInstance + """ + + data = values.of( + { + "SchemaVersion": schema_version, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Events.V1.SubscribedEventContext {}>".format(context) + + +class SubscribedEventPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SubscribedEventInstance: + """ + Build an instance of SubscribedEventInstance + + :param payload: Payload response from the API + """ + return SubscribedEventInstance( + self._version, payload, subscription_sid=self._solution["subscription_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Events.V1.SubscribedEventPage>" + + +class SubscribedEventList(ListResource): + + def __init__(self, version: Version, subscription_sid: str): + """ + Initialize the SubscribedEventList + + :param version: Version that contains the resource + :param subscription_sid: The unique SID identifier of the Subscription. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "subscription_sid": subscription_sid, + } + self._uri = "/Subscriptions/{subscription_sid}/SubscribedEvents".format( + **self._solution + ) + + def create( + self, type: str, schema_version: Union[int, object] = values.unset + ) -> SubscribedEventInstance: + """ + Create the SubscribedEventInstance + + :param type: Type of event being subscribed to. + :param schema_version: The schema version that the Subscription should use. + + :returns: The created SubscribedEventInstance + """ + + data = values.of( + { + "Type": type, + "SchemaVersion": schema_version, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SubscribedEventInstance( + self._version, payload, subscription_sid=self._solution["subscription_sid"] + ) + + async def create_async( + self, type: str, schema_version: Union[int, object] = values.unset + ) -> SubscribedEventInstance: + """ + Asynchronously create the SubscribedEventInstance + + :param type: Type of event being subscribed to. + :param schema_version: The schema version that the Subscription should use. + + :returns: The created SubscribedEventInstance + """ + + data = values.of( + { + "Type": type, + "SchemaVersion": schema_version, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SubscribedEventInstance( + self._version, payload, subscription_sid=self._solution["subscription_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SubscribedEventInstance]: + """ + Streams SubscribedEventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SubscribedEventInstance]: + """ + Asynchronously streams SubscribedEventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SubscribedEventInstance]: + """ + Lists SubscribedEventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SubscribedEventInstance]: + """ + Asynchronously lists SubscribedEventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SubscribedEventPage: + """ + Retrieve a single page of SubscribedEventInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SubscribedEventInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SubscribedEventPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SubscribedEventPage: + """ + Asynchronously retrieve a single page of SubscribedEventInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SubscribedEventInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SubscribedEventPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SubscribedEventPage: + """ + Retrieve a specific page of SubscribedEventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SubscribedEventInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SubscribedEventPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SubscribedEventPage: + """ + Asynchronously retrieve a specific page of SubscribedEventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SubscribedEventInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SubscribedEventPage(self._version, response, self._solution) + + def get(self, type: str) -> SubscribedEventContext: + """ + Constructs a SubscribedEventContext + + :param type: Type of event being subscribed to. + """ + return SubscribedEventContext( + self._version, + subscription_sid=self._solution["subscription_sid"], + type=type, + ) + + def __call__(self, type: str) -> SubscribedEventContext: + """ + Constructs a SubscribedEventContext + + :param type: Type of event being subscribed to. + """ + return SubscribedEventContext( + self._version, + subscription_sid=self._solution["subscription_sid"], + type=type, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Events.V1.SubscribedEventList>" diff --git a/twilio/rest/flex_api/FlexApiBase.py b/twilio/rest/flex_api/FlexApiBase.py new file mode 100644 index 0000000000..3bda5b6b47 --- /dev/null +++ b/twilio/rest/flex_api/FlexApiBase.py @@ -0,0 +1,55 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.flex_api.v1 import V1 +from twilio.rest.flex_api.v2 import V2 + + +class FlexApiBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the FlexApi Domain + + :returns: Domain for FlexApi + """ + super().__init__(twilio, "https://flex-api.twilio.com") + self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of FlexApi + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of FlexApi + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi>" diff --git a/twilio/rest/flex_api/__init__.py b/twilio/rest/flex_api/__init__.py new file mode 100644 index 0000000000..8f679516c1 --- /dev/null +++ b/twilio/rest/flex_api/__init__.py @@ -0,0 +1,185 @@ +from warnings import warn + +from twilio.rest.flex_api.FlexApiBase import FlexApiBase +from twilio.rest.flex_api.v1.assessments import AssessmentsList +from twilio.rest.flex_api.v1.channel import ChannelList +from twilio.rest.flex_api.v1.configuration import ConfigurationList +from twilio.rest.flex_api.v1.flex_flow import FlexFlowList +from twilio.rest.flex_api.v1.insights_assessments_comment import ( + InsightsAssessmentsCommentList, +) +from twilio.rest.flex_api.v1.insights_conversations import InsightsConversationsList +from twilio.rest.flex_api.v1.insights_questionnaires import InsightsQuestionnairesList +from twilio.rest.flex_api.v1.insights_questionnaires_category import ( + InsightsQuestionnairesCategoryList, +) +from twilio.rest.flex_api.v1.insights_questionnaires_question import ( + InsightsQuestionnairesQuestionList, +) +from twilio.rest.flex_api.v1.insights_segments import InsightsSegmentsList +from twilio.rest.flex_api.v1.insights_session import InsightsSessionList +from twilio.rest.flex_api.v1.insights_settings_answer_sets import ( + InsightsSettingsAnswerSetsList, +) +from twilio.rest.flex_api.v1.insights_settings_comment import ( + InsightsSettingsCommentList, +) +from twilio.rest.flex_api.v1.insights_user_roles import InsightsUserRolesList +from twilio.rest.flex_api.v1.interaction import InteractionList +from twilio.rest.flex_api.v1.web_channel import WebChannelList +from twilio.rest.flex_api.v2.web_channels import WebChannelsList + + +class FlexApi(FlexApiBase): + @property + def assessments(self) -> AssessmentsList: + warn( + "assessments is deprecated. Use v1.assessments instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.assessments + + @property + def channel(self) -> ChannelList: + warn( + "channel is deprecated. Use v1.channel instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.channel + + @property + def configuration(self) -> ConfigurationList: + warn( + "configuration is deprecated. Use v1.configuration instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.configuration + + @property + def flex_flow(self) -> FlexFlowList: + warn( + "flex_flow is deprecated. Use v1.flex_flow instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.flex_flow + + @property + def insights_assessments_comment(self) -> InsightsAssessmentsCommentList: + warn( + "insights_assessments_comment is deprecated. Use v1.insights_assessments_comment instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_assessments_comment + + @property + def insights_conversations(self) -> InsightsConversationsList: + warn( + "insights_conversations is deprecated. Use v1.insights_conversations instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_conversations + + @property + def insights_questionnaires(self) -> InsightsQuestionnairesList: + warn( + "insights_questionnaires is deprecated. Use v1.insights_questionnaires instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_questionnaires + + @property + def insights_questionnaires_category(self) -> InsightsQuestionnairesCategoryList: + warn( + "insights_questionnaires_category is deprecated. Use v1.insights_questionnaires_category instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_questionnaires_category + + @property + def insights_questionnaires_question(self) -> InsightsQuestionnairesQuestionList: + warn( + "insights_questionnaires_question is deprecated. Use v1.insights_questionnaires_question instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_questionnaires_question + + @property + def insights_segments(self) -> InsightsSegmentsList: + warn( + "insights_segments is deprecated. Use v1.insights_segments instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_segments + + @property + def insights_session(self) -> InsightsSessionList: + warn( + "insights_session is deprecated. Use v1.insights_session instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_session + + @property + def insights_settings_answer_sets(self) -> InsightsSettingsAnswerSetsList: + warn( + "insights_settings_answer_sets is deprecated. Use v1.insights_settings_answer_sets instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_settings_answer_sets + + @property + def insights_settings_comment(self) -> InsightsSettingsCommentList: + warn( + "insights_settings_comment is deprecated. Use v1.insights_settings_comment instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_settings_comment + + @property + def insights_user_roles(self) -> InsightsUserRolesList: + warn( + "insights_user_roles is deprecated. Use v1.insights_user_roles instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.insights_user_roles + + @property + def interaction(self) -> InteractionList: + warn( + "interaction is deprecated. Use v1.interaction instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.interaction + + @property + def web_channel(self) -> WebChannelList: + warn( + "web_channel is deprecated. Use v1.web_channel instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.web_channel + + @property + def web_channels(self) -> WebChannelsList: + warn( + "web_channels is deprecated. Use v2.web_channels instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.web_channels diff --git a/twilio/rest/flex_api/v1/__init__.py b/twilio/rest/flex_api/v1/__init__.py new file mode 100644 index 0000000000..eeb00227e9 --- /dev/null +++ b/twilio/rest/flex_api/v1/__init__.py @@ -0,0 +1,245 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.flex_api.v1.assessments import AssessmentsList +from twilio.rest.flex_api.v1.channel import ChannelList +from twilio.rest.flex_api.v1.configuration import ConfigurationList +from twilio.rest.flex_api.v1.flex_flow import FlexFlowList +from twilio.rest.flex_api.v1.insights_assessments_comment import ( + InsightsAssessmentsCommentList, +) +from twilio.rest.flex_api.v1.insights_conversations import InsightsConversationsList +from twilio.rest.flex_api.v1.insights_questionnaires import InsightsQuestionnairesList +from twilio.rest.flex_api.v1.insights_questionnaires_category import ( + InsightsQuestionnairesCategoryList, +) +from twilio.rest.flex_api.v1.insights_questionnaires_question import ( + InsightsQuestionnairesQuestionList, +) +from twilio.rest.flex_api.v1.insights_segments import InsightsSegmentsList +from twilio.rest.flex_api.v1.insights_session import InsightsSessionList +from twilio.rest.flex_api.v1.insights_settings_answer_sets import ( + InsightsSettingsAnswerSetsList, +) +from twilio.rest.flex_api.v1.insights_settings_comment import ( + InsightsSettingsCommentList, +) +from twilio.rest.flex_api.v1.insights_user_roles import InsightsUserRolesList +from twilio.rest.flex_api.v1.interaction import InteractionList +from twilio.rest.flex_api.v1.plugin import PluginList +from twilio.rest.flex_api.v1.plugin_archive import PluginArchiveList +from twilio.rest.flex_api.v1.plugin_configuration import PluginConfigurationList +from twilio.rest.flex_api.v1.plugin_configuration_archive import ( + PluginConfigurationArchiveList, +) +from twilio.rest.flex_api.v1.plugin_release import PluginReleaseList +from twilio.rest.flex_api.v1.plugin_version_archive import PluginVersionArchiveList +from twilio.rest.flex_api.v1.provisioning_status import ProvisioningStatusList +from twilio.rest.flex_api.v1.web_channel import WebChannelList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of FlexApi + + :param domain: The Twilio.flex_api domain + """ + super().__init__(domain, "v1") + self._assessments: Optional[AssessmentsList] = None + self._channel: Optional[ChannelList] = None + self._configuration: Optional[ConfigurationList] = None + self._flex_flow: Optional[FlexFlowList] = None + self._insights_assessments_comment: Optional[InsightsAssessmentsCommentList] = ( + None + ) + self._insights_conversations: Optional[InsightsConversationsList] = None + self._insights_questionnaires: Optional[InsightsQuestionnairesList] = None + self._insights_questionnaires_category: Optional[ + InsightsQuestionnairesCategoryList + ] = None + self._insights_questionnaires_question: Optional[ + InsightsQuestionnairesQuestionList + ] = None + self._insights_segments: Optional[InsightsSegmentsList] = None + self._insights_session: Optional[InsightsSessionList] = None + self._insights_settings_answer_sets: Optional[ + InsightsSettingsAnswerSetsList + ] = None + self._insights_settings_comment: Optional[InsightsSettingsCommentList] = None + self._insights_user_roles: Optional[InsightsUserRolesList] = None + self._interaction: Optional[InteractionList] = None + self._plugins: Optional[PluginList] = None + self._plugin_archive: Optional[PluginArchiveList] = None + self._plugin_configurations: Optional[PluginConfigurationList] = None + self._plugin_configuration_archive: Optional[PluginConfigurationArchiveList] = ( + None + ) + self._plugin_releases: Optional[PluginReleaseList] = None + self._plugin_version_archive: Optional[PluginVersionArchiveList] = None + self._provisioning_status: Optional[ProvisioningStatusList] = None + self._web_channel: Optional[WebChannelList] = None + + @property + def assessments(self) -> AssessmentsList: + if self._assessments is None: + self._assessments = AssessmentsList(self) + return self._assessments + + @property + def channel(self) -> ChannelList: + if self._channel is None: + self._channel = ChannelList(self) + return self._channel + + @property + def configuration(self) -> ConfigurationList: + if self._configuration is None: + self._configuration = ConfigurationList(self) + return self._configuration + + @property + def flex_flow(self) -> FlexFlowList: + if self._flex_flow is None: + self._flex_flow = FlexFlowList(self) + return self._flex_flow + + @property + def insights_assessments_comment(self) -> InsightsAssessmentsCommentList: + if self._insights_assessments_comment is None: + self._insights_assessments_comment = InsightsAssessmentsCommentList(self) + return self._insights_assessments_comment + + @property + def insights_conversations(self) -> InsightsConversationsList: + if self._insights_conversations is None: + self._insights_conversations = InsightsConversationsList(self) + return self._insights_conversations + + @property + def insights_questionnaires(self) -> InsightsQuestionnairesList: + if self._insights_questionnaires is None: + self._insights_questionnaires = InsightsQuestionnairesList(self) + return self._insights_questionnaires + + @property + def insights_questionnaires_category(self) -> InsightsQuestionnairesCategoryList: + if self._insights_questionnaires_category is None: + self._insights_questionnaires_category = InsightsQuestionnairesCategoryList( + self + ) + return self._insights_questionnaires_category + + @property + def insights_questionnaires_question(self) -> InsightsQuestionnairesQuestionList: + if self._insights_questionnaires_question is None: + self._insights_questionnaires_question = InsightsQuestionnairesQuestionList( + self + ) + return self._insights_questionnaires_question + + @property + def insights_segments(self) -> InsightsSegmentsList: + if self._insights_segments is None: + self._insights_segments = InsightsSegmentsList(self) + return self._insights_segments + + @property + def insights_session(self) -> InsightsSessionList: + if self._insights_session is None: + self._insights_session = InsightsSessionList(self) + return self._insights_session + + @property + def insights_settings_answer_sets(self) -> InsightsSettingsAnswerSetsList: + if self._insights_settings_answer_sets is None: + self._insights_settings_answer_sets = InsightsSettingsAnswerSetsList(self) + return self._insights_settings_answer_sets + + @property + def insights_settings_comment(self) -> InsightsSettingsCommentList: + if self._insights_settings_comment is None: + self._insights_settings_comment = InsightsSettingsCommentList(self) + return self._insights_settings_comment + + @property + def insights_user_roles(self) -> InsightsUserRolesList: + if self._insights_user_roles is None: + self._insights_user_roles = InsightsUserRolesList(self) + return self._insights_user_roles + + @property + def interaction(self) -> InteractionList: + if self._interaction is None: + self._interaction = InteractionList(self) + return self._interaction + + @property + def plugins(self) -> PluginList: + if self._plugins is None: + self._plugins = PluginList(self) + return self._plugins + + @property + def plugin_archive(self) -> PluginArchiveList: + if self._plugin_archive is None: + self._plugin_archive = PluginArchiveList(self) + return self._plugin_archive + + @property + def plugin_configurations(self) -> PluginConfigurationList: + if self._plugin_configurations is None: + self._plugin_configurations = PluginConfigurationList(self) + return self._plugin_configurations + + @property + def plugin_configuration_archive(self) -> PluginConfigurationArchiveList: + if self._plugin_configuration_archive is None: + self._plugin_configuration_archive = PluginConfigurationArchiveList(self) + return self._plugin_configuration_archive + + @property + def plugin_releases(self) -> PluginReleaseList: + if self._plugin_releases is None: + self._plugin_releases = PluginReleaseList(self) + return self._plugin_releases + + @property + def plugin_version_archive(self) -> PluginVersionArchiveList: + if self._plugin_version_archive is None: + self._plugin_version_archive = PluginVersionArchiveList(self) + return self._plugin_version_archive + + @property + def provisioning_status(self) -> ProvisioningStatusList: + if self._provisioning_status is None: + self._provisioning_status = ProvisioningStatusList(self) + return self._provisioning_status + + @property + def web_channel(self) -> WebChannelList: + if self._web_channel is None: + self._web_channel = WebChannelList(self) + return self._web_channel + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1>" diff --git a/twilio/rest/flex_api/v1/assessments.py b/twilio/rest/flex_api/v1/assessments.py new file mode 100644 index 0000000000..130514b295 --- /dev/null +++ b/twilio/rest/flex_api/v1/assessments.py @@ -0,0 +1,685 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AssessmentsInstance(InstanceResource): + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar assessment_sid: The SID of the assessment + :ivar offset: Offset of the conversation + :ivar report: The flag indicating if this assessment is part of report + :ivar weight: The weightage given to this comment + :ivar agent_id: The id of the Agent + :ivar segment_id: Segment Id of conversation + :ivar user_name: The name of the user. + :ivar user_email: The email id of the user. + :ivar answer_text: The answer text selected by user + :ivar answer_id: The id of the answer selected by user + :ivar assessment: Assessment Details associated with an assessment + :ivar timestamp: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + assessment_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.assessment_sid: Optional[str] = payload.get("assessment_sid") + self.offset: Optional[float] = deserialize.decimal(payload.get("offset")) + self.report: Optional[bool] = payload.get("report") + self.weight: Optional[float] = deserialize.decimal(payload.get("weight")) + self.agent_id: Optional[str] = payload.get("agent_id") + self.segment_id: Optional[str] = payload.get("segment_id") + self.user_name: Optional[str] = payload.get("user_name") + self.user_email: Optional[str] = payload.get("user_email") + self.answer_text: Optional[str] = payload.get("answer_text") + self.answer_id: Optional[str] = payload.get("answer_id") + self.assessment: Optional[Dict[str, object]] = payload.get("assessment") + self.timestamp: Optional[float] = deserialize.decimal(payload.get("timestamp")) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "assessment_sid": assessment_sid or self.assessment_sid, + } + self._context: Optional[AssessmentsContext] = None + + @property + def _proxy(self) -> "AssessmentsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AssessmentsContext for this AssessmentsInstance + """ + if self._context is None: + self._context = AssessmentsContext( + self._version, + assessment_sid=self._solution["assessment_sid"], + ) + return self._context + + def update( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> "AssessmentsInstance": + """ + Update the AssessmentsInstance + + :param offset: The offset of the conversation + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param authorization: The Authorization HTTP request header + + :returns: The updated AssessmentsInstance + """ + return self._proxy.update( + offset=offset, + answer_text=answer_text, + answer_id=answer_id, + authorization=authorization, + ) + + async def update_async( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> "AssessmentsInstance": + """ + Asynchronous coroutine to update the AssessmentsInstance + + :param offset: The offset of the conversation + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param authorization: The Authorization HTTP request header + + :returns: The updated AssessmentsInstance + """ + return await self._proxy.update_async( + offset=offset, + answer_text=answer_text, + answer_id=answer_id, + authorization=authorization, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.AssessmentsInstance {}>".format(context) + + +class AssessmentsContext(InstanceContext): + + def __init__(self, version: Version, assessment_sid: str): + """ + Initialize the AssessmentsContext + + :param version: Version that contains the resource + :param assessment_sid: The SID of the assessment to be modified + """ + super().__init__(version) + + # Path Solution + self._solution = { + "assessment_sid": assessment_sid, + } + self._uri = "/Insights/QualityManagement/Assessments/{assessment_sid}".format( + **self._solution + ) + + def update( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> AssessmentsInstance: + """ + Update the AssessmentsInstance + + :param offset: The offset of the conversation + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param authorization: The Authorization HTTP request header + + :returns: The updated AssessmentsInstance + """ + + data = values.of( + { + "Offset": offset, + "AnswerText": answer_text, + "AnswerId": answer_id, + } + ) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssessmentsInstance( + self._version, payload, assessment_sid=self._solution["assessment_sid"] + ) + + async def update_async( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> AssessmentsInstance: + """ + Asynchronous coroutine to update the AssessmentsInstance + + :param offset: The offset of the conversation + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param authorization: The Authorization HTTP request header + + :returns: The updated AssessmentsInstance + """ + + data = values.of( + { + "Offset": offset, + "AnswerText": answer_text, + "AnswerId": answer_id, + } + ) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssessmentsInstance( + self._version, payload, assessment_sid=self._solution["assessment_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.AssessmentsContext {}>".format(context) + + +class AssessmentsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AssessmentsInstance: + """ + Build an instance of AssessmentsInstance + + :param payload: Payload response from the API + """ + return AssessmentsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.AssessmentsPage>" + + +class AssessmentsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AssessmentsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Insights/QualityManagement/Assessments" + + def create( + self, + category_sid: str, + category_name: str, + segment_id: str, + agent_id: str, + offset: float, + metric_id: str, + metric_name: str, + answer_text: str, + answer_id: str, + questionnaire_sid: str, + authorization: Union[str, object] = values.unset, + ) -> AssessmentsInstance: + """ + Create the AssessmentsInstance + + :param category_sid: The SID of the category + :param category_name: The name of the category + :param segment_id: Segment Id of the conversation + :param agent_id: The id of the Agent + :param offset: The offset of the conversation. + :param metric_id: The question SID selected for assessment + :param metric_name: The question name of the assessment + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param questionnaire_sid: Questionnaire SID of the associated question + :param authorization: The Authorization HTTP request header + + :returns: The created AssessmentsInstance + """ + + data = values.of( + { + "CategorySid": category_sid, + "CategoryName": category_name, + "SegmentId": segment_id, + "AgentId": agent_id, + "Offset": offset, + "MetricId": metric_id, + "MetricName": metric_name, + "AnswerText": answer_text, + "AnswerId": answer_id, + "QuestionnaireSid": questionnaire_sid, + } + ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssessmentsInstance(self._version, payload) + + async def create_async( + self, + category_sid: str, + category_name: str, + segment_id: str, + agent_id: str, + offset: float, + metric_id: str, + metric_name: str, + answer_text: str, + answer_id: str, + questionnaire_sid: str, + authorization: Union[str, object] = values.unset, + ) -> AssessmentsInstance: + """ + Asynchronously create the AssessmentsInstance + + :param category_sid: The SID of the category + :param category_name: The name of the category + :param segment_id: Segment Id of the conversation + :param agent_id: The id of the Agent + :param offset: The offset of the conversation. + :param metric_id: The question SID selected for assessment + :param metric_name: The question name of the assessment + :param answer_text: The answer text selected by user + :param answer_id: The id of the answer selected by user + :param questionnaire_sid: Questionnaire SID of the associated question + :param authorization: The Authorization HTTP request header + + :returns: The created AssessmentsInstance + """ + + data = values.of( + { + "CategorySid": category_sid, + "CategoryName": category_name, + "SegmentId": segment_id, + "AgentId": agent_id, + "Offset": offset, + "MetricId": metric_id, + "MetricName": metric_name, + "AnswerText": answer_text, + "AnswerId": answer_id, + "QuestionnaireSid": questionnaire_sid, + } + ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssessmentsInstance(self._version, payload) + + def stream( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssessmentsInstance]: + """ + Streams AssessmentsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AssessmentsInstance]: + """ + Asynchronously streams AssessmentsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssessmentsInstance]: + """ + Lists AssessmentsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + authorization=authorization, + segment_id=segment_id, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssessmentsInstance]: + """ + Asynchronously lists AssessmentsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + authorization=authorization, + segment_id=segment_id, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssessmentsPage: + """ + Retrieve a single page of AssessmentsInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param segment_id: The id of the segment. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssessmentsInstance + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssessmentsPage(self._version, response) + + async def page_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssessmentsPage: + """ + Asynchronously retrieve a single page of AssessmentsInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param segment_id: The id of the segment. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssessmentsInstance + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssessmentsPage(self._version, response) + + def get_page(self, target_url: str) -> AssessmentsPage: + """ + Retrieve a specific page of AssessmentsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssessmentsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AssessmentsPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AssessmentsPage: + """ + Asynchronously retrieve a specific page of AssessmentsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssessmentsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssessmentsPage(self._version, response) + + def get(self, assessment_sid: str) -> AssessmentsContext: + """ + Constructs a AssessmentsContext + + :param assessment_sid: The SID of the assessment to be modified + """ + return AssessmentsContext(self._version, assessment_sid=assessment_sid) + + def __call__(self, assessment_sid: str) -> AssessmentsContext: + """ + Constructs a AssessmentsContext + + :param assessment_sid: The SID of the assessment to be modified + """ + return AssessmentsContext(self._version, assessment_sid=assessment_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.AssessmentsList>" diff --git a/twilio/rest/flex_api/v1/channel.py b/twilio/rest/flex_api/v1/channel.py new file mode 100644 index 0000000000..aa98ff8d31 --- /dev/null +++ b/twilio/rest/flex_api/v1/channel.py @@ -0,0 +1,575 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ChannelInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Channel resource and owns this Workflow. + :ivar flex_flow_sid: The SID of the Flex Flow. + :ivar sid: The unique string that we created to identify the Channel resource. + :ivar user_sid: The SID of the chat user. + :ivar task_sid: The SID of the TaskRouter Task. Only valid when integration type is `task`. `null` for integration types `studio` & `external` + :ivar url: The absolute URL of the Flex chat channel resource. + :ivar date_created: The date and time in GMT when the Flex chat channel was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Flex chat channel was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.flex_flow_sid: Optional[str] = payload.get("flex_flow_sid") + self.sid: Optional[str] = payload.get("sid") + self.user_sid: Optional[str] = payload.get("user_sid") + self.task_sid: Optional[str] = payload.get("task_sid") + self.url: Optional[str] = payload.get("url") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None + + @property + def _proxy(self) -> "ChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ChannelContext for this ChannelInstance + """ + if self._context is None: + self._context = ChannelContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ChannelInstance": + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ChannelInstance": + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.ChannelInstance {}>".format(context) + + +class ChannelContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ChannelContext + + :param version: Version that contains the resource + :param sid: The SID of the Flex chat channel resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Channels/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelInstance: + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ChannelInstance: + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.ChannelContext {}>".format(context) + + +class ChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: + """ + Build an instance of ChannelInstance + + :param payload: Payload response from the API + """ + return ChannelInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.ChannelPage>" + + +class ChannelList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ChannelList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Channels" + + def create( + self, + flex_flow_sid: str, + identity: str, + chat_user_friendly_name: str, + chat_friendly_name: str, + target: Union[str, object] = values.unset, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + task_attributes: Union[str, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + ) -> ChannelInstance: + """ + Create the ChannelInstance + + :param flex_flow_sid: The SID of the Flex Flow. + :param identity: The `identity` value that uniquely identifies the new resource's chat User. + :param chat_user_friendly_name: The chat participant's friendly name. + :param chat_friendly_name: The chat channel's friendly name. + :param target: The Target Contact Identity, for example the phone number of an SMS. + :param chat_unique_name: The chat channel's unique name. + :param pre_engagement_data: The pre-engagement data. + :param task_sid: The SID of the TaskRouter Task. Only valid when integration type is `task`. `null` for integration types `studio` & `external` + :param task_attributes: The Task attributes to be added for the TaskRouter Task. + :param long_lived: Whether to create the channel as long-lived. + + :returns: The created ChannelInstance + """ + + data = values.of( + { + "FlexFlowSid": flex_flow_sid, + "Identity": identity, + "ChatUserFriendlyName": chat_user_friendly_name, + "ChatFriendlyName": chat_friendly_name, + "Target": target, + "ChatUniqueName": chat_unique_name, + "PreEngagementData": pre_engagement_data, + "TaskSid": task_sid, + "TaskAttributes": task_attributes, + "LongLived": serialize.boolean_to_string(long_lived), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance(self._version, payload) + + async def create_async( + self, + flex_flow_sid: str, + identity: str, + chat_user_friendly_name: str, + chat_friendly_name: str, + target: Union[str, object] = values.unset, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + task_attributes: Union[str, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronously create the ChannelInstance + + :param flex_flow_sid: The SID of the Flex Flow. + :param identity: The `identity` value that uniquely identifies the new resource's chat User. + :param chat_user_friendly_name: The chat participant's friendly name. + :param chat_friendly_name: The chat channel's friendly name. + :param target: The Target Contact Identity, for example the phone number of an SMS. + :param chat_unique_name: The chat channel's unique name. + :param pre_engagement_data: The pre-engagement data. + :param task_sid: The SID of the TaskRouter Task. Only valid when integration type is `task`. `null` for integration types `studio` & `external` + :param task_attributes: The Task attributes to be added for the TaskRouter Task. + :param long_lived: Whether to create the channel as long-lived. + + :returns: The created ChannelInstance + """ + + data = values.of( + { + "FlexFlowSid": flex_flow_sid, + "Identity": identity, + "ChatUserFriendlyName": chat_user_friendly_name, + "ChatFriendlyName": chat_friendly_name, + "Target": target, + "ChatUniqueName": chat_unique_name, + "PreEngagementData": pre_engagement_data, + "TaskSid": task_sid, + "TaskAttributes": task_attributes, + "LongLived": serialize.boolean_to_string(long_lived), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelInstance]: + """ + Streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChannelInstance]: + """ + Asynchronously streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Asynchronously lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Asynchronously retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response) + + def get_page(self, target_url: str) -> ChannelPage: + """ + Retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChannelPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ChannelPage: + """ + Asynchronously retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelPage(self._version, response) + + def get(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: The SID of the Flex chat channel resource to fetch. + """ + return ChannelContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: The SID of the Flex chat channel resource to fetch. + """ + return ChannelContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.ChannelList>" diff --git a/twilio/rest/flex_api/v1/configuration.py b/twilio/rest/flex_api/v1/configuration.py new file mode 100644 index 0000000000..28a66be036 --- /dev/null +++ b/twilio/rest/flex_api/v1/configuration.py @@ -0,0 +1,439 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ConfigurationInstance(InstanceResource): + + class Status(object): + OK = "ok" + INPROGRESS = "inprogress" + NOTSTARTED = "notstarted" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Configuration resource. + :ivar date_created: The date and time in GMT when the Configuration resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Configuration resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar attributes: An object that contains application-specific data. + :ivar status: + :ivar taskrouter_workspace_sid: The SID of the TaskRouter Workspace. + :ivar taskrouter_target_workflow_sid: The SID of the TaskRouter target Workflow. + :ivar taskrouter_target_taskqueue_sid: The SID of the TaskRouter Target TaskQueue. + :ivar taskrouter_taskqueues: The list of TaskRouter TaskQueues. + :ivar taskrouter_skills: The Skill description for TaskRouter workers. + :ivar taskrouter_worker_channels: The TaskRouter default channel capacities and availability for workers. + :ivar taskrouter_worker_attributes: The TaskRouter Worker attributes. + :ivar taskrouter_offline_activity_sid: The TaskRouter SID of the offline activity. + :ivar runtime_domain: The URL where the Flex instance is hosted. + :ivar messaging_service_instance_sid: The SID of the Messaging service instance. + :ivar chat_service_instance_sid: The SID of the chat service this user belongs to. + :ivar flex_service_instance_sid: The SID of the Flex service instance. + :ivar flex_instance_sid: The SID of the Flex instance. + :ivar ui_language: The primary language of the Flex UI. + :ivar ui_attributes: The object that describes Flex UI characteristics and settings. + :ivar ui_dependencies: The object that defines the NPM packages and versions to be used in Hosted Flex. + :ivar ui_version: The Pinned UI version. + :ivar service_version: The Flex Service version. + :ivar call_recording_enabled: Whether call recording is enabled. + :ivar call_recording_webhook_url: The call recording webhook URL. + :ivar crm_enabled: Whether CRM is present for Flex. + :ivar crm_type: The CRM type. + :ivar crm_callback_url: The CRM Callback URL. + :ivar crm_fallback_url: The CRM Fallback URL. + :ivar crm_attributes: An object that contains the CRM attributes. + :ivar public_attributes: The list of public attributes, which are visible to unauthenticated clients. + :ivar plugin_service_enabled: Whether the plugin service enabled. + :ivar plugin_service_attributes: The plugin service attributes. + :ivar integrations: A list of objects that contain the configurations for the Integrations supported in this configuration. + :ivar outbound_call_flows: The list of outbound call flows. + :ivar serverless_service_sids: The list of serverless service SIDs. + :ivar queue_stats_configuration: Configurable parameters for Queues Statistics. + :ivar notifications: Configurable parameters for Notifications. + :ivar markdown: Configurable parameters for Markdown. + :ivar url: The absolute URL of the Configuration resource. + :ivar flex_insights_hr: Object with enabled/disabled flag with list of workspaces. + :ivar flex_insights_drilldown: Setting this to true will redirect Flex UI to the URL set in flex_url + :ivar flex_url: URL to redirect to in case drilldown is enabled. + :ivar channel_configs: Settings for different limits for Flex Conversations channels attachments. + :ivar debugger_integration: Configurable parameters for Debugger Integration. + :ivar flex_ui_status_report: Configurable parameters for Flex UI Status report. + :ivar agent_conv_end_methods: Agent conversation end methods. + :ivar citrix_voice_vdi: Citrix voice vdi configuration and settings. + :ivar offline_config: Presence and presence ttl configuration + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.attributes: Optional[Dict[str, object]] = payload.get("attributes") + self.status: Optional["ConfigurationInstance.Status"] = payload.get("status") + self.taskrouter_workspace_sid: Optional[str] = payload.get( + "taskrouter_workspace_sid" + ) + self.taskrouter_target_workflow_sid: Optional[str] = payload.get( + "taskrouter_target_workflow_sid" + ) + self.taskrouter_target_taskqueue_sid: Optional[str] = payload.get( + "taskrouter_target_taskqueue_sid" + ) + self.taskrouter_taskqueues: Optional[List[Dict[str, object]]] = payload.get( + "taskrouter_taskqueues" + ) + self.taskrouter_skills: Optional[List[Dict[str, object]]] = payload.get( + "taskrouter_skills" + ) + self.taskrouter_worker_channels: Optional[Dict[str, object]] = payload.get( + "taskrouter_worker_channels" + ) + self.taskrouter_worker_attributes: Optional[Dict[str, object]] = payload.get( + "taskrouter_worker_attributes" + ) + self.taskrouter_offline_activity_sid: Optional[str] = payload.get( + "taskrouter_offline_activity_sid" + ) + self.runtime_domain: Optional[str] = payload.get("runtime_domain") + self.messaging_service_instance_sid: Optional[str] = payload.get( + "messaging_service_instance_sid" + ) + self.chat_service_instance_sid: Optional[str] = payload.get( + "chat_service_instance_sid" + ) + self.flex_service_instance_sid: Optional[str] = payload.get( + "flex_service_instance_sid" + ) + self.flex_instance_sid: Optional[str] = payload.get("flex_instance_sid") + self.ui_language: Optional[str] = payload.get("ui_language") + self.ui_attributes: Optional[Dict[str, object]] = payload.get("ui_attributes") + self.ui_dependencies: Optional[Dict[str, object]] = payload.get( + "ui_dependencies" + ) + self.ui_version: Optional[str] = payload.get("ui_version") + self.service_version: Optional[str] = payload.get("service_version") + self.call_recording_enabled: Optional[bool] = payload.get( + "call_recording_enabled" + ) + self.call_recording_webhook_url: Optional[str] = payload.get( + "call_recording_webhook_url" + ) + self.crm_enabled: Optional[bool] = payload.get("crm_enabled") + self.crm_type: Optional[str] = payload.get("crm_type") + self.crm_callback_url: Optional[str] = payload.get("crm_callback_url") + self.crm_fallback_url: Optional[str] = payload.get("crm_fallback_url") + self.crm_attributes: Optional[Dict[str, object]] = payload.get("crm_attributes") + self.public_attributes: Optional[Dict[str, object]] = payload.get( + "public_attributes" + ) + self.plugin_service_enabled: Optional[bool] = payload.get( + "plugin_service_enabled" + ) + self.plugin_service_attributes: Optional[Dict[str, object]] = payload.get( + "plugin_service_attributes" + ) + self.integrations: Optional[List[Dict[str, object]]] = payload.get( + "integrations" + ) + self.outbound_call_flows: Optional[Dict[str, object]] = payload.get( + "outbound_call_flows" + ) + self.serverless_service_sids: Optional[List[str]] = payload.get( + "serverless_service_sids" + ) + self.queue_stats_configuration: Optional[Dict[str, object]] = payload.get( + "queue_stats_configuration" + ) + self.notifications: Optional[Dict[str, object]] = payload.get("notifications") + self.markdown: Optional[Dict[str, object]] = payload.get("markdown") + self.url: Optional[str] = payload.get("url") + self.flex_insights_hr: Optional[Dict[str, object]] = payload.get( + "flex_insights_hr" + ) + self.flex_insights_drilldown: Optional[bool] = payload.get( + "flex_insights_drilldown" + ) + self.flex_url: Optional[str] = payload.get("flex_url") + self.channel_configs: Optional[List[Dict[str, object]]] = payload.get( + "channel_configs" + ) + self.debugger_integration: Optional[Dict[str, object]] = payload.get( + "debugger_integration" + ) + self.flex_ui_status_report: Optional[Dict[str, object]] = payload.get( + "flex_ui_status_report" + ) + self.agent_conv_end_methods: Optional[Dict[str, object]] = payload.get( + "agent_conv_end_methods" + ) + self.citrix_voice_vdi: Optional[Dict[str, object]] = payload.get( + "citrix_voice_vdi" + ) + self.offline_config: Optional[Dict[str, object]] = payload.get("offline_config") + + self._context: Optional[ConfigurationContext] = None + + @property + def _proxy(self) -> "ConfigurationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConfigurationContext for this ConfigurationInstance + """ + if self._context is None: + self._context = ConfigurationContext( + self._version, + ) + return self._context + + def fetch( + self, ui_version: Union[str, object] = values.unset + ) -> "ConfigurationInstance": + """ + Fetch the ConfigurationInstance + + :param ui_version: The Pinned UI version of the Configuration resource to fetch. + + :returns: The fetched ConfigurationInstance + """ + return self._proxy.fetch( + ui_version=ui_version, + ) + + async def fetch_async( + self, ui_version: Union[str, object] = values.unset + ) -> "ConfigurationInstance": + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + :param ui_version: The Pinned UI version of the Configuration resource to fetch. + + :returns: The fetched ConfigurationInstance + """ + return await self._proxy.fetch_async( + ui_version=ui_version, + ) + + def update( + self, body: Union[object, object] = values.unset + ) -> "ConfigurationInstance": + """ + Update the ConfigurationInstance + + :param body: + + :returns: The updated ConfigurationInstance + """ + return self._proxy.update( + body=body, + ) + + async def update_async( + self, body: Union[object, object] = values.unset + ) -> "ConfigurationInstance": + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param body: + + :returns: The updated ConfigurationInstance + """ + return await self._proxy.update_async( + body=body, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.FlexApi.V1.ConfigurationInstance>" + + +class ConfigurationContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the ConfigurationContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/Configuration" + + def fetch( + self, ui_version: Union[str, object] = values.unset + ) -> ConfigurationInstance: + """ + Fetch the ConfigurationInstance + + :param ui_version: The Pinned UI version of the Configuration resource to fetch. + + :returns: The fetched ConfigurationInstance + """ + + data = values.of( + { + "UiVersion": ui_version, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return ConfigurationInstance( + self._version, + payload, + ) + + async def fetch_async( + self, ui_version: Union[str, object] = values.unset + ) -> ConfigurationInstance: + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + :param ui_version: The Pinned UI version of the Configuration resource to fetch. + + :returns: The fetched ConfigurationInstance + """ + + data = values.of( + { + "UiVersion": ui_version, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return ConfigurationInstance( + self._version, + payload, + ) + + def update( + self, body: Union[object, object] = values.unset + ) -> ConfigurationInstance: + """ + Update the ConfigurationInstance + + :param body: + + :returns: The updated ConfigurationInstance + """ + data = body.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConfigurationInstance(self._version, payload) + + async def update_async( + self, body: Union[object, object] = values.unset + ) -> ConfigurationInstance: + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param body: + + :returns: The updated ConfigurationInstance + """ + data = body.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConfigurationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.FlexApi.V1.ConfigurationContext>" + + +class ConfigurationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + """ + return ConfigurationContext(self._version) + + def __call__(self) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + """ + return ConfigurationContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.ConfigurationList>" diff --git a/twilio/rest/flex_api/v1/flex_flow.py b/twilio/rest/flex_api/v1/flex_flow.py new file mode 100644 index 0000000000..0ae2634666 --- /dev/null +++ b/twilio/rest/flex_api/v1/flex_flow.py @@ -0,0 +1,965 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class FlexFlowInstance(InstanceResource): + + class ChannelType(object): + WEB = "web" + SMS = "sms" + FACEBOOK = "facebook" + WHATSAPP = "whatsapp" + LINE = "line" + CUSTOM = "custom" + + class IntegrationType(object): + STUDIO = "studio" + EXTERNAL = "external" + TASK = "task" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Flow resource and owns this Workflow. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar sid: The unique string that we created to identify the Flex Flow resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar chat_service_sid: The SID of the chat service. + :ivar channel_type: + :ivar contact_identity: The channel contact's Identity. + :ivar enabled: Whether the Flex Flow is enabled. + :ivar integration_type: + :ivar integration: An object that contains specific parameters for the integration. + :ivar long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :ivar janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :ivar url: The absolute URL of the Flex Flow resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.channel_type: Optional["FlexFlowInstance.ChannelType"] = payload.get( + "channel_type" + ) + self.contact_identity: Optional[str] = payload.get("contact_identity") + self.enabled: Optional[bool] = payload.get("enabled") + self.integration_type: Optional["FlexFlowInstance.IntegrationType"] = ( + payload.get("integration_type") + ) + self.integration: Optional[Dict[str, object]] = payload.get("integration") + self.long_lived: Optional[bool] = payload.get("long_lived") + self.janitor_enabled: Optional[bool] = payload.get("janitor_enabled") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[FlexFlowContext] = None + + @property + def _proxy(self) -> "FlexFlowContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FlexFlowContext for this FlexFlowInstance + """ + if self._context is None: + self._context = FlexFlowContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the FlexFlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FlexFlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "FlexFlowInstance": + """ + Fetch the FlexFlowInstance + + + :returns: The fetched FlexFlowInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FlexFlowInstance": + """ + Asynchronous coroutine to fetch the FlexFlowInstance + + + :returns: The fetched FlexFlowInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + chat_service_sid: Union[str, object] = values.unset, + channel_type: Union["FlexFlowInstance.ChannelType", object] = values.unset, + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> "FlexFlowInstance": + """ + Update the FlexFlowInstance + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: The updated FlexFlowInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + chat_service_sid=chat_service_sid, + channel_type=channel_type, + contact_identity=contact_identity, + enabled=enabled, + integration_type=integration_type, + integration_flow_sid=integration_flow_sid, + integration_url=integration_url, + integration_workspace_sid=integration_workspace_sid, + integration_workflow_sid=integration_workflow_sid, + integration_channel=integration_channel, + integration_timeout=integration_timeout, + integration_priority=integration_priority, + integration_creation_on_message=integration_creation_on_message, + long_lived=long_lived, + janitor_enabled=janitor_enabled, + integration_retry_count=integration_retry_count, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + chat_service_sid: Union[str, object] = values.unset, + channel_type: Union["FlexFlowInstance.ChannelType", object] = values.unset, + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> "FlexFlowInstance": + """ + Asynchronous coroutine to update the FlexFlowInstance + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: The updated FlexFlowInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + chat_service_sid=chat_service_sid, + channel_type=channel_type, + contact_identity=contact_identity, + enabled=enabled, + integration_type=integration_type, + integration_flow_sid=integration_flow_sid, + integration_url=integration_url, + integration_workspace_sid=integration_workspace_sid, + integration_workflow_sid=integration_workflow_sid, + integration_channel=integration_channel, + integration_timeout=integration_timeout, + integration_priority=integration_priority, + integration_creation_on_message=integration_creation_on_message, + long_lived=long_lived, + janitor_enabled=janitor_enabled, + integration_retry_count=integration_retry_count, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.FlexFlowInstance {}>".format(context) + + +class FlexFlowContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the FlexFlowContext + + :param version: Version that contains the resource + :param sid: The SID of the Flex Flow resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/FlexFlows/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the FlexFlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FlexFlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> FlexFlowInstance: + """ + Fetch the FlexFlowInstance + + + :returns: The fetched FlexFlowInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FlexFlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> FlexFlowInstance: + """ + Asynchronous coroutine to fetch the FlexFlowInstance + + + :returns: The fetched FlexFlowInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FlexFlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + chat_service_sid: Union[str, object] = values.unset, + channel_type: Union["FlexFlowInstance.ChannelType", object] = values.unset, + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> FlexFlowInstance: + """ + Update the FlexFlowInstance + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: The updated FlexFlowInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ChatServiceSid": chat_service_sid, + "ChannelType": channel_type, + "ContactIdentity": contact_identity, + "Enabled": serialize.boolean_to_string(enabled), + "IntegrationType": integration_type, + "Integration.FlowSid": integration_flow_sid, + "Integration.Url": integration_url, + "Integration.WorkspaceSid": integration_workspace_sid, + "Integration.WorkflowSid": integration_workflow_sid, + "Integration.Channel": integration_channel, + "Integration.Timeout": integration_timeout, + "Integration.Priority": integration_priority, + "Integration.CreationOnMessage": serialize.boolean_to_string( + integration_creation_on_message + ), + "LongLived": serialize.boolean_to_string(long_lived), + "JanitorEnabled": serialize.boolean_to_string(janitor_enabled), + "Integration.RetryCount": integration_retry_count, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlexFlowInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + chat_service_sid: Union[str, object] = values.unset, + channel_type: Union["FlexFlowInstance.ChannelType", object] = values.unset, + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> FlexFlowInstance: + """ + Asynchronous coroutine to update the FlexFlowInstance + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: The updated FlexFlowInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ChatServiceSid": chat_service_sid, + "ChannelType": channel_type, + "ContactIdentity": contact_identity, + "Enabled": serialize.boolean_to_string(enabled), + "IntegrationType": integration_type, + "Integration.FlowSid": integration_flow_sid, + "Integration.Url": integration_url, + "Integration.WorkspaceSid": integration_workspace_sid, + "Integration.WorkflowSid": integration_workflow_sid, + "Integration.Channel": integration_channel, + "Integration.Timeout": integration_timeout, + "Integration.Priority": integration_priority, + "Integration.CreationOnMessage": serialize.boolean_to_string( + integration_creation_on_message + ), + "LongLived": serialize.boolean_to_string(long_lived), + "JanitorEnabled": serialize.boolean_to_string(janitor_enabled), + "Integration.RetryCount": integration_retry_count, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlexFlowInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.FlexFlowContext {}>".format(context) + + +class FlexFlowPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FlexFlowInstance: + """ + Build an instance of FlexFlowInstance + + :param payload: Payload response from the API + """ + return FlexFlowInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.FlexFlowPage>" + + +class FlexFlowList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the FlexFlowList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/FlexFlows" + + def create( + self, + friendly_name: str, + chat_service_sid: str, + channel_type: "FlexFlowInstance.ChannelType", + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> FlexFlowInstance: + """ + Create the FlexFlowInstance + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: The created FlexFlowInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ChatServiceSid": chat_service_sid, + "ChannelType": channel_type, + "ContactIdentity": contact_identity, + "Enabled": serialize.boolean_to_string(enabled), + "IntegrationType": integration_type, + "Integration.FlowSid": integration_flow_sid, + "Integration.Url": integration_url, + "Integration.WorkspaceSid": integration_workspace_sid, + "Integration.WorkflowSid": integration_workflow_sid, + "Integration.Channel": integration_channel, + "Integration.Timeout": integration_timeout, + "Integration.Priority": integration_priority, + "Integration.CreationOnMessage": serialize.boolean_to_string( + integration_creation_on_message + ), + "LongLived": serialize.boolean_to_string(long_lived), + "JanitorEnabled": serialize.boolean_to_string(janitor_enabled), + "Integration.RetryCount": integration_retry_count, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlexFlowInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + chat_service_sid: str, + channel_type: "FlexFlowInstance.ChannelType", + contact_identity: Union[str, object] = values.unset, + enabled: Union[bool, object] = values.unset, + integration_type: Union[ + "FlexFlowInstance.IntegrationType", object + ] = values.unset, + integration_flow_sid: Union[str, object] = values.unset, + integration_url: Union[str, object] = values.unset, + integration_workspace_sid: Union[str, object] = values.unset, + integration_workflow_sid: Union[str, object] = values.unset, + integration_channel: Union[str, object] = values.unset, + integration_timeout: Union[int, object] = values.unset, + integration_priority: Union[int, object] = values.unset, + integration_creation_on_message: Union[bool, object] = values.unset, + long_lived: Union[bool, object] = values.unset, + janitor_enabled: Union[bool, object] = values.unset, + integration_retry_count: Union[int, object] = values.unset, + ) -> FlexFlowInstance: + """ + Asynchronously create the FlexFlowInstance + + :param friendly_name: A descriptive string that you create to describe the Flex Flow resource. + :param chat_service_sid: The SID of the chat service. + :param channel_type: + :param contact_identity: The channel contact's Identity. + :param enabled: Whether the new Flex Flow is enabled. + :param integration_type: + :param integration_flow_sid: The SID of the Studio Flow. Required when `integrationType` is `studio`. + :param integration_url: The URL of the external webhook. Required when `integrationType` is `external`. + :param integration_workspace_sid: The Workspace SID for a new Task. Required when `integrationType` is `task`. + :param integration_workflow_sid: The Workflow SID for a new Task. Required when `integrationType` is `task`. + :param integration_channel: The Task Channel SID (TCXXXX) or unique name (e.g., `sms`) to use for the Task that will be created. Applicable and required when `integrationType` is `task`. The default value is `default`. + :param integration_timeout: The Task timeout in seconds for a new Task. Default is 86,400 seconds (24 hours). Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_priority: The Task priority of a new Task. The default priority is 0. Optional when `integrationType` is `task`, not applicable otherwise. + :param integration_creation_on_message: In the context of outbound messaging, defines whether to create a Task immediately (and therefore reserve the conversation to current agent), or delay Task creation until the customer sends the first response. Set to false to create immediately, true to delay Task creation. This setting is only applicable for outbound messaging. + :param long_lived: When enabled, Flex will keep the chat channel active so that it may be used for subsequent interactions with a contact identity. Defaults to `false`. + :param janitor_enabled: When enabled, the Messaging Channel Janitor will remove active Proxy sessions if the associated Task is deleted outside of the Flex UI. Defaults to `false`. + :param integration_retry_count: The number of times to retry the Studio Flow or webhook in case of failure. Takes integer values from 0 to 3 with the default being 3. Optional when `integrationType` is `studio` or `external`, not applicable otherwise. + + :returns: The created FlexFlowInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ChatServiceSid": chat_service_sid, + "ChannelType": channel_type, + "ContactIdentity": contact_identity, + "Enabled": serialize.boolean_to_string(enabled), + "IntegrationType": integration_type, + "Integration.FlowSid": integration_flow_sid, + "Integration.Url": integration_url, + "Integration.WorkspaceSid": integration_workspace_sid, + "Integration.WorkflowSid": integration_workflow_sid, + "Integration.Channel": integration_channel, + "Integration.Timeout": integration_timeout, + "Integration.Priority": integration_priority, + "Integration.CreationOnMessage": serialize.boolean_to_string( + integration_creation_on_message + ), + "LongLived": serialize.boolean_to_string(long_lived), + "JanitorEnabled": serialize.boolean_to_string(janitor_enabled), + "Integration.RetryCount": integration_retry_count, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlexFlowInstance(self._version, payload) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FlexFlowInstance]: + """ + Streams FlexFlowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FlexFlowInstance]: + """ + Asynchronously streams FlexFlowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlexFlowInstance]: + """ + Lists FlexFlowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlexFlowInstance]: + """ + Asynchronously lists FlexFlowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FlexFlowPage: + """ + Retrieve a single page of FlexFlowInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FlexFlowInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlexFlowPage(self._version, response) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FlexFlowPage: + """ + Asynchronously retrieve a single page of FlexFlowInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Flex Flow resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FlexFlowInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlexFlowPage(self._version, response) + + def get_page(self, target_url: str) -> FlexFlowPage: + """ + Retrieve a specific page of FlexFlowInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FlexFlowInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FlexFlowPage(self._version, response) + + async def get_page_async(self, target_url: str) -> FlexFlowPage: + """ + Asynchronously retrieve a specific page of FlexFlowInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FlexFlowInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FlexFlowPage(self._version, response) + + def get(self, sid: str) -> FlexFlowContext: + """ + Constructs a FlexFlowContext + + :param sid: The SID of the Flex Flow resource to update. + """ + return FlexFlowContext(self._version, sid=sid) + + def __call__(self, sid: str) -> FlexFlowContext: + """ + Constructs a FlexFlowContext + + :param sid: The SID of the Flex Flow resource to update. + """ + return FlexFlowContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.FlexFlowList>" diff --git a/twilio/rest/flex_api/v1/insights_assessments_comment.py b/twilio/rest/flex_api/v1/insights_assessments_comment.py new file mode 100644 index 0000000000..2b6c79343b --- /dev/null +++ b/twilio/rest/flex_api/v1/insights_assessments_comment.py @@ -0,0 +1,469 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InsightsAssessmentsCommentInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. + :ivar assessment_sid: The SID of the assessment. + :ivar comment: The comment added for assessment. + :ivar offset: The offset + :ivar report: The flag indicating if this assessment is part of report + :ivar weight: The weightage given to this comment + :ivar agent_id: The id of the agent. + :ivar segment_id: The id of the segment. + :ivar user_name: The name of the user. + :ivar user_email: The email id of the user. + :ivar timestamp: The timestamp when the record is inserted + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.assessment_sid: Optional[str] = payload.get("assessment_sid") + self.comment: Optional[Dict[str, object]] = payload.get("comment") + self.offset: Optional[float] = deserialize.decimal(payload.get("offset")) + self.report: Optional[bool] = payload.get("report") + self.weight: Optional[float] = deserialize.decimal(payload.get("weight")) + self.agent_id: Optional[str] = payload.get("agent_id") + self.segment_id: Optional[str] = payload.get("segment_id") + self.user_name: Optional[str] = payload.get("user_name") + self.user_email: Optional[str] = payload.get("user_email") + self.timestamp: Optional[float] = deserialize.decimal(payload.get("timestamp")) + self.url: Optional[str] = payload.get("url") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.FlexApi.V1.InsightsAssessmentsCommentInstance>" + + +class InsightsAssessmentsCommentPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> InsightsAssessmentsCommentInstance: + """ + Build an instance of InsightsAssessmentsCommentInstance + + :param payload: Payload response from the API + """ + return InsightsAssessmentsCommentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InsightsAssessmentsCommentPage>" + + +class InsightsAssessmentsCommentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InsightsAssessmentsCommentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Insights/QualityManagement/Assessments/Comments" + + def create( + self, + category_id: str, + category_name: str, + comment: str, + segment_id: str, + agent_id: str, + offset: float, + authorization: Union[str, object] = values.unset, + ) -> InsightsAssessmentsCommentInstance: + """ + Create the InsightsAssessmentsCommentInstance + + :param category_id: The ID of the category + :param category_name: The name of the category + :param comment: The Assessment comment. + :param segment_id: The id of the segment. + :param agent_id: The id of the agent. + :param offset: The offset + :param authorization: The Authorization HTTP request header + + :returns: The created InsightsAssessmentsCommentInstance + """ + + data = values.of( + { + "CategoryId": category_id, + "CategoryName": category_name, + "Comment": comment, + "SegmentId": segment_id, + "AgentId": agent_id, + "Offset": offset, + } + ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsAssessmentsCommentInstance(self._version, payload) + + async def create_async( + self, + category_id: str, + category_name: str, + comment: str, + segment_id: str, + agent_id: str, + offset: float, + authorization: Union[str, object] = values.unset, + ) -> InsightsAssessmentsCommentInstance: + """ + Asynchronously create the InsightsAssessmentsCommentInstance + + :param category_id: The ID of the category + :param category_name: The name of the category + :param comment: The Assessment comment. + :param segment_id: The id of the segment. + :param agent_id: The id of the agent. + :param offset: The offset + :param authorization: The Authorization HTTP request header + + :returns: The created InsightsAssessmentsCommentInstance + """ + + data = values.of( + { + "CategoryId": category_id, + "CategoryName": category_name, + "Comment": comment, + "SegmentId": segment_id, + "AgentId": agent_id, + "Offset": offset, + } + ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsAssessmentsCommentInstance(self._version, payload) + + def stream( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InsightsAssessmentsCommentInstance]: + """ + Streams InsightsAssessmentsCommentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param str agent_id: The id of the agent. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + authorization=authorization, + segment_id=segment_id, + agent_id=agent_id, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InsightsAssessmentsCommentInstance]: + """ + Asynchronously streams InsightsAssessmentsCommentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param str agent_id: The id of the agent. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + authorization=authorization, + segment_id=segment_id, + agent_id=agent_id, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsAssessmentsCommentInstance]: + """ + Lists InsightsAssessmentsCommentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param str agent_id: The id of the agent. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + authorization=authorization, + segment_id=segment_id, + agent_id=agent_id, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsAssessmentsCommentInstance]: + """ + Asynchronously lists InsightsAssessmentsCommentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: The id of the segment. + :param str agent_id: The id of the agent. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + authorization=authorization, + segment_id=segment_id, + agent_id=agent_id, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsAssessmentsCommentPage: + """ + Retrieve a single page of InsightsAssessmentsCommentInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param segment_id: The id of the segment. + :param agent_id: The id of the agent. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsAssessmentsCommentInstance + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "AgentId": agent_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsAssessmentsCommentPage(self._version, response) + + async def page_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + agent_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsAssessmentsCommentPage: + """ + Asynchronously retrieve a single page of InsightsAssessmentsCommentInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param segment_id: The id of the segment. + :param agent_id: The id of the agent. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsAssessmentsCommentInstance + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "AgentId": agent_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsAssessmentsCommentPage(self._version, response) + + def get_page(self, target_url: str) -> InsightsAssessmentsCommentPage: + """ + Retrieve a specific page of InsightsAssessmentsCommentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsAssessmentsCommentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InsightsAssessmentsCommentPage(self._version, response) + + async def get_page_async(self, target_url: str) -> InsightsAssessmentsCommentPage: + """ + Asynchronously retrieve a specific page of InsightsAssessmentsCommentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsAssessmentsCommentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InsightsAssessmentsCommentPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InsightsAssessmentsCommentList>" diff --git a/twilio/rest/flex_api/v1/insights_conversations.py b/twilio/rest/flex_api/v1/insights_conversations.py new file mode 100644 index 0000000000..efdcea203e --- /dev/null +++ b/twilio/rest/flex_api/v1/insights_conversations.py @@ -0,0 +1,333 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InsightsConversationsInstance(InstanceResource): + """ + :ivar account_id: The id of the account. + :ivar conversation_id: The unique id of the conversation + :ivar segment_count: The count of segments for a conversation + :ivar segments: The Segments of a conversation + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_id: Optional[str] = payload.get("account_id") + self.conversation_id: Optional[str] = payload.get("conversation_id") + self.segment_count: Optional[int] = deserialize.integer( + payload.get("segment_count") + ) + self.segments: Optional[List[Dict[str, object]]] = payload.get("segments") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.FlexApi.V1.InsightsConversationsInstance>" + + +class InsightsConversationsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InsightsConversationsInstance: + """ + Build an instance of InsightsConversationsInstance + + :param payload: Payload response from the API + """ + return InsightsConversationsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InsightsConversationsPage>" + + +class InsightsConversationsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InsightsConversationsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Insights/Conversations" + + def stream( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InsightsConversationsInstance]: + """ + Streams InsightsConversationsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InsightsConversationsInstance]: + """ + Asynchronously streams InsightsConversationsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsConversationsInstance]: + """ + Lists InsightsConversationsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + authorization=authorization, + segment_id=segment_id, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsConversationsInstance]: + """ + Asynchronously lists InsightsConversationsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + authorization=authorization, + segment_id=segment_id, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsConversationsPage: + """ + Retrieve a single page of InsightsConversationsInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsConversationsInstance + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsConversationsPage(self._version, response) + + async def page_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsConversationsPage: + """ + Asynchronously retrieve a single page of InsightsConversationsInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param segment_id: Unique Id of the segment for which conversation details needs to be fetched + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsConversationsInstance + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsConversationsPage(self._version, response) + + def get_page(self, target_url: str) -> InsightsConversationsPage: + """ + Retrieve a specific page of InsightsConversationsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsConversationsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InsightsConversationsPage(self._version, response) + + async def get_page_async(self, target_url: str) -> InsightsConversationsPage: + """ + Asynchronously retrieve a specific page of InsightsConversationsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsConversationsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InsightsConversationsPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InsightsConversationsList>" diff --git a/twilio/rest/flex_api/v1/insights_questionnaires.py b/twilio/rest/flex_api/v1/insights_questionnaires.py new file mode 100644 index 0000000000..d21aff8242 --- /dev/null +++ b/twilio/rest/flex_api/v1/insights_questionnaires.py @@ -0,0 +1,813 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InsightsQuestionnairesInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. + :ivar questionnaire_sid: The sid of this questionnaire + :ivar name: The name of this category. + :ivar description: The description of this questionnaire + :ivar active: The flag to enable or disable questionnaire + :ivar questions: The list of questions with category for a questionnaire + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + questionnaire_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.questionnaire_sid: Optional[str] = payload.get("questionnaire_sid") + self.name: Optional[str] = payload.get("name") + self.description: Optional[str] = payload.get("description") + self.active: Optional[bool] = payload.get("active") + self.questions: Optional[List[Dict[str, object]]] = payload.get("questions") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "questionnaire_sid": questionnaire_sid or self.questionnaire_sid, + } + self._context: Optional[InsightsQuestionnairesContext] = None + + @property + def _proxy(self) -> "InsightsQuestionnairesContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InsightsQuestionnairesContext for this InsightsQuestionnairesInstance + """ + if self._context is None: + self._context = InsightsQuestionnairesContext( + self._version, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + return self._context + + def delete(self, authorization: Union[str, object] = values.unset) -> bool: + """ + Deletes the InsightsQuestionnairesInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + authorization=authorization, + ) + + async def delete_async( + self, authorization: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + authorization=authorization, + ) + + def fetch( + self, authorization: Union[str, object] = values.unset + ) -> "InsightsQuestionnairesInstance": + """ + Fetch the InsightsQuestionnairesInstance + + :param authorization: The Authorization HTTP request header + + :returns: The fetched InsightsQuestionnairesInstance + """ + return self._proxy.fetch( + authorization=authorization, + ) + + async def fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> "InsightsQuestionnairesInstance": + """ + Asynchronous coroutine to fetch the InsightsQuestionnairesInstance + + :param authorization: The Authorization HTTP request header + + :returns: The fetched InsightsQuestionnairesInstance + """ + return await self._proxy.fetch_async( + authorization=authorization, + ) + + def update( + self, + active: bool, + authorization: Union[str, object] = values.unset, + name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> "InsightsQuestionnairesInstance": + """ + Update the InsightsQuestionnairesInstance + + :param active: The flag to enable or disable questionnaire + :param authorization: The Authorization HTTP request header + :param name: The name of this questionnaire + :param description: The description of this questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: The updated InsightsQuestionnairesInstance + """ + return self._proxy.update( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) + + async def update_async( + self, + active: bool, + authorization: Union[str, object] = values.unset, + name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> "InsightsQuestionnairesInstance": + """ + Asynchronous coroutine to update the InsightsQuestionnairesInstance + + :param active: The flag to enable or disable questionnaire + :param authorization: The Authorization HTTP request header + :param name: The name of this questionnaire + :param description: The description of this questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: The updated InsightsQuestionnairesInstance + """ + return await self._proxy.update_async( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.InsightsQuestionnairesInstance {}>".format(context) + + +class InsightsQuestionnairesContext(InstanceContext): + + def __init__(self, version: Version, questionnaire_sid: str): + """ + Initialize the InsightsQuestionnairesContext + + :param version: Version that contains the resource + :param questionnaire_sid: The SID of the questionnaire + """ + super().__init__(version) + + # Path Solution + self._solution = { + "questionnaire_sid": questionnaire_sid, + } + self._uri = ( + "/Insights/QualityManagement/Questionnaires/{questionnaire_sid}".format( + **self._solution + ) + ) + + def delete(self, authorization: Union[str, object] = values.unset) -> bool: + """ + Deletes the InsightsQuestionnairesInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, authorization: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch( + self, authorization: Union[str, object] = values.unset + ) -> InsightsQuestionnairesInstance: + """ + Fetch the InsightsQuestionnairesInstance + + :param authorization: The Authorization HTTP request header + + :returns: The fetched InsightsQuestionnairesInstance + """ + + data = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + + async def fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> InsightsQuestionnairesInstance: + """ + Asynchronous coroutine to fetch the InsightsQuestionnairesInstance + + :param authorization: The Authorization HTTP request header + + :returns: The fetched InsightsQuestionnairesInstance + """ + + data = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + + def update( + self, + active: bool, + authorization: Union[str, object] = values.unset, + name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> InsightsQuestionnairesInstance: + """ + Update the InsightsQuestionnairesInstance + + :param active: The flag to enable or disable questionnaire + :param authorization: The Authorization HTTP request header + :param name: The name of this questionnaire + :param description: The description of this questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: The updated InsightsQuestionnairesInstance + """ + + data = values.of( + { + "Active": serialize.boolean_to_string(active), + "Name": name, + "Description": description, + "QuestionSids": serialize.map(question_sids, lambda e: e), + } + ) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + + async def update_async( + self, + active: bool, + authorization: Union[str, object] = values.unset, + name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> InsightsQuestionnairesInstance: + """ + Asynchronous coroutine to update the InsightsQuestionnairesInstance + + :param active: The flag to enable or disable questionnaire + :param authorization: The Authorization HTTP request header + :param name: The name of this questionnaire + :param description: The description of this questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: The updated InsightsQuestionnairesInstance + """ + + data = values.of( + { + "Active": serialize.boolean_to_string(active), + "Name": name, + "Description": description, + "QuestionSids": serialize.map(question_sids, lambda e: e), + } + ) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.InsightsQuestionnairesContext {}>".format(context) + + +class InsightsQuestionnairesPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InsightsQuestionnairesInstance: + """ + Build an instance of InsightsQuestionnairesInstance + + :param payload: Payload response from the API + """ + return InsightsQuestionnairesInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InsightsQuestionnairesPage>" + + +class InsightsQuestionnairesList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InsightsQuestionnairesList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Insights/QualityManagement/Questionnaires" + + def create( + self, + name: str, + authorization: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + active: Union[bool, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> InsightsQuestionnairesInstance: + """ + Create the InsightsQuestionnairesInstance + + :param name: The name of this questionnaire + :param authorization: The Authorization HTTP request header + :param description: The description of this questionnaire + :param active: The flag to enable or disable questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: The created InsightsQuestionnairesInstance + """ + + data = values.of( + { + "Name": name, + "Description": description, + "Active": serialize.boolean_to_string(active), + "QuestionSids": serialize.map(question_sids, lambda e: e), + } + ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesInstance(self._version, payload) + + async def create_async( + self, + name: str, + authorization: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + active: Union[bool, object] = values.unset, + question_sids: Union[List[str], object] = values.unset, + ) -> InsightsQuestionnairesInstance: + """ + Asynchronously create the InsightsQuestionnairesInstance + + :param name: The name of this questionnaire + :param authorization: The Authorization HTTP request header + :param description: The description of this questionnaire + :param active: The flag to enable or disable questionnaire + :param question_sids: The list of questions sids under a questionnaire + + :returns: The created InsightsQuestionnairesInstance + """ + + data = values.of( + { + "Name": name, + "Description": description, + "Active": serialize.boolean_to_string(active), + "QuestionSids": serialize.map(question_sids, lambda e: e), + } + ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesInstance(self._version, payload) + + def stream( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InsightsQuestionnairesInstance]: + """ + Streams InsightsQuestionnairesInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param bool include_inactive: Flag indicating whether to include inactive questionnaires or not + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + authorization=authorization, + include_inactive=include_inactive, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InsightsQuestionnairesInstance]: + """ + Asynchronously streams InsightsQuestionnairesInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param bool include_inactive: Flag indicating whether to include inactive questionnaires or not + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + authorization=authorization, + include_inactive=include_inactive, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsQuestionnairesInstance]: + """ + Lists InsightsQuestionnairesInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param bool include_inactive: Flag indicating whether to include inactive questionnaires or not + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + authorization=authorization, + include_inactive=include_inactive, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsQuestionnairesInstance]: + """ + Asynchronously lists InsightsQuestionnairesInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param bool include_inactive: Flag indicating whether to include inactive questionnaires or not + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + authorization=authorization, + include_inactive=include_inactive, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsQuestionnairesPage: + """ + Retrieve a single page of InsightsQuestionnairesInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param include_inactive: Flag indicating whether to include inactive questionnaires or not + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsQuestionnairesInstance + """ + data = values.of( + { + "Authorization": authorization, + "IncludeInactive": serialize.boolean_to_string(include_inactive), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsQuestionnairesPage(self._version, response) + + async def page_async( + self, + authorization: Union[str, object] = values.unset, + include_inactive: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsQuestionnairesPage: + """ + Asynchronously retrieve a single page of InsightsQuestionnairesInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param include_inactive: Flag indicating whether to include inactive questionnaires or not + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsQuestionnairesInstance + """ + data = values.of( + { + "Authorization": authorization, + "IncludeInactive": serialize.boolean_to_string(include_inactive), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsQuestionnairesPage(self._version, response) + + def get_page(self, target_url: str) -> InsightsQuestionnairesPage: + """ + Retrieve a specific page of InsightsQuestionnairesInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsQuestionnairesInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InsightsQuestionnairesPage(self._version, response) + + async def get_page_async(self, target_url: str) -> InsightsQuestionnairesPage: + """ + Asynchronously retrieve a specific page of InsightsQuestionnairesInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsQuestionnairesInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InsightsQuestionnairesPage(self._version, response) + + def get(self, questionnaire_sid: str) -> InsightsQuestionnairesContext: + """ + Constructs a InsightsQuestionnairesContext + + :param questionnaire_sid: The SID of the questionnaire + """ + return InsightsQuestionnairesContext( + self._version, questionnaire_sid=questionnaire_sid + ) + + def __call__(self, questionnaire_sid: str) -> InsightsQuestionnairesContext: + """ + Constructs a InsightsQuestionnairesContext + + :param questionnaire_sid: The SID of the questionnaire + """ + return InsightsQuestionnairesContext( + self._version, questionnaire_sid=questionnaire_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InsightsQuestionnairesList>" diff --git a/twilio/rest/flex_api/v1/insights_questionnaires_category.py b/twilio/rest/flex_api/v1/insights_questionnaires_category.py new file mode 100644 index 0000000000..817a4753f9 --- /dev/null +++ b/twilio/rest/flex_api/v1/insights_questionnaires_category.py @@ -0,0 +1,631 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InsightsQuestionnairesCategoryInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. + :ivar category_sid: The SID of the category + :ivar name: The name of this category. + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + category_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.category_sid: Optional[str] = payload.get("category_sid") + self.name: Optional[str] = payload.get("name") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "category_sid": category_sid or self.category_sid, + } + self._context: Optional[InsightsQuestionnairesCategoryContext] = None + + @property + def _proxy(self) -> "InsightsQuestionnairesCategoryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InsightsQuestionnairesCategoryContext for this InsightsQuestionnairesCategoryInstance + """ + if self._context is None: + self._context = InsightsQuestionnairesCategoryContext( + self._version, + category_sid=self._solution["category_sid"], + ) + return self._context + + def delete(self, authorization: Union[str, object] = values.unset) -> bool: + """ + Deletes the InsightsQuestionnairesCategoryInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + authorization=authorization, + ) + + async def delete_async( + self, authorization: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesCategoryInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + authorization=authorization, + ) + + def update( + self, name: str, authorization: Union[str, object] = values.unset + ) -> "InsightsQuestionnairesCategoryInstance": + """ + Update the InsightsQuestionnairesCategoryInstance + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: The updated InsightsQuestionnairesCategoryInstance + """ + return self._proxy.update( + name=name, + authorization=authorization, + ) + + async def update_async( + self, name: str, authorization: Union[str, object] = values.unset + ) -> "InsightsQuestionnairesCategoryInstance": + """ + Asynchronous coroutine to update the InsightsQuestionnairesCategoryInstance + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: The updated InsightsQuestionnairesCategoryInstance + """ + return await self._proxy.update_async( + name=name, + authorization=authorization, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.InsightsQuestionnairesCategoryInstance {}>".format( + context + ) + + +class InsightsQuestionnairesCategoryContext(InstanceContext): + + def __init__(self, version: Version, category_sid: str): + """ + Initialize the InsightsQuestionnairesCategoryContext + + :param version: Version that contains the resource + :param category_sid: The SID of the category to be updated + """ + super().__init__(version) + + # Path Solution + self._solution = { + "category_sid": category_sid, + } + self._uri = "/Insights/QualityManagement/Categories/{category_sid}".format( + **self._solution + ) + + def delete(self, authorization: Union[str, object] = values.unset) -> bool: + """ + Deletes the InsightsQuestionnairesCategoryInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, authorization: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesCategoryInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def update( + self, name: str, authorization: Union[str, object] = values.unset + ) -> InsightsQuestionnairesCategoryInstance: + """ + Update the InsightsQuestionnairesCategoryInstance + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: The updated InsightsQuestionnairesCategoryInstance + """ + + data = values.of( + { + "Name": name, + } + ) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesCategoryInstance( + self._version, payload, category_sid=self._solution["category_sid"] + ) + + async def update_async( + self, name: str, authorization: Union[str, object] = values.unset + ) -> InsightsQuestionnairesCategoryInstance: + """ + Asynchronous coroutine to update the InsightsQuestionnairesCategoryInstance + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: The updated InsightsQuestionnairesCategoryInstance + """ + + data = values.of( + { + "Name": name, + } + ) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesCategoryInstance( + self._version, payload, category_sid=self._solution["category_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.InsightsQuestionnairesCategoryContext {}>".format( + context + ) + + +class InsightsQuestionnairesCategoryPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> InsightsQuestionnairesCategoryInstance: + """ + Build an instance of InsightsQuestionnairesCategoryInstance + + :param payload: Payload response from the API + """ + return InsightsQuestionnairesCategoryInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InsightsQuestionnairesCategoryPage>" + + +class InsightsQuestionnairesCategoryList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InsightsQuestionnairesCategoryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Insights/QualityManagement/Categories" + + def create( + self, name: str, authorization: Union[str, object] = values.unset + ) -> InsightsQuestionnairesCategoryInstance: + """ + Create the InsightsQuestionnairesCategoryInstance + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: The created InsightsQuestionnairesCategoryInstance + """ + + data = values.of( + { + "Name": name, + } + ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesCategoryInstance(self._version, payload) + + async def create_async( + self, name: str, authorization: Union[str, object] = values.unset + ) -> InsightsQuestionnairesCategoryInstance: + """ + Asynchronously create the InsightsQuestionnairesCategoryInstance + + :param name: The name of this category. + :param authorization: The Authorization HTTP request header + + :returns: The created InsightsQuestionnairesCategoryInstance + """ + + data = values.of( + { + "Name": name, + } + ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesCategoryInstance(self._version, payload) + + def stream( + self, + authorization: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InsightsQuestionnairesCategoryInstance]: + """ + Streams InsightsQuestionnairesCategoryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(authorization=authorization, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + authorization: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InsightsQuestionnairesCategoryInstance]: + """ + Asynchronously streams InsightsQuestionnairesCategoryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + authorization=authorization, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + authorization: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsQuestionnairesCategoryInstance]: + """ + Lists InsightsQuestionnairesCategoryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + authorization=authorization, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + authorization: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsQuestionnairesCategoryInstance]: + """ + Asynchronously lists InsightsQuestionnairesCategoryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + authorization=authorization, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + authorization: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsQuestionnairesCategoryPage: + """ + Retrieve a single page of InsightsQuestionnairesCategoryInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsQuestionnairesCategoryInstance + """ + data = values.of( + { + "Authorization": authorization, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsQuestionnairesCategoryPage(self._version, response) + + async def page_async( + self, + authorization: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsQuestionnairesCategoryPage: + """ + Asynchronously retrieve a single page of InsightsQuestionnairesCategoryInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsQuestionnairesCategoryInstance + """ + data = values.of( + { + "Authorization": authorization, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsQuestionnairesCategoryPage(self._version, response) + + def get_page(self, target_url: str) -> InsightsQuestionnairesCategoryPage: + """ + Retrieve a specific page of InsightsQuestionnairesCategoryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsQuestionnairesCategoryInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InsightsQuestionnairesCategoryPage(self._version, response) + + async def get_page_async( + self, target_url: str + ) -> InsightsQuestionnairesCategoryPage: + """ + Asynchronously retrieve a specific page of InsightsQuestionnairesCategoryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsQuestionnairesCategoryInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InsightsQuestionnairesCategoryPage(self._version, response) + + def get(self, category_sid: str) -> InsightsQuestionnairesCategoryContext: + """ + Constructs a InsightsQuestionnairesCategoryContext + + :param category_sid: The SID of the category to be updated + """ + return InsightsQuestionnairesCategoryContext( + self._version, category_sid=category_sid + ) + + def __call__(self, category_sid: str) -> InsightsQuestionnairesCategoryContext: + """ + Constructs a InsightsQuestionnairesCategoryContext + + :param category_sid: The SID of the category to be updated + """ + return InsightsQuestionnairesCategoryContext( + self._version, category_sid=category_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InsightsQuestionnairesCategoryList>" diff --git a/twilio/rest/flex_api/v1/insights_questionnaires_question.py b/twilio/rest/flex_api/v1/insights_questionnaires_question.py new file mode 100644 index 0000000000..33e2304599 --- /dev/null +++ b/twilio/rest/flex_api/v1/insights_questionnaires_question.py @@ -0,0 +1,749 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InsightsQuestionnairesQuestionInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. + :ivar question_sid: The SID of the question + :ivar question: The question. + :ivar description: The description for the question. + :ivar category: The Category for the question. + :ivar answer_set_id: The answer_set for the question. + :ivar allow_na: The flag to enable for disable NA for answer. + :ivar usage: Integer value that tells a particular question is used by how many questionnaires + :ivar answer_set: Set of answers for the question + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + question_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.question_sid: Optional[str] = payload.get("question_sid") + self.question: Optional[str] = payload.get("question") + self.description: Optional[str] = payload.get("description") + self.category: Optional[Dict[str, object]] = payload.get("category") + self.answer_set_id: Optional[str] = payload.get("answer_set_id") + self.allow_na: Optional[bool] = payload.get("allow_na") + self.usage: Optional[int] = deserialize.integer(payload.get("usage")) + self.answer_set: Optional[Dict[str, object]] = payload.get("answer_set") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "question_sid": question_sid or self.question_sid, + } + self._context: Optional[InsightsQuestionnairesQuestionContext] = None + + @property + def _proxy(self) -> "InsightsQuestionnairesQuestionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InsightsQuestionnairesQuestionContext for this InsightsQuestionnairesQuestionInstance + """ + if self._context is None: + self._context = InsightsQuestionnairesQuestionContext( + self._version, + question_sid=self._solution["question_sid"], + ) + return self._context + + def delete(self, authorization: Union[str, object] = values.unset) -> bool: + """ + Deletes the InsightsQuestionnairesQuestionInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + authorization=authorization, + ) + + async def delete_async( + self, authorization: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesQuestionInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + authorization=authorization, + ) + + def update( + self, + allow_na: bool, + authorization: Union[str, object] = values.unset, + category_sid: Union[str, object] = values.unset, + question: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + answer_set_id: Union[str, object] = values.unset, + ) -> "InsightsQuestionnairesQuestionInstance": + """ + Update the InsightsQuestionnairesQuestionInstance + + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param category_sid: The SID of the category + :param question: The question. + :param description: The description for the question. + :param answer_set_id: The answer_set for the question. + + :returns: The updated InsightsQuestionnairesQuestionInstance + """ + return self._proxy.update( + allow_na=allow_na, + authorization=authorization, + category_sid=category_sid, + question=question, + description=description, + answer_set_id=answer_set_id, + ) + + async def update_async( + self, + allow_na: bool, + authorization: Union[str, object] = values.unset, + category_sid: Union[str, object] = values.unset, + question: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + answer_set_id: Union[str, object] = values.unset, + ) -> "InsightsQuestionnairesQuestionInstance": + """ + Asynchronous coroutine to update the InsightsQuestionnairesQuestionInstance + + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param category_sid: The SID of the category + :param question: The question. + :param description: The description for the question. + :param answer_set_id: The answer_set for the question. + + :returns: The updated InsightsQuestionnairesQuestionInstance + """ + return await self._proxy.update_async( + allow_na=allow_na, + authorization=authorization, + category_sid=category_sid, + question=question, + description=description, + answer_set_id=answer_set_id, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.InsightsQuestionnairesQuestionInstance {}>".format( + context + ) + + +class InsightsQuestionnairesQuestionContext(InstanceContext): + + def __init__(self, version: Version, question_sid: str): + """ + Initialize the InsightsQuestionnairesQuestionContext + + :param version: Version that contains the resource + :param question_sid: The SID of the question + """ + super().__init__(version) + + # Path Solution + self._solution = { + "question_sid": question_sid, + } + self._uri = "/Insights/QualityManagement/Questions/{question_sid}".format( + **self._solution + ) + + def delete(self, authorization: Union[str, object] = values.unset) -> bool: + """ + Deletes the InsightsQuestionnairesQuestionInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, authorization: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesQuestionInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def update( + self, + allow_na: bool, + authorization: Union[str, object] = values.unset, + category_sid: Union[str, object] = values.unset, + question: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + answer_set_id: Union[str, object] = values.unset, + ) -> InsightsQuestionnairesQuestionInstance: + """ + Update the InsightsQuestionnairesQuestionInstance + + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param category_sid: The SID of the category + :param question: The question. + :param description: The description for the question. + :param answer_set_id: The answer_set for the question. + + :returns: The updated InsightsQuestionnairesQuestionInstance + """ + + data = values.of( + { + "AllowNa": serialize.boolean_to_string(allow_na), + "CategorySid": category_sid, + "Question": question, + "Description": description, + "AnswerSetId": answer_set_id, + } + ) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesQuestionInstance( + self._version, payload, question_sid=self._solution["question_sid"] + ) + + async def update_async( + self, + allow_na: bool, + authorization: Union[str, object] = values.unset, + category_sid: Union[str, object] = values.unset, + question: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + answer_set_id: Union[str, object] = values.unset, + ) -> InsightsQuestionnairesQuestionInstance: + """ + Asynchronous coroutine to update the InsightsQuestionnairesQuestionInstance + + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param category_sid: The SID of the category + :param question: The question. + :param description: The description for the question. + :param answer_set_id: The answer_set for the question. + + :returns: The updated InsightsQuestionnairesQuestionInstance + """ + + data = values.of( + { + "AllowNa": serialize.boolean_to_string(allow_na), + "CategorySid": category_sid, + "Question": question, + "Description": description, + "AnswerSetId": answer_set_id, + } + ) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesQuestionInstance( + self._version, payload, question_sid=self._solution["question_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.InsightsQuestionnairesQuestionContext {}>".format( + context + ) + + +class InsightsQuestionnairesQuestionPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> InsightsQuestionnairesQuestionInstance: + """ + Build an instance of InsightsQuestionnairesQuestionInstance + + :param payload: Payload response from the API + """ + return InsightsQuestionnairesQuestionInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InsightsQuestionnairesQuestionPage>" + + +class InsightsQuestionnairesQuestionList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InsightsQuestionnairesQuestionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Insights/QualityManagement/Questions" + + def create( + self, + category_sid: str, + question: str, + answer_set_id: str, + allow_na: bool, + authorization: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> InsightsQuestionnairesQuestionInstance: + """ + Create the InsightsQuestionnairesQuestionInstance + + :param category_sid: The SID of the category + :param question: The question. + :param answer_set_id: The answer_set for the question. + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param description: The description for the question. + + :returns: The created InsightsQuestionnairesQuestionInstance + """ + + data = values.of( + { + "CategorySid": category_sid, + "Question": question, + "AnswerSetId": answer_set_id, + "AllowNa": serialize.boolean_to_string(allow_na), + "Description": description, + } + ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesQuestionInstance(self._version, payload) + + async def create_async( + self, + category_sid: str, + question: str, + answer_set_id: str, + allow_na: bool, + authorization: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> InsightsQuestionnairesQuestionInstance: + """ + Asynchronously create the InsightsQuestionnairesQuestionInstance + + :param category_sid: The SID of the category + :param question: The question. + :param answer_set_id: The answer_set for the question. + :param allow_na: The flag to enable for disable NA for answer. + :param authorization: The Authorization HTTP request header + :param description: The description for the question. + + :returns: The created InsightsQuestionnairesQuestionInstance + """ + + data = values.of( + { + "CategorySid": category_sid, + "Question": question, + "AnswerSetId": answer_set_id, + "AllowNa": serialize.boolean_to_string(allow_na), + "Description": description, + } + ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InsightsQuestionnairesQuestionInstance(self._version, payload) + + def stream( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InsightsQuestionnairesQuestionInstance]: + """ + Streams InsightsQuestionnairesQuestionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param List[str] category_sid: The list of category SIDs + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + authorization=authorization, + category_sid=category_sid, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InsightsQuestionnairesQuestionInstance]: + """ + Asynchronously streams InsightsQuestionnairesQuestionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param List[str] category_sid: The list of category SIDs + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + authorization=authorization, + category_sid=category_sid, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsQuestionnairesQuestionInstance]: + """ + Lists InsightsQuestionnairesQuestionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param List[str] category_sid: The list of category SIDs + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + authorization=authorization, + category_sid=category_sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsQuestionnairesQuestionInstance]: + """ + Asynchronously lists InsightsQuestionnairesQuestionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param List[str] category_sid: The list of category SIDs + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + authorization=authorization, + category_sid=category_sid, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsQuestionnairesQuestionPage: + """ + Retrieve a single page of InsightsQuestionnairesQuestionInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param category_sid: The list of category SIDs + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsQuestionnairesQuestionInstance + """ + data = values.of( + { + "Authorization": authorization, + "CategorySid": serialize.map(category_sid, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsQuestionnairesQuestionPage(self._version, response) + + async def page_async( + self, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsQuestionnairesQuestionPage: + """ + Asynchronously retrieve a single page of InsightsQuestionnairesQuestionInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param category_sid: The list of category SIDs + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsQuestionnairesQuestionInstance + """ + data = values.of( + { + "Authorization": authorization, + "CategorySid": serialize.map(category_sid, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsQuestionnairesQuestionPage(self._version, response) + + def get_page(self, target_url: str) -> InsightsQuestionnairesQuestionPage: + """ + Retrieve a specific page of InsightsQuestionnairesQuestionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsQuestionnairesQuestionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InsightsQuestionnairesQuestionPage(self._version, response) + + async def get_page_async( + self, target_url: str + ) -> InsightsQuestionnairesQuestionPage: + """ + Asynchronously retrieve a specific page of InsightsQuestionnairesQuestionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsQuestionnairesQuestionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InsightsQuestionnairesQuestionPage(self._version, response) + + def get(self, question_sid: str) -> InsightsQuestionnairesQuestionContext: + """ + Constructs a InsightsQuestionnairesQuestionContext + + :param question_sid: The SID of the question + """ + return InsightsQuestionnairesQuestionContext( + self._version, question_sid=question_sid + ) + + def __call__(self, question_sid: str) -> InsightsQuestionnairesQuestionContext: + """ + Constructs a InsightsQuestionnairesQuestionContext + + :param question_sid: The SID of the question + """ + return InsightsQuestionnairesQuestionContext( + self._version, question_sid=question_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InsightsQuestionnairesQuestionList>" diff --git a/twilio/rest/flex_api/v1/insights_segments.py b/twilio/rest/flex_api/v1/insights_segments.py new file mode 100644 index 0000000000..7c98e81cff --- /dev/null +++ b/twilio/rest/flex_api/v1/insights_segments.py @@ -0,0 +1,395 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InsightsSegmentsInstance(InstanceResource): + """ + :ivar segment_id: To unique id of the segment + :ivar external_id: The unique id for the conversation. + :ivar queue: + :ivar external_contact: + :ivar external_segment_link_id: The uuid for the external_segment_link. + :ivar date: The date of the conversation. + :ivar account_id: The unique id for the account. + :ivar external_segment_link: The hyperlink to recording of the task event. + :ivar agent_id: The unique id for the agent. + :ivar agent_phone: The phone number of the agent. + :ivar agent_name: The name of the agent. + :ivar agent_team_name: The team name to which agent belongs. + :ivar agent_team_name_in_hierarchy: he team name to which agent belongs. + :ivar agent_link: The link to the agent conversation. + :ivar customer_phone: The phone number of the customer. + :ivar customer_name: The name of the customer. + :ivar customer_link: The link to the customer conversation. + :ivar segment_recording_offset: The offset value for the recording. + :ivar media: The media identifiers of the conversation. + :ivar assessment_type: The type of the assessment. + :ivar assessment_percentage: The percentage scored on the Assessments. + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.segment_id: Optional[str] = payload.get("segment_id") + self.external_id: Optional[str] = payload.get("external_id") + self.queue: Optional[str] = payload.get("queue") + self.external_contact: Optional[str] = payload.get("external_contact") + self.external_segment_link_id: Optional[str] = payload.get( + "external_segment_link_id" + ) + self.date: Optional[str] = payload.get("date") + self.account_id: Optional[str] = payload.get("account_id") + self.external_segment_link: Optional[str] = payload.get("external_segment_link") + self.agent_id: Optional[str] = payload.get("agent_id") + self.agent_phone: Optional[str] = payload.get("agent_phone") + self.agent_name: Optional[str] = payload.get("agent_name") + self.agent_team_name: Optional[str] = payload.get("agent_team_name") + self.agent_team_name_in_hierarchy: Optional[str] = payload.get( + "agent_team_name_in_hierarchy" + ) + self.agent_link: Optional[str] = payload.get("agent_link") + self.customer_phone: Optional[str] = payload.get("customer_phone") + self.customer_name: Optional[str] = payload.get("customer_name") + self.customer_link: Optional[str] = payload.get("customer_link") + self.segment_recording_offset: Optional[str] = payload.get( + "segment_recording_offset" + ) + self.media: Optional[Dict[str, object]] = payload.get("media") + self.assessment_type: Optional[Dict[str, object]] = payload.get( + "assessment_type" + ) + self.assessment_percentage: Optional[Dict[str, object]] = payload.get( + "assessment_percentage" + ) + self.url: Optional[str] = payload.get("url") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.FlexApi.V1.InsightsSegmentsInstance>" + + +class InsightsSegmentsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InsightsSegmentsInstance: + """ + Build an instance of InsightsSegmentsInstance + + :param payload: Payload response from the API + """ + return InsightsSegmentsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InsightsSegmentsPage>" + + +class InsightsSegmentsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InsightsSegmentsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Insights/Segments" + + def stream( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InsightsSegmentsInstance]: + """ + Streams InsightsSegmentsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: To unique id of the segment + :param List[str] reservation_id: The list of reservation Ids + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InsightsSegmentsInstance]: + """ + Asynchronously streams InsightsSegmentsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: To unique id of the segment + :param List[str] reservation_id: The list of reservation Ids + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsSegmentsInstance]: + """ + Lists InsightsSegmentsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: To unique id of the segment + :param List[str] reservation_id: The list of reservation Ids + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InsightsSegmentsInstance]: + """ + Asynchronously lists InsightsSegmentsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str authorization: The Authorization HTTP request header + :param str segment_id: To unique id of the segment + :param List[str] reservation_id: The list of reservation Ids + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsSegmentsPage: + """ + Retrieve a single page of InsightsSegmentsInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param segment_id: To unique id of the segment + :param reservation_id: The list of reservation Ids + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsSegmentsInstance + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "ReservationId": serialize.map(reservation_id, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsSegmentsPage(self._version, response) + + async def page_async( + self, + authorization: Union[str, object] = values.unset, + segment_id: Union[str, object] = values.unset, + reservation_id: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InsightsSegmentsPage: + """ + Asynchronously retrieve a single page of InsightsSegmentsInstance records from the API. + Request is executed immediately + + :param authorization: The Authorization HTTP request header + :param segment_id: To unique id of the segment + :param reservation_id: The list of reservation Ids + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InsightsSegmentsInstance + """ + data = values.of( + { + "Authorization": authorization, + "SegmentId": segment_id, + "ReservationId": serialize.map(reservation_id, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InsightsSegmentsPage(self._version, response) + + def get_page(self, target_url: str) -> InsightsSegmentsPage: + """ + Retrieve a specific page of InsightsSegmentsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsSegmentsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InsightsSegmentsPage(self._version, response) + + async def get_page_async(self, target_url: str) -> InsightsSegmentsPage: + """ + Asynchronously retrieve a specific page of InsightsSegmentsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InsightsSegmentsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InsightsSegmentsPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InsightsSegmentsList>" diff --git a/twilio/rest/flex_api/v1/insights_session.py b/twilio/rest/flex_api/v1/insights_session.py new file mode 100644 index 0000000000..b4174aa949 --- /dev/null +++ b/twilio/rest/flex_api/v1/insights_session.py @@ -0,0 +1,190 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class InsightsSessionInstance(InstanceResource): + """ + :ivar workspace_id: Unique ID to identify the user's workspace + :ivar session_expiry: The session expiry date and time, given in ISO 8601 format. + :ivar session_id: The unique ID for the session + :ivar base_url: The base URL to fetch reports and dashboards + :ivar url: The URL of this resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.workspace_id: Optional[str] = payload.get("workspace_id") + self.session_expiry: Optional[str] = payload.get("session_expiry") + self.session_id: Optional[str] = payload.get("session_id") + self.base_url: Optional[str] = payload.get("base_url") + self.url: Optional[str] = payload.get("url") + + self._context: Optional[InsightsSessionContext] = None + + @property + def _proxy(self) -> "InsightsSessionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InsightsSessionContext for this InsightsSessionInstance + """ + if self._context is None: + self._context = InsightsSessionContext( + self._version, + ) + return self._context + + def create( + self, authorization: Union[str, object] = values.unset + ) -> "InsightsSessionInstance": + """ + Create the InsightsSessionInstance + + :param authorization: The Authorization HTTP request header + + :returns: The created InsightsSessionInstance + """ + return self._proxy.create( + authorization=authorization, + ) + + async def create_async( + self, authorization: Union[str, object] = values.unset + ) -> "InsightsSessionInstance": + """ + Asynchronous coroutine to create the InsightsSessionInstance + + :param authorization: The Authorization HTTP request header + + :returns: The created InsightsSessionInstance + """ + return await self._proxy.create_async( + authorization=authorization, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.FlexApi.V1.InsightsSessionInstance>" + + +class InsightsSessionContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the InsightsSessionContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/Insights/Session" + + def create( + self, authorization: Union[str, object] = values.unset + ) -> InsightsSessionInstance: + """ + Create the InsightsSessionInstance + + :param authorization: The Authorization HTTP request header + + :returns: The created InsightsSessionInstance + """ + data = values.of( + { + "Authorization": authorization, + } + ) + + payload = self._version.create(method="POST", uri=self._uri, data=data) + + return InsightsSessionInstance(self._version, payload) + + async def create_async( + self, authorization: Union[str, object] = values.unset + ) -> InsightsSessionInstance: + """ + Asynchronous coroutine to create the InsightsSessionInstance + + :param authorization: The Authorization HTTP request header + + :returns: The created InsightsSessionInstance + """ + data = values.of( + { + "Authorization": authorization, + } + ) + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data + ) + + return InsightsSessionInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.FlexApi.V1.InsightsSessionContext>" + + +class InsightsSessionList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InsightsSessionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> InsightsSessionContext: + """ + Constructs a InsightsSessionContext + + """ + return InsightsSessionContext(self._version) + + def __call__(self) -> InsightsSessionContext: + """ + Constructs a InsightsSessionContext + + """ + return InsightsSessionContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InsightsSessionList>" diff --git a/twilio/rest/flex_api/v1/insights_settings_answer_sets.py b/twilio/rest/flex_api/v1/insights_settings_answer_sets.py new file mode 100644 index 0000000000..9b0e89e938 --- /dev/null +++ b/twilio/rest/flex_api/v1/insights_settings_answer_sets.py @@ -0,0 +1,118 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class InsightsSettingsAnswerSetsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. + :ivar answer_sets: The lis of answer sets + :ivar answer_set_categories: The list of answer set categories + :ivar not_applicable: The details for not applicable answer set + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.answer_sets: Optional[Dict[str, object]] = payload.get("answer_sets") + self.answer_set_categories: Optional[Dict[str, object]] = payload.get( + "answer_set_categories" + ) + self.not_applicable: Optional[Dict[str, object]] = payload.get("not_applicable") + self.url: Optional[str] = payload.get("url") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.FlexApi.V1.InsightsSettingsAnswerSetsInstance>" + + +class InsightsSettingsAnswerSetsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InsightsSettingsAnswerSetsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Insights/QualityManagement/Settings/AnswerSets" + + def fetch( + self, authorization: Union[str, object] = values.unset + ) -> InsightsSettingsAnswerSetsInstance: + """ + Asynchronously fetch the InsightsSettingsAnswerSetsInstance + + :param authorization: The Authorization HTTP request header + :returns: The fetched InsightsSettingsAnswerSetsInstance + """ + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InsightsSettingsAnswerSetsInstance(self._version, payload) + + async def fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> InsightsSettingsAnswerSetsInstance: + """ + Asynchronously fetch the InsightsSettingsAnswerSetsInstance + + :param authorization: The Authorization HTTP request header + :returns: The fetched InsightsSettingsAnswerSetsInstance + """ + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InsightsSettingsAnswerSetsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InsightsSettingsAnswerSetsList>" diff --git a/twilio/rest/flex_api/v1/insights_settings_comment.py b/twilio/rest/flex_api/v1/insights_settings_comment.py new file mode 100644 index 0000000000..18733a4957 --- /dev/null +++ b/twilio/rest/flex_api/v1/insights_settings_comment.py @@ -0,0 +1,112 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class InsightsSettingsCommentInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. + :ivar comments: + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.comments: Optional[Dict[str, object]] = payload.get("comments") + self.url: Optional[str] = payload.get("url") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.FlexApi.V1.InsightsSettingsCommentInstance>" + + +class InsightsSettingsCommentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InsightsSettingsCommentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Insights/QualityManagement/Settings/CommentTags" + + def fetch( + self, authorization: Union[str, object] = values.unset + ) -> InsightsSettingsCommentInstance: + """ + Asynchronously fetch the InsightsSettingsCommentInstance + + :param authorization: The Authorization HTTP request header + :returns: The fetched InsightsSettingsCommentInstance + """ + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InsightsSettingsCommentInstance(self._version, payload) + + async def fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> InsightsSettingsCommentInstance: + """ + Asynchronously fetch the InsightsSettingsCommentInstance + + :param authorization: The Authorization HTTP request header + :returns: The fetched InsightsSettingsCommentInstance + """ + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InsightsSettingsCommentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InsightsSettingsCommentList>" diff --git a/twilio/rest/flex_api/v1/insights_user_roles.py b/twilio/rest/flex_api/v1/insights_user_roles.py new file mode 100644 index 0000000000..19cb10b8e4 --- /dev/null +++ b/twilio/rest/flex_api/v1/insights_user_roles.py @@ -0,0 +1,202 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class InsightsUserRolesInstance(InstanceResource): + """ + :ivar roles: Flex Insights roles for the user + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.roles: Optional[List[str]] = payload.get("roles") + self.url: Optional[str] = payload.get("url") + + self._context: Optional[InsightsUserRolesContext] = None + + @property + def _proxy(self) -> "InsightsUserRolesContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InsightsUserRolesContext for this InsightsUserRolesInstance + """ + if self._context is None: + self._context = InsightsUserRolesContext( + self._version, + ) + return self._context + + def fetch( + self, authorization: Union[str, object] = values.unset + ) -> "InsightsUserRolesInstance": + """ + Fetch the InsightsUserRolesInstance + + :param authorization: The Authorization HTTP request header + + :returns: The fetched InsightsUserRolesInstance + """ + return self._proxy.fetch( + authorization=authorization, + ) + + async def fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> "InsightsUserRolesInstance": + """ + Asynchronous coroutine to fetch the InsightsUserRolesInstance + + :param authorization: The Authorization HTTP request header + + :returns: The fetched InsightsUserRolesInstance + """ + return await self._proxy.fetch_async( + authorization=authorization, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.FlexApi.V1.InsightsUserRolesInstance>" + + +class InsightsUserRolesContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the InsightsUserRolesContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/Insights/UserRoles" + + def fetch( + self, authorization: Union[str, object] = values.unset + ) -> InsightsUserRolesInstance: + """ + Fetch the InsightsUserRolesInstance + + :param authorization: The Authorization HTTP request header + + :returns: The fetched InsightsUserRolesInstance + """ + + data = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return InsightsUserRolesInstance( + self._version, + payload, + ) + + async def fetch_async( + self, authorization: Union[str, object] = values.unset + ) -> InsightsUserRolesInstance: + """ + Asynchronous coroutine to fetch the InsightsUserRolesInstance + + :param authorization: The Authorization HTTP request header + + :returns: The fetched InsightsUserRolesInstance + """ + + data = values.of( + { + "Authorization": authorization, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return InsightsUserRolesInstance( + self._version, + payload, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.FlexApi.V1.InsightsUserRolesContext>" + + +class InsightsUserRolesList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InsightsUserRolesList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> InsightsUserRolesContext: + """ + Constructs a InsightsUserRolesContext + + """ + return InsightsUserRolesContext(self._version) + + def __call__(self) -> InsightsUserRolesContext: + """ + Constructs a InsightsUserRolesContext + + """ + return InsightsUserRolesContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InsightsUserRolesList>" diff --git a/twilio/rest/flex_api/v1/interaction/__init__.py b/twilio/rest/flex_api/v1/interaction/__init__.py new file mode 100644 index 0000000000..653938f28d --- /dev/null +++ b/twilio/rest/flex_api/v1/interaction/__init__.py @@ -0,0 +1,386 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.flex_api.v1.interaction.interaction_channel import ( + InteractionChannelList, +) + + +class InteractionInstance(InstanceResource): + """ + :ivar sid: The unique string created by Twilio to identify an Interaction resource, prefixed with KD. + :ivar channel: A JSON object that defines the Interaction’s communication channel and includes details about the channel. See the [Outbound SMS](https://www.twilio.com/docs/flex/developer/conversations/interactions-api/interactions#agent-initiated-outbound-interactions) and [inbound (API-initiated)](https://www.twilio.com/docs/flex/developer/conversations/interactions-api/interactions#api-initiated-contact) Channel object examples. + :ivar routing: A JSON Object representing the routing rules for the Interaction Channel. See [Outbound SMS Example](https://www.twilio.com/docs/flex/developer/conversations/interactions-api/interactions#agent-initiated-outbound-interactions) for an example Routing object. The Interactions resource uses TaskRouter for all routing functionality. All attributes in the Routing object on your Interaction request body are added “as is” to the task. For a list of known attributes consumed by the Flex UI and/or Flex Insights, see [Known Task Attributes](https://www.twilio.com/docs/flex/developer/conversations/interactions-api#task-attributes). + :ivar url: + :ivar links: + :ivar interaction_context_sid: + :ivar webhook_ttid: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.channel: Optional[Dict[str, object]] = payload.get("channel") + self.routing: Optional[Dict[str, object]] = payload.get("routing") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.interaction_context_sid: Optional[str] = payload.get( + "interaction_context_sid" + ) + self.webhook_ttid: Optional[str] = payload.get("webhook_ttid") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[InteractionContext] = None + + @property + def _proxy(self) -> "InteractionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InteractionContext for this InteractionInstance + """ + if self._context is None: + self._context = InteractionContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "InteractionInstance": + """ + Fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InteractionInstance": + """ + Asynchronous coroutine to fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + return await self._proxy.fetch_async() + + def update( + self, webhook_ttid: Union[str, object] = values.unset + ) -> "InteractionInstance": + """ + Update the InteractionInstance + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: The updated InteractionInstance + """ + return self._proxy.update( + webhook_ttid=webhook_ttid, + ) + + async def update_async( + self, webhook_ttid: Union[str, object] = values.unset + ) -> "InteractionInstance": + """ + Asynchronous coroutine to update the InteractionInstance + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: The updated InteractionInstance + """ + return await self._proxy.update_async( + webhook_ttid=webhook_ttid, + ) + + @property + def channels(self) -> InteractionChannelList: + """ + Access the channels + """ + return self._proxy.channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.InteractionInstance {}>".format(context) + + +class InteractionContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the InteractionContext + + :param version: Version that contains the resource + :param sid: The SID of the Interaction resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Interactions/{sid}".format(**self._solution) + + self._channels: Optional[InteractionChannelList] = None + + def fetch(self) -> InteractionInstance: + """ + Fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InteractionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InteractionInstance: + """ + Asynchronous coroutine to fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InteractionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, webhook_ttid: Union[str, object] = values.unset + ) -> InteractionInstance: + """ + Update the InteractionInstance + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: The updated InteractionInstance + """ + + data = values.of( + { + "WebhookTtid": webhook_ttid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, webhook_ttid: Union[str, object] = values.unset + ) -> InteractionInstance: + """ + Asynchronous coroutine to update the InteractionInstance + + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: The updated InteractionInstance + """ + + data = values.of( + { + "WebhookTtid": webhook_ttid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def channels(self) -> InteractionChannelList: + """ + Access the channels + """ + if self._channels is None: + self._channels = InteractionChannelList( + self._version, + self._solution["sid"], + ) + return self._channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.InteractionContext {}>".format(context) + + +class InteractionList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InteractionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Interactions" + + def create( + self, + channel: object, + routing: Union[object, object] = values.unset, + interaction_context_sid: Union[str, object] = values.unset, + webhook_ttid: Union[str, object] = values.unset, + ) -> InteractionInstance: + """ + Create the InteractionInstance + + :param channel: The Interaction's channel. + :param routing: The Interaction's routing logic. + :param interaction_context_sid: The Interaction context sid is used for adding a context lookup sid + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: The created InteractionInstance + """ + + data = values.of( + { + "Channel": serialize.object(channel), + "Routing": serialize.object(routing), + "InteractionContextSid": interaction_context_sid, + "WebhookTtid": webhook_ttid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionInstance(self._version, payload) + + async def create_async( + self, + channel: object, + routing: Union[object, object] = values.unset, + interaction_context_sid: Union[str, object] = values.unset, + webhook_ttid: Union[str, object] = values.unset, + ) -> InteractionInstance: + """ + Asynchronously create the InteractionInstance + + :param channel: The Interaction's channel. + :param routing: The Interaction's routing logic. + :param interaction_context_sid: The Interaction context sid is used for adding a context lookup sid + :param webhook_ttid: The unique identifier for Interaction level webhook + + :returns: The created InteractionInstance + """ + + data = values.of( + { + "Channel": serialize.object(channel), + "Routing": serialize.object(routing), + "InteractionContextSid": interaction_context_sid, + "WebhookTtid": webhook_ttid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionInstance(self._version, payload) + + def get(self, sid: str) -> InteractionContext: + """ + Constructs a InteractionContext + + :param sid: The SID of the Interaction resource to fetch. + """ + return InteractionContext(self._version, sid=sid) + + def __call__(self, sid: str) -> InteractionContext: + """ + Constructs a InteractionContext + + :param sid: The SID of the Interaction resource to fetch. + """ + return InteractionContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InteractionList>" diff --git a/twilio/rest/flex_api/v1/interaction/interaction_channel/__init__.py b/twilio/rest/flex_api/v1/interaction/interaction_channel/__init__.py new file mode 100644 index 0000000000..b029104c8d --- /dev/null +++ b/twilio/rest/flex_api/v1/interaction/interaction_channel/__init__.py @@ -0,0 +1,644 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.flex_api.v1.interaction.interaction_channel.interaction_channel_invite import ( + InteractionChannelInviteList, +) +from twilio.rest.flex_api.v1.interaction.interaction_channel.interaction_channel_participant import ( + InteractionChannelParticipantList, +) +from twilio.rest.flex_api.v1.interaction.interaction_channel.interaction_transfer import ( + InteractionTransferList, +) + + +class InteractionChannelInstance(InstanceResource): + + class ChannelStatus(object): + SETUP = "setup" + ACTIVE = "active" + FAILED = "failed" + CLOSED = "closed" + INACTIVE = "inactive" + + class Type(object): + VOICE = "voice" + SMS = "sms" + EMAIL = "email" + WEB = "web" + WHATSAPP = "whatsapp" + CHAT = "chat" + MESSENGER = "messenger" + GBM = "gbm" + + class UpdateChannelStatus(object): + CLOSED = "closed" + INACTIVE = "inactive" + + """ + :ivar sid: The unique string created by Twilio to identify an Interaction Channel resource, prefixed with UO. + :ivar interaction_sid: The unique string created by Twilio to identify an Interaction resource, prefixed with KD. + :ivar type: + :ivar status: + :ivar error_code: The Twilio error code for a failed channel. + :ivar error_message: The error message for a failed channel. + :ivar url: + :ivar links: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + interaction_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.interaction_sid: Optional[str] = payload.get("interaction_sid") + self.type: Optional["InteractionChannelInstance.Type"] = payload.get("type") + self.status: Optional["InteractionChannelInstance.ChannelStatus"] = payload.get( + "status" + ) + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.error_message: Optional[str] = payload.get("error_message") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "interaction_sid": interaction_sid, + "sid": sid or self.sid, + } + self._context: Optional[InteractionChannelContext] = None + + @property + def _proxy(self) -> "InteractionChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InteractionChannelContext for this InteractionChannelInstance + """ + if self._context is None: + self._context = InteractionChannelContext( + self._version, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "InteractionChannelInstance": + """ + Fetch the InteractionChannelInstance + + + :returns: The fetched InteractionChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InteractionChannelInstance": + """ + Asynchronous coroutine to fetch the InteractionChannelInstance + + + :returns: The fetched InteractionChannelInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> "InteractionChannelInstance": + """ + Update the InteractionChannelInstance + + :param status: + :param routing: It changes the state of associated tasks. Routing status is required, When the channel status is set to `inactive`. Allowed Value for routing status is `closed`. Otherwise Optional, if not specified, all tasks will be set to `wrapping`. + + :returns: The updated InteractionChannelInstance + """ + return self._proxy.update( + status=status, + routing=routing, + ) + + async def update_async( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> "InteractionChannelInstance": + """ + Asynchronous coroutine to update the InteractionChannelInstance + + :param status: + :param routing: It changes the state of associated tasks. Routing status is required, When the channel status is set to `inactive`. Allowed Value for routing status is `closed`. Otherwise Optional, if not specified, all tasks will be set to `wrapping`. + + :returns: The updated InteractionChannelInstance + """ + return await self._proxy.update_async( + status=status, + routing=routing, + ) + + @property + def invites(self) -> InteractionChannelInviteList: + """ + Access the invites + """ + return self._proxy.invites + + @property + def participants(self) -> InteractionChannelParticipantList: + """ + Access the participants + """ + return self._proxy.participants + + @property + def transfers(self) -> InteractionTransferList: + """ + Access the transfers + """ + return self._proxy.transfers + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.InteractionChannelInstance {}>".format(context) + + +class InteractionChannelContext(InstanceContext): + + def __init__(self, version: Version, interaction_sid: str, sid: str): + """ + Initialize the InteractionChannelContext + + :param version: Version that contains the resource + :param interaction_sid: The unique string created by Twilio to identify an Interaction resource, prefixed with KD. + :param sid: The unique string created by Twilio to identify an Interaction Channel resource, prefixed with UO. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "interaction_sid": interaction_sid, + "sid": sid, + } + self._uri = "/Interactions/{interaction_sid}/Channels/{sid}".format( + **self._solution + ) + + self._invites: Optional[InteractionChannelInviteList] = None + self._participants: Optional[InteractionChannelParticipantList] = None + self._transfers: Optional[InteractionTransferList] = None + + def fetch(self) -> InteractionChannelInstance: + """ + Fetch the InteractionChannelInstance + + + :returns: The fetched InteractionChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InteractionChannelInstance: + """ + Asynchronous coroutine to fetch the InteractionChannelInstance + + + :returns: The fetched InteractionChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> InteractionChannelInstance: + """ + Update the InteractionChannelInstance + + :param status: + :param routing: It changes the state of associated tasks. Routing status is required, When the channel status is set to `inactive`. Allowed Value for routing status is `closed`. Otherwise Optional, if not specified, all tasks will be set to `wrapping`. + + :returns: The updated InteractionChannelInstance + """ + + data = values.of( + { + "Status": status, + "Routing": serialize.object(routing), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + status: "InteractionChannelInstance.UpdateChannelStatus", + routing: Union[object, object] = values.unset, + ) -> InteractionChannelInstance: + """ + Asynchronous coroutine to update the InteractionChannelInstance + + :param status: + :param routing: It changes the state of associated tasks. Routing status is required, When the channel status is set to `inactive`. Allowed Value for routing status is `closed`. Otherwise Optional, if not specified, all tasks will be set to `wrapping`. + + :returns: The updated InteractionChannelInstance + """ + + data = values.of( + { + "Status": status, + "Routing": serialize.object(routing), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], + ) + + @property + def invites(self) -> InteractionChannelInviteList: + """ + Access the invites + """ + if self._invites is None: + self._invites = InteractionChannelInviteList( + self._version, + self._solution["interaction_sid"], + self._solution["sid"], + ) + return self._invites + + @property + def participants(self) -> InteractionChannelParticipantList: + """ + Access the participants + """ + if self._participants is None: + self._participants = InteractionChannelParticipantList( + self._version, + self._solution["interaction_sid"], + self._solution["sid"], + ) + return self._participants + + @property + def transfers(self) -> InteractionTransferList: + """ + Access the transfers + """ + if self._transfers is None: + self._transfers = InteractionTransferList( + self._version, + self._solution["interaction_sid"], + self._solution["sid"], + ) + return self._transfers + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.InteractionChannelContext {}>".format(context) + + +class InteractionChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InteractionChannelInstance: + """ + Build an instance of InteractionChannelInstance + + :param payload: Payload response from the API + """ + return InteractionChannelInstance( + self._version, payload, interaction_sid=self._solution["interaction_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InteractionChannelPage>" + + +class InteractionChannelList(ListResource): + + def __init__(self, version: Version, interaction_sid: str): + """ + Initialize the InteractionChannelList + + :param version: Version that contains the resource + :param interaction_sid: The unique string created by Twilio to identify an Interaction resource, prefixed with KD. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "interaction_sid": interaction_sid, + } + self._uri = "/Interactions/{interaction_sid}/Channels".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InteractionChannelInstance]: + """ + Streams InteractionChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InteractionChannelInstance]: + """ + Asynchronously streams InteractionChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionChannelInstance]: + """ + Lists InteractionChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionChannelInstance]: + """ + Asynchronously lists InteractionChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InteractionChannelPage: + """ + Retrieve a single page of InteractionChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InteractionChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InteractionChannelPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InteractionChannelPage: + """ + Asynchronously retrieve a single page of InteractionChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InteractionChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InteractionChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> InteractionChannelPage: + """ + Retrieve a specific page of InteractionChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InteractionChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InteractionChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> InteractionChannelPage: + """ + Asynchronously retrieve a specific page of InteractionChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InteractionChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InteractionChannelPage(self._version, response, self._solution) + + def get(self, sid: str) -> InteractionChannelContext: + """ + Constructs a InteractionChannelContext + + :param sid: The unique string created by Twilio to identify an Interaction Channel resource, prefixed with UO. + """ + return InteractionChannelContext( + self._version, interaction_sid=self._solution["interaction_sid"], sid=sid + ) + + def __call__(self, sid: str) -> InteractionChannelContext: + """ + Constructs a InteractionChannelContext + + :param sid: The unique string created by Twilio to identify an Interaction Channel resource, prefixed with UO. + """ + return InteractionChannelContext( + self._version, interaction_sid=self._solution["interaction_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InteractionChannelList>" diff --git a/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_invite.py b/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_invite.py new file mode 100644 index 0000000000..a81acd4fc4 --- /dev/null +++ b/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_invite.py @@ -0,0 +1,372 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InteractionChannelInviteInstance(InstanceResource): + """ + :ivar sid: The unique string created by Twilio to identify an Interaction Channel Invite resource. + :ivar interaction_sid: The Interaction SID for this Channel. + :ivar channel_sid: The Channel SID for this Invite. + :ivar routing: A JSON object representing the routing rules for the Interaction Channel. See [Outbound SMS Example](https://www.twilio.com/docs/flex/developer/conversations/interactions-api/interactions#agent-initiated-outbound-interactions) for an example Routing object. The Interactions resource uses TaskRouter for all routing functionality. All attributes in the Routing object on your Interaction request body are added “as is” to the task. For a list of known attributes consumed by the Flex UI and/or Flex Insights, see [Known Task Attributes](https://www.twilio.com/docs/flex/developer/conversations/interactions-api#task-attributes). + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + interaction_sid: str, + channel_sid: str, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.interaction_sid: Optional[str] = payload.get("interaction_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.routing: Optional[Dict[str, object]] = payload.get("routing") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.InteractionChannelInviteInstance {}>".format(context) + + +class InteractionChannelInvitePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InteractionChannelInviteInstance: + """ + Build an instance of InteractionChannelInviteInstance + + :param payload: Payload response from the API + """ + return InteractionChannelInviteInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InteractionChannelInvitePage>" + + +class InteractionChannelInviteList(ListResource): + + def __init__(self, version: Version, interaction_sid: str, channel_sid: str): + """ + Initialize the InteractionChannelInviteList + + :param version: Version that contains the resource + :param interaction_sid: The Interaction SID for this Channel. + :param channel_sid: The Channel SID for this Participant. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + } + self._uri = ( + "/Interactions/{interaction_sid}/Channels/{channel_sid}/Invites".format( + **self._solution + ) + ) + + def create(self, routing: object) -> InteractionChannelInviteInstance: + """ + Create the InteractionChannelInviteInstance + + :param routing: The Interaction's routing logic. + + :returns: The created InteractionChannelInviteInstance + """ + + data = values.of( + { + "Routing": serialize.object(routing), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionChannelInviteInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async(self, routing: object) -> InteractionChannelInviteInstance: + """ + Asynchronously create the InteractionChannelInviteInstance + + :param routing: The Interaction's routing logic. + + :returns: The created InteractionChannelInviteInstance + """ + + data = values.of( + { + "Routing": serialize.object(routing), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionChannelInviteInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InteractionChannelInviteInstance]: + """ + Streams InteractionChannelInviteInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InteractionChannelInviteInstance]: + """ + Asynchronously streams InteractionChannelInviteInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionChannelInviteInstance]: + """ + Lists InteractionChannelInviteInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionChannelInviteInstance]: + """ + Asynchronously lists InteractionChannelInviteInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InteractionChannelInvitePage: + """ + Retrieve a single page of InteractionChannelInviteInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InteractionChannelInviteInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InteractionChannelInvitePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InteractionChannelInvitePage: + """ + Asynchronously retrieve a single page of InteractionChannelInviteInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InteractionChannelInviteInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InteractionChannelInvitePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> InteractionChannelInvitePage: + """ + Retrieve a specific page of InteractionChannelInviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InteractionChannelInviteInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InteractionChannelInvitePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> InteractionChannelInvitePage: + """ + Asynchronously retrieve a specific page of InteractionChannelInviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InteractionChannelInviteInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InteractionChannelInvitePage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InteractionChannelInviteList>" diff --git a/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_participant.py b/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_participant.py new file mode 100644 index 0000000000..53d2d40dbf --- /dev/null +++ b/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_channel_participant.py @@ -0,0 +1,599 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InteractionChannelParticipantInstance(InstanceResource): + + class Status(object): + CLOSED = "closed" + WRAPUP = "wrapup" + + class Type(object): + SUPERVISOR = "supervisor" + CUSTOMER = "customer" + EXTERNAL = "external" + AGENT = "agent" + UNKNOWN = "unknown" + + """ + :ivar sid: The unique string created by Twilio to identify an Interaction Channel Participant resource. + :ivar type: + :ivar interaction_sid: The Interaction Sid for this channel. + :ivar channel_sid: The Channel Sid for this Participant. + :ivar url: + :ivar routing_properties: The Participant's routing properties. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + interaction_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.type: Optional["InteractionChannelParticipantInstance.Type"] = payload.get( + "type" + ) + self.interaction_sid: Optional[str] = payload.get("interaction_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.url: Optional[str] = payload.get("url") + self.routing_properties: Optional[Dict[str, object]] = payload.get( + "routing_properties" + ) + + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[InteractionChannelParticipantContext] = None + + @property + def _proxy(self) -> "InteractionChannelParticipantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InteractionChannelParticipantContext for this InteractionChannelParticipantInstance + """ + if self._context is None: + self._context = InteractionChannelParticipantContext( + self._version, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def update( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> "InteractionChannelParticipantInstance": + """ + Update the InteractionChannelParticipantInstance + + :param status: + + :returns: The updated InteractionChannelParticipantInstance + """ + return self._proxy.update( + status=status, + ) + + async def update_async( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> "InteractionChannelParticipantInstance": + """ + Asynchronous coroutine to update the InteractionChannelParticipantInstance + + :param status: + + :returns: The updated InteractionChannelParticipantInstance + """ + return await self._proxy.update_async( + status=status, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.InteractionChannelParticipantInstance {}>".format( + context + ) + + +class InteractionChannelParticipantContext(InstanceContext): + + def __init__( + self, version: Version, interaction_sid: str, channel_sid: str, sid: str + ): + """ + Initialize the InteractionChannelParticipantContext + + :param version: Version that contains the resource + :param interaction_sid: The Interaction Sid for this channel. + :param channel_sid: The Channel Sid for this Participant. + :param sid: The unique string created by Twilio to identify an Interaction Channel resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = "/Interactions/{interaction_sid}/Channels/{channel_sid}/Participants/{sid}".format( + **self._solution + ) + + def update( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> InteractionChannelParticipantInstance: + """ + Update the InteractionChannelParticipantInstance + + :param status: + + :returns: The updated InteractionChannelParticipantInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, status: "InteractionChannelParticipantInstance.Status" + ) -> InteractionChannelParticipantInstance: + """ + Asynchronous coroutine to update the InteractionChannelParticipantInstance + + :param status: + + :returns: The updated InteractionChannelParticipantInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.InteractionChannelParticipantContext {}>".format( + context + ) + + +class InteractionChannelParticipantPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> InteractionChannelParticipantInstance: + """ + Build an instance of InteractionChannelParticipantInstance + + :param payload: Payload response from the API + """ + return InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InteractionChannelParticipantPage>" + + +class InteractionChannelParticipantList(ListResource): + + def __init__(self, version: Version, interaction_sid: str, channel_sid: str): + """ + Initialize the InteractionChannelParticipantList + + :param version: Version that contains the resource + :param interaction_sid: The Interaction Sid for this channel. + :param channel_sid: The Channel Sid for this Participant. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + } + self._uri = "/Interactions/{interaction_sid}/Channels/{channel_sid}/Participants".format( + **self._solution + ) + + def create( + self, + type: "InteractionChannelParticipantInstance.Type", + media_properties: object, + routing_properties: Union[object, object] = values.unset, + ) -> InteractionChannelParticipantInstance: + """ + Create the InteractionChannelParticipantInstance + + :param type: + :param media_properties: JSON representing the Media Properties for the new Participant. + :param routing_properties: Object representing the Routing Properties for the new Participant. + + :returns: The created InteractionChannelParticipantInstance + """ + + data = values.of( + { + "Type": type, + "MediaProperties": serialize.object(media_properties), + "RoutingProperties": serialize.object(routing_properties), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, + type: "InteractionChannelParticipantInstance.Type", + media_properties: object, + routing_properties: Union[object, object] = values.unset, + ) -> InteractionChannelParticipantInstance: + """ + Asynchronously create the InteractionChannelParticipantInstance + + :param type: + :param media_properties: JSON representing the Media Properties for the new Participant. + :param routing_properties: Object representing the Routing Properties for the new Participant. + + :returns: The created InteractionChannelParticipantInstance + """ + + data = values.of( + { + "Type": type, + "MediaProperties": serialize.object(media_properties), + "RoutingProperties": serialize.object(routing_properties), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionChannelParticipantInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InteractionChannelParticipantInstance]: + """ + Streams InteractionChannelParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InteractionChannelParticipantInstance]: + """ + Asynchronously streams InteractionChannelParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionChannelParticipantInstance]: + """ + Lists InteractionChannelParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionChannelParticipantInstance]: + """ + Asynchronously lists InteractionChannelParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InteractionChannelParticipantPage: + """ + Retrieve a single page of InteractionChannelParticipantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InteractionChannelParticipantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InteractionChannelParticipantPage( + self._version, response, self._solution + ) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InteractionChannelParticipantPage: + """ + Asynchronously retrieve a single page of InteractionChannelParticipantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InteractionChannelParticipantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InteractionChannelParticipantPage( + self._version, response, self._solution + ) + + def get_page(self, target_url: str) -> InteractionChannelParticipantPage: + """ + Retrieve a specific page of InteractionChannelParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InteractionChannelParticipantInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InteractionChannelParticipantPage( + self._version, response, self._solution + ) + + async def get_page_async( + self, target_url: str + ) -> InteractionChannelParticipantPage: + """ + Asynchronously retrieve a specific page of InteractionChannelParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InteractionChannelParticipantInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InteractionChannelParticipantPage( + self._version, response, self._solution + ) + + def get(self, sid: str) -> InteractionChannelParticipantContext: + """ + Constructs a InteractionChannelParticipantContext + + :param sid: The unique string created by Twilio to identify an Interaction Channel resource. + """ + return InteractionChannelParticipantContext( + self._version, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InteractionChannelParticipantContext: + """ + Constructs a InteractionChannelParticipantContext + + :param sid: The unique string created by Twilio to identify an Interaction Channel resource. + """ + return InteractionChannelParticipantContext( + self._version, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InteractionChannelParticipantList>" diff --git a/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_transfer.py b/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_transfer.py new file mode 100644 index 0000000000..04a5afacdb --- /dev/null +++ b/twilio/rest/flex_api/v1/interaction/interaction_channel/interaction_transfer.py @@ -0,0 +1,423 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class InteractionTransferInstance(InstanceResource): + + class TransferStatus(object): + ACTIVE = "active" + FAILED = "failed" + COMPLETED = "completed" + + class TransferType(object): + WARM = "warm" + COLD = "cold" + EXTERNAL = "external" + + """ + :ivar sid: The unique string created by Twilio to identify an Interaction Transfer resource. + :ivar instance_sid: The SID of the Instance associated with the Transfer. + :ivar account_sid: The SID of the Account that created the Transfer. + :ivar interaction_sid: The Interaction Sid for this channel. + :ivar channel_sid: The Channel Sid for this Transfer. + :ivar execution_sid: The Execution SID associated with the Transfer. + :ivar type: + :ivar status: + :ivar _from: The SID of the Participant initiating the Transfer. + :ivar to: The SID of the Participant receiving the Transfer. + :ivar note_sid: The SID of the Note associated with the Transfer. + :ivar summary_sid: The SID of the Summary associated with the Transfer. + :ivar date_created: The date and time when the Transfer was created. + :ivar date_updated: The date and time when the Transfer was last updated. + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + interaction_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.instance_sid: Optional[str] = payload.get("instance_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.interaction_sid: Optional[str] = payload.get("interaction_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.execution_sid: Optional[str] = payload.get("execution_sid") + self.type: Optional["InteractionTransferInstance.TransferType"] = payload.get( + "type" + ) + self.status: Optional["InteractionTransferInstance.TransferStatus"] = ( + payload.get("status") + ) + self._from: Optional[str] = payload.get("from") + self.to: Optional[str] = payload.get("to") + self.note_sid: Optional[str] = payload.get("note_sid") + self.summary_sid: Optional[str] = payload.get("summary_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[InteractionTransferContext] = None + + @property + def _proxy(self) -> "InteractionTransferContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InteractionTransferContext for this InteractionTransferInstance + """ + if self._context is None: + self._context = InteractionTransferContext( + self._version, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "InteractionTransferInstance": + """ + Fetch the InteractionTransferInstance + + + :returns: The fetched InteractionTransferInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InteractionTransferInstance": + """ + Asynchronous coroutine to fetch the InteractionTransferInstance + + + :returns: The fetched InteractionTransferInstance + """ + return await self._proxy.fetch_async() + + def update( + self, body: Union[object, object] = values.unset + ) -> "InteractionTransferInstance": + """ + Update the InteractionTransferInstance + + :param body: + + :returns: The updated InteractionTransferInstance + """ + return self._proxy.update( + body=body, + ) + + async def update_async( + self, body: Union[object, object] = values.unset + ) -> "InteractionTransferInstance": + """ + Asynchronous coroutine to update the InteractionTransferInstance + + :param body: + + :returns: The updated InteractionTransferInstance + """ + return await self._proxy.update_async( + body=body, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.InteractionTransferInstance {}>".format(context) + + +class InteractionTransferContext(InstanceContext): + + def __init__( + self, version: Version, interaction_sid: str, channel_sid: str, sid: str + ): + """ + Initialize the InteractionTransferContext + + :param version: Version that contains the resource + :param interaction_sid: The Interaction Sid for this channel. + :param channel_sid: The Channel Sid for this Transfer. + :param sid: The unique string created by Twilio to identify a Transfer resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = "/Interactions/{interaction_sid}/Channels/{channel_sid}/Transfers/{sid}".format( + **self._solution + ) + + def fetch(self) -> InteractionTransferInstance: + """ + Fetch the InteractionTransferInstance + + + :returns: The fetched InteractionTransferInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InteractionTransferInstance: + """ + Asynchronous coroutine to fetch the InteractionTransferInstance + + + :returns: The fetched InteractionTransferInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, body: Union[object, object] = values.unset + ) -> InteractionTransferInstance: + """ + Update the InteractionTransferInstance + + :param body: + + :returns: The updated InteractionTransferInstance + """ + data = body.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, body: Union[object, object] = values.unset + ) -> InteractionTransferInstance: + """ + Asynchronous coroutine to update the InteractionTransferInstance + + :param body: + + :returns: The updated InteractionTransferInstance + """ + data = body.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.InteractionTransferContext {}>".format(context) + + +class InteractionTransferList(ListResource): + + def __init__(self, version: Version, interaction_sid: str, channel_sid: str): + """ + Initialize the InteractionTransferList + + :param version: Version that contains the resource + :param interaction_sid: The Interaction Sid for the Interaction + :param channel_sid: The Channel Sid for the Channel. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "interaction_sid": interaction_sid, + "channel_sid": channel_sid, + } + self._uri = ( + "/Interactions/{interaction_sid}/Channels/{channel_sid}/Transfers".format( + **self._solution + ) + ) + + def create( + self, body: Union[object, object] = values.unset + ) -> InteractionTransferInstance: + """ + Create the InteractionTransferInstance + + :param body: + + :returns: The created InteractionTransferInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> InteractionTransferInstance: + """ + Asynchronously create the InteractionTransferInstance + + :param body: + + :returns: The created InteractionTransferInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InteractionTransferInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def get(self, sid: str) -> InteractionTransferContext: + """ + Constructs a InteractionTransferContext + + :param sid: The unique string created by Twilio to identify a Transfer resource. + """ + return InteractionTransferContext( + self._version, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InteractionTransferContext: + """ + Constructs a InteractionTransferContext + + :param sid: The unique string created by Twilio to identify a Transfer resource. + """ + return InteractionTransferContext( + self._version, + interaction_sid=self._solution["interaction_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.InteractionTransferList>" diff --git a/twilio/rest/flex_api/v1/plugin/__init__.py b/twilio/rest/flex_api/v1/plugin/__init__.py new file mode 100644 index 0000000000..2415c42710 --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin/__init__.py @@ -0,0 +1,707 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.flex_api.v1.plugin.plugin_versions import PluginVersionsList + + +class PluginInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Flex Plugin resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin resource and owns this resource. + :ivar unique_name: The name that uniquely identifies this Flex Plugin resource. + :ivar friendly_name: The friendly name this Flex Plugin resource. + :ivar description: A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long + :ivar archived: Whether the Flex Plugin is archived. The default value is false. + :ivar date_created: The date and time in GMT-7 when the Flex Plugin was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT-7 when the Flex Plugin was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin resource. + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.archived: Optional[bool] = payload.get("archived") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[PluginContext] = None + + @property + def _proxy(self) -> "PluginContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginContext for this PluginInstance + """ + if self._context is None: + self._context = PluginContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginInstance": + """ + Fetch the PluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginInstance + """ + return self._proxy.fetch( + flex_metadata=flex_metadata, + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginInstance": + """ + Asynchronous coroutine to fetch the PluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginInstance + """ + return await self._proxy.fetch_async( + flex_metadata=flex_metadata, + ) + + def update( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> "PluginInstance": + """ + Update the PluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you update to describe the plugin resource. It can be up to 500 characters long + + :returns: The updated PluginInstance + """ + return self._proxy.update( + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + + async def update_async( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> "PluginInstance": + """ + Asynchronous coroutine to update the PluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you update to describe the plugin resource. It can be up to 500 characters long + + :returns: The updated PluginInstance + """ + return await self._proxy.update_async( + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + + @property + def plugin_versions(self) -> PluginVersionsList: + """ + Access the plugin_versions + """ + return self._proxy.plugin_versions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.PluginInstance {}>".format(context) + + +class PluginContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PluginContext + + :param version: Version that contains the resource + :param sid: The SID of the Flex Plugin resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/PluginService/Plugins/{sid}".format(**self._solution) + + self._plugin_versions: Optional[PluginVersionsList] = None + + def fetch(self, flex_metadata: Union[str, object] = values.unset) -> PluginInstance: + """ + Fetch the PluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginInstance + """ + + data = values.of( + { + "Flex-Metadata": flex_metadata, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PluginInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginInstance: + """ + Asynchronous coroutine to fetch the PluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginInstance + """ + + data = values.of( + { + "Flex-Metadata": flex_metadata, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PluginInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> PluginInstance: + """ + Update the PluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you update to describe the plugin resource. It can be up to 500 characters long + + :returns: The updated PluginInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Description": description, + } + ) + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> PluginInstance: + """ + Asynchronous coroutine to update the PluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you update to describe the plugin resource. It can be up to 500 characters long + + :returns: The updated PluginInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Description": description, + } + ) + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def plugin_versions(self) -> PluginVersionsList: + """ + Access the plugin_versions + """ + if self._plugin_versions is None: + self._plugin_versions = PluginVersionsList( + self._version, + self._solution["sid"], + ) + return self._plugin_versions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.PluginContext {}>".format(context) + + +class PluginPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PluginInstance: + """ + Build an instance of PluginInstance + + :param payload: Payload response from the API + """ + return PluginInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.PluginPage>" + + +class PluginList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PluginList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/PluginService/Plugins" + + def create( + self, + unique_name: str, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> PluginInstance: + """ + Create the PluginInstance + + :param unique_name: The Flex Plugin's unique name. + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long + + :returns: The created PluginInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "Description": description, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginInstance(self._version, payload) + + async def create_async( + self, + unique_name: str, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> PluginInstance: + """ + Asynchronously create the PluginInstance + + :param unique_name: The Flex Plugin's unique name. + :param flex_metadata: The Flex-Metadata HTTP request header + :param friendly_name: The Flex Plugin's friendly name. + :param description: A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long + + :returns: The created PluginInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "Description": description, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginInstance(self._version, payload) + + def stream( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PluginInstance]: + """ + Streams PluginInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(flex_metadata=flex_metadata, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PluginInstance]: + """ + Asynchronously streams PluginInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginInstance]: + """ + Lists PluginInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginInstance]: + """ + Asynchronously lists PluginInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PluginPage: + """ + Retrieve a single page of PluginInstance records from the API. + Request is executed immediately + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PluginInstance + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PluginPage(self._version, response) + + async def page_async( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PluginPage: + """ + Asynchronously retrieve a single page of PluginInstance records from the API. + Request is executed immediately + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PluginInstance + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PluginPage(self._version, response) + + def get_page(self, target_url: str) -> PluginPage: + """ + Retrieve a specific page of PluginInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PluginPage(self._version, response) + + async def get_page_async(self, target_url: str) -> PluginPage: + """ + Asynchronously retrieve a specific page of PluginInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PluginPage(self._version, response) + + def get(self, sid: str) -> PluginContext: + """ + Constructs a PluginContext + + :param sid: The SID of the Flex Plugin resource to update. + """ + return PluginContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PluginContext: + """ + Constructs a PluginContext + + :param sid: The SID of the Flex Plugin resource to update. + """ + return PluginContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.PluginList>" diff --git a/twilio/rest/flex_api/v1/plugin/plugin_versions.py b/twilio/rest/flex_api/v1/plugin/plugin_versions.py new file mode 100644 index 0000000000..4d66ef572b --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin/plugin_versions.py @@ -0,0 +1,612 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PluginVersionsInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Flex Plugin Version resource. + :ivar plugin_sid: The SID of the Flex Plugin resource this Flex Plugin Version belongs to. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin Version resource and owns this resource. + :ivar version: The unique version of this Flex Plugin Version. + :ivar plugin_url: The URL of where the Flex Plugin Version JavaScript bundle is hosted on. + :ivar changelog: A changelog that describes the changes this Flex Plugin Version brings. + :ivar private: Whether the Flex Plugin Version is validated. The default value is false. + :ivar archived: Whether the Flex Plugin Version is archived. The default value is false. + :ivar validated: + :ivar date_created: The date and time in GMT when the Flex Plugin Version was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin Version resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + plugin_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.plugin_sid: Optional[str] = payload.get("plugin_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.version: Optional[str] = payload.get("version") + self.plugin_url: Optional[str] = payload.get("plugin_url") + self.changelog: Optional[str] = payload.get("changelog") + self.private: Optional[bool] = payload.get("private") + self.archived: Optional[bool] = payload.get("archived") + self.validated: Optional[bool] = payload.get("validated") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "plugin_sid": plugin_sid, + "sid": sid or self.sid, + } + self._context: Optional[PluginVersionsContext] = None + + @property + def _proxy(self) -> "PluginVersionsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginVersionsContext for this PluginVersionsInstance + """ + if self._context is None: + self._context = PluginVersionsContext( + self._version, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginVersionsInstance": + """ + Fetch the PluginVersionsInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginVersionsInstance + """ + return self._proxy.fetch( + flex_metadata=flex_metadata, + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginVersionsInstance": + """ + Asynchronous coroutine to fetch the PluginVersionsInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginVersionsInstance + """ + return await self._proxy.fetch_async( + flex_metadata=flex_metadata, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.PluginVersionsInstance {}>".format(context) + + +class PluginVersionsContext(InstanceContext): + + def __init__(self, version: Version, plugin_sid: str, sid: str): + """ + Initialize the PluginVersionsContext + + :param version: Version that contains the resource + :param plugin_sid: The SID of the Flex Plugin the resource to belongs to. + :param sid: The SID of the Flex Plugin Version resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "plugin_sid": plugin_sid, + "sid": sid, + } + self._uri = "/PluginService/Plugins/{plugin_sid}/Versions/{sid}".format( + **self._solution + ) + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginVersionsInstance: + """ + Fetch the PluginVersionsInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginVersionsInstance + """ + + data = values.of( + { + "Flex-Metadata": flex_metadata, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PluginVersionsInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginVersionsInstance: + """ + Asynchronous coroutine to fetch the PluginVersionsInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginVersionsInstance + """ + + data = values.of( + { + "Flex-Metadata": flex_metadata, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PluginVersionsInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.PluginVersionsContext {}>".format(context) + + +class PluginVersionsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PluginVersionsInstance: + """ + Build an instance of PluginVersionsInstance + + :param payload: Payload response from the API + """ + return PluginVersionsInstance( + self._version, payload, plugin_sid=self._solution["plugin_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.PluginVersionsPage>" + + +class PluginVersionsList(ListResource): + + def __init__(self, version: Version, plugin_sid: str): + """ + Initialize the PluginVersionsList + + :param version: Version that contains the resource + :param plugin_sid: The SID of the Flex Plugin the resource to belongs to. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "plugin_sid": plugin_sid, + } + self._uri = "/PluginService/Plugins/{plugin_sid}/Versions".format( + **self._solution + ) + + def create( + self, + version: str, + plugin_url: str, + flex_metadata: Union[str, object] = values.unset, + changelog: Union[str, object] = values.unset, + private: Union[bool, object] = values.unset, + cli_version: Union[str, object] = values.unset, + validate_status: Union[str, object] = values.unset, + ) -> PluginVersionsInstance: + """ + Create the PluginVersionsInstance + + :param version: The Flex Plugin Version's version. + :param plugin_url: The URL of the Flex Plugin Version bundle + :param flex_metadata: The Flex-Metadata HTTP request header + :param changelog: The changelog of the Flex Plugin Version. + :param private: Whether this Flex Plugin Version requires authorization. + :param cli_version: The version of Flex Plugins CLI used to create this plugin + :param validate_status: The validation status of the plugin, indicating whether it has been validated + + :returns: The created PluginVersionsInstance + """ + + data = values.of( + { + "Version": version, + "PluginUrl": plugin_url, + "Changelog": changelog, + "Private": serialize.boolean_to_string(private), + "CliVersion": cli_version, + "ValidateStatus": validate_status, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginVersionsInstance( + self._version, payload, plugin_sid=self._solution["plugin_sid"] + ) + + async def create_async( + self, + version: str, + plugin_url: str, + flex_metadata: Union[str, object] = values.unset, + changelog: Union[str, object] = values.unset, + private: Union[bool, object] = values.unset, + cli_version: Union[str, object] = values.unset, + validate_status: Union[str, object] = values.unset, + ) -> PluginVersionsInstance: + """ + Asynchronously create the PluginVersionsInstance + + :param version: The Flex Plugin Version's version. + :param plugin_url: The URL of the Flex Plugin Version bundle + :param flex_metadata: The Flex-Metadata HTTP request header + :param changelog: The changelog of the Flex Plugin Version. + :param private: Whether this Flex Plugin Version requires authorization. + :param cli_version: The version of Flex Plugins CLI used to create this plugin + :param validate_status: The validation status of the plugin, indicating whether it has been validated + + :returns: The created PluginVersionsInstance + """ + + data = values.of( + { + "Version": version, + "PluginUrl": plugin_url, + "Changelog": changelog, + "Private": serialize.boolean_to_string(private), + "CliVersion": cli_version, + "ValidateStatus": validate_status, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginVersionsInstance( + self._version, payload, plugin_sid=self._solution["plugin_sid"] + ) + + def stream( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PluginVersionsInstance]: + """ + Streams PluginVersionsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(flex_metadata=flex_metadata, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PluginVersionsInstance]: + """ + Asynchronously streams PluginVersionsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginVersionsInstance]: + """ + Lists PluginVersionsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginVersionsInstance]: + """ + Asynchronously lists PluginVersionsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PluginVersionsPage: + """ + Retrieve a single page of PluginVersionsInstance records from the API. + Request is executed immediately + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PluginVersionsInstance + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PluginVersionsPage(self._version, response, self._solution) + + async def page_async( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PluginVersionsPage: + """ + Asynchronously retrieve a single page of PluginVersionsInstance records from the API. + Request is executed immediately + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PluginVersionsInstance + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PluginVersionsPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> PluginVersionsPage: + """ + Retrieve a specific page of PluginVersionsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginVersionsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PluginVersionsPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> PluginVersionsPage: + """ + Asynchronously retrieve a specific page of PluginVersionsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginVersionsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PluginVersionsPage(self._version, response, self._solution) + + def get(self, sid: str) -> PluginVersionsContext: + """ + Constructs a PluginVersionsContext + + :param sid: The SID of the Flex Plugin Version resource to fetch. + """ + return PluginVersionsContext( + self._version, plugin_sid=self._solution["plugin_sid"], sid=sid + ) + + def __call__(self, sid: str) -> PluginVersionsContext: + """ + Constructs a PluginVersionsContext + + :param sid: The SID of the Flex Plugin Version resource to fetch. + """ + return PluginVersionsContext( + self._version, plugin_sid=self._solution["plugin_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.PluginVersionsList>" diff --git a/twilio/rest/flex_api/v1/plugin_archive.py b/twilio/rest/flex_api/v1/plugin_archive.py new file mode 100644 index 0000000000..e7f526a919 --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin_archive.py @@ -0,0 +1,230 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PluginArchiveInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Flex Plugin resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin resource and owns this resource. + :ivar unique_name: The name that uniquely identifies this Flex Plugin resource. + :ivar friendly_name: The friendly name this Flex Plugin resource. + :ivar description: A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long + :ivar archived: Whether the Flex Plugin is archived. The default value is false. + :ivar date_created: The date and time in GMT when the Flex Plugin was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Flex Plugin was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.archived: Optional[bool] = payload.get("archived") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[PluginArchiveContext] = None + + @property + def _proxy(self) -> "PluginArchiveContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginArchiveContext for this PluginArchiveInstance + """ + if self._context is None: + self._context = PluginArchiveContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def update( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginArchiveInstance": + """ + Update the PluginArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginArchiveInstance + """ + return self._proxy.update( + flex_metadata=flex_metadata, + ) + + async def update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginArchiveInstance": + """ + Asynchronous coroutine to update the PluginArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginArchiveInstance + """ + return await self._proxy.update_async( + flex_metadata=flex_metadata, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.PluginArchiveInstance {}>".format(context) + + +class PluginArchiveContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PluginArchiveContext + + :param version: Version that contains the resource + :param sid: The SID of the Flex Plugin resource to archive. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/PluginService/Plugins/{sid}/Archive".format(**self._solution) + + def update( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginArchiveInstance: + """ + Update the PluginArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginArchiveInstance + """ + + data = values.of({}) + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginArchiveInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginArchiveInstance: + """ + Asynchronous coroutine to update the PluginArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginArchiveInstance + """ + + data = values.of({}) + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginArchiveInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.PluginArchiveContext {}>".format(context) + + +class PluginArchiveList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PluginArchiveList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sid: str) -> PluginArchiveContext: + """ + Constructs a PluginArchiveContext + + :param sid: The SID of the Flex Plugin resource to archive. + """ + return PluginArchiveContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PluginArchiveContext: + """ + Constructs a PluginArchiveContext + + :param sid: The SID of the Flex Plugin resource to archive. + """ + return PluginArchiveContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.PluginArchiveList>" diff --git a/twilio/rest/flex_api/v1/plugin_configuration/__init__.py b/twilio/rest/flex_api/v1/plugin_configuration/__init__.py new file mode 100644 index 0000000000..b17d697e3b --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin_configuration/__init__.py @@ -0,0 +1,583 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.flex_api.v1.plugin_configuration.configured_plugin import ( + ConfiguredPluginList, +) + + +class PluginConfigurationInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Flex Plugin Configuration resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin Configuration resource and owns this resource. + :ivar name: The name of this Flex Plugin Configuration. + :ivar description: The description of the Flex Plugin Configuration resource. + :ivar archived: Whether the Flex Plugin Configuration is archived. The default value is false. + :ivar date_created: The date and time in GMT when the Flex Plugin Configuration was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin Configuration resource. + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.name: Optional[str] = payload.get("name") + self.description: Optional[str] = payload.get("description") + self.archived: Optional[bool] = payload.get("archived") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[PluginConfigurationContext] = None + + @property + def _proxy(self) -> "PluginConfigurationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginConfigurationContext for this PluginConfigurationInstance + """ + if self._context is None: + self._context = PluginConfigurationContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginConfigurationInstance": + """ + Fetch the PluginConfigurationInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginConfigurationInstance + """ + return self._proxy.fetch( + flex_metadata=flex_metadata, + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginConfigurationInstance": + """ + Asynchronous coroutine to fetch the PluginConfigurationInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginConfigurationInstance + """ + return await self._proxy.fetch_async( + flex_metadata=flex_metadata, + ) + + @property + def plugins(self) -> ConfiguredPluginList: + """ + Access the plugins + """ + return self._proxy.plugins + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.PluginConfigurationInstance {}>".format(context) + + +class PluginConfigurationContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PluginConfigurationContext + + :param version: Version that contains the resource + :param sid: The SID of the Flex Plugin Configuration resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/PluginService/Configurations/{sid}".format(**self._solution) + + self._plugins: Optional[ConfiguredPluginList] = None + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginConfigurationInstance: + """ + Fetch the PluginConfigurationInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginConfigurationInstance + """ + + data = values.of( + { + "Flex-Metadata": flex_metadata, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PluginConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginConfigurationInstance: + """ + Asynchronous coroutine to fetch the PluginConfigurationInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginConfigurationInstance + """ + + data = values.of( + { + "Flex-Metadata": flex_metadata, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PluginConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + @property + def plugins(self) -> ConfiguredPluginList: + """ + Access the plugins + """ + if self._plugins is None: + self._plugins = ConfiguredPluginList( + self._version, + self._solution["sid"], + ) + return self._plugins + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.PluginConfigurationContext {}>".format(context) + + +class PluginConfigurationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PluginConfigurationInstance: + """ + Build an instance of PluginConfigurationInstance + + :param payload: Payload response from the API + """ + return PluginConfigurationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.PluginConfigurationPage>" + + +class PluginConfigurationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PluginConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/PluginService/Configurations" + + def create( + self, + name: str, + flex_metadata: Union[str, object] = values.unset, + plugins: Union[List[object], object] = values.unset, + description: Union[str, object] = values.unset, + ) -> PluginConfigurationInstance: + """ + Create the PluginConfigurationInstance + + :param name: The Flex Plugin Configuration's name. + :param flex_metadata: The Flex-Metadata HTTP request header + :param plugins: A list of objects that describe the plugin versions included in the configuration. Each object contains the sid of the plugin version. + :param description: The Flex Plugin Configuration's description. + + :returns: The created PluginConfigurationInstance + """ + + data = values.of( + { + "Name": name, + "Plugins": serialize.map(plugins, lambda e: serialize.object(e)), + "Description": description, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginConfigurationInstance(self._version, payload) + + async def create_async( + self, + name: str, + flex_metadata: Union[str, object] = values.unset, + plugins: Union[List[object], object] = values.unset, + description: Union[str, object] = values.unset, + ) -> PluginConfigurationInstance: + """ + Asynchronously create the PluginConfigurationInstance + + :param name: The Flex Plugin Configuration's name. + :param flex_metadata: The Flex-Metadata HTTP request header + :param plugins: A list of objects that describe the plugin versions included in the configuration. Each object contains the sid of the plugin version. + :param description: The Flex Plugin Configuration's description. + + :returns: The created PluginConfigurationInstance + """ + + data = values.of( + { + "Name": name, + "Plugins": serialize.map(plugins, lambda e: serialize.object(e)), + "Description": description, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginConfigurationInstance(self._version, payload) + + def stream( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PluginConfigurationInstance]: + """ + Streams PluginConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(flex_metadata=flex_metadata, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PluginConfigurationInstance]: + """ + Asynchronously streams PluginConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginConfigurationInstance]: + """ + Lists PluginConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginConfigurationInstance]: + """ + Asynchronously lists PluginConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PluginConfigurationPage: + """ + Retrieve a single page of PluginConfigurationInstance records from the API. + Request is executed immediately + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PluginConfigurationInstance + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PluginConfigurationPage(self._version, response) + + async def page_async( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PluginConfigurationPage: + """ + Asynchronously retrieve a single page of PluginConfigurationInstance records from the API. + Request is executed immediately + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PluginConfigurationInstance + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PluginConfigurationPage(self._version, response) + + def get_page(self, target_url: str) -> PluginConfigurationPage: + """ + Retrieve a specific page of PluginConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginConfigurationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PluginConfigurationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> PluginConfigurationPage: + """ + Asynchronously retrieve a specific page of PluginConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginConfigurationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PluginConfigurationPage(self._version, response) + + def get(self, sid: str) -> PluginConfigurationContext: + """ + Constructs a PluginConfigurationContext + + :param sid: The SID of the Flex Plugin Configuration resource to fetch. + """ + return PluginConfigurationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PluginConfigurationContext: + """ + Constructs a PluginConfigurationContext + + :param sid: The SID of the Flex Plugin Configuration resource to fetch. + """ + return PluginConfigurationContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.PluginConfigurationList>" diff --git a/twilio/rest/flex_api/v1/plugin_configuration/configured_plugin.py b/twilio/rest/flex_api/v1/plugin_configuration/configured_plugin.py new file mode 100644 index 0000000000..062a7db7b4 --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin_configuration/configured_plugin.py @@ -0,0 +1,524 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ConfiguredPluginInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the Flex Plugin resource is installed for. + :ivar configuration_sid: The SID of the Flex Plugin Configuration that this Flex Plugin belongs to. + :ivar plugin_sid: The SID of the Flex Plugin. + :ivar plugin_version_sid: The SID of the Flex Plugin Version. + :ivar phase: The phase this Flex Plugin would initialize at runtime. + :ivar plugin_url: The URL of where the Flex Plugin Version JavaScript bundle is hosted on. + :ivar unique_name: The name that uniquely identifies this Flex Plugin resource. + :ivar friendly_name: The friendly name of this Flex Plugin resource. + :ivar description: A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long + :ivar plugin_archived: Whether the Flex Plugin is archived. The default value is false. + :ivar version: The latest version of this Flex Plugin Version. + :ivar changelog: A changelog that describes the changes this Flex Plugin Version brings. + :ivar plugin_version_archived: Whether the Flex Plugin Version is archived. The default value is false. + :ivar private: Whether to validate the request is authorized to access the Flex Plugin Version. + :ivar date_created: The date and time in GMT when the Flex Plugin was installed specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + configuration_sid: str, + plugin_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.configuration_sid: Optional[str] = payload.get("configuration_sid") + self.plugin_sid: Optional[str] = payload.get("plugin_sid") + self.plugin_version_sid: Optional[str] = payload.get("plugin_version_sid") + self.phase: Optional[int] = deserialize.integer(payload.get("phase")) + self.plugin_url: Optional[str] = payload.get("plugin_url") + self.unique_name: Optional[str] = payload.get("unique_name") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.plugin_archived: Optional[bool] = payload.get("plugin_archived") + self.version: Optional[str] = payload.get("version") + self.changelog: Optional[str] = payload.get("changelog") + self.plugin_version_archived: Optional[bool] = payload.get( + "plugin_version_archived" + ) + self.private: Optional[bool] = payload.get("private") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "configuration_sid": configuration_sid, + "plugin_sid": plugin_sid or self.plugin_sid, + } + self._context: Optional[ConfiguredPluginContext] = None + + @property + def _proxy(self) -> "ConfiguredPluginContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConfiguredPluginContext for this ConfiguredPluginInstance + """ + if self._context is None: + self._context = ConfiguredPluginContext( + self._version, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=self._solution["plugin_sid"], + ) + return self._context + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> "ConfiguredPluginInstance": + """ + Fetch the ConfiguredPluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched ConfiguredPluginInstance + """ + return self._proxy.fetch( + flex_metadata=flex_metadata, + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "ConfiguredPluginInstance": + """ + Asynchronous coroutine to fetch the ConfiguredPluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched ConfiguredPluginInstance + """ + return await self._proxy.fetch_async( + flex_metadata=flex_metadata, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.ConfiguredPluginInstance {}>".format(context) + + +class ConfiguredPluginContext(InstanceContext): + + def __init__(self, version: Version, configuration_sid: str, plugin_sid: str): + """ + Initialize the ConfiguredPluginContext + + :param version: Version that contains the resource + :param configuration_sid: The SID of the Flex Plugin Configuration the resource to belongs to. + :param plugin_sid: The unique string that we created to identify the Flex Plugin resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "configuration_sid": configuration_sid, + "plugin_sid": plugin_sid, + } + self._uri = "/PluginService/Configurations/{configuration_sid}/Plugins/{plugin_sid}".format( + **self._solution + ) + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> ConfiguredPluginInstance: + """ + Fetch the ConfiguredPluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched ConfiguredPluginInstance + """ + + data = values.of( + { + "Flex-Metadata": flex_metadata, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return ConfiguredPluginInstance( + self._version, + payload, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=self._solution["plugin_sid"], + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> ConfiguredPluginInstance: + """ + Asynchronous coroutine to fetch the ConfiguredPluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched ConfiguredPluginInstance + """ + + data = values.of( + { + "Flex-Metadata": flex_metadata, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return ConfiguredPluginInstance( + self._version, + payload, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=self._solution["plugin_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.ConfiguredPluginContext {}>".format(context) + + +class ConfiguredPluginPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConfiguredPluginInstance: + """ + Build an instance of ConfiguredPluginInstance + + :param payload: Payload response from the API + """ + return ConfiguredPluginInstance( + self._version, + payload, + configuration_sid=self._solution["configuration_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.ConfiguredPluginPage>" + + +class ConfiguredPluginList(ListResource): + + def __init__(self, version: Version, configuration_sid: str): + """ + Initialize the ConfiguredPluginList + + :param version: Version that contains the resource + :param configuration_sid: The SID of the Flex Plugin Configuration the resource to belongs to. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "configuration_sid": configuration_sid, + } + self._uri = "/PluginService/Configurations/{configuration_sid}/Plugins".format( + **self._solution + ) + + def stream( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConfiguredPluginInstance]: + """ + Streams ConfiguredPluginInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(flex_metadata=flex_metadata, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConfiguredPluginInstance]: + """ + Asynchronously streams ConfiguredPluginInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConfiguredPluginInstance]: + """ + Lists ConfiguredPluginInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConfiguredPluginInstance]: + """ + Asynchronously lists ConfiguredPluginInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConfiguredPluginPage: + """ + Retrieve a single page of ConfiguredPluginInstance records from the API. + Request is executed immediately + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConfiguredPluginInstance + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConfiguredPluginPage(self._version, response, self._solution) + + async def page_async( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConfiguredPluginPage: + """ + Asynchronously retrieve a single page of ConfiguredPluginInstance records from the API. + Request is executed immediately + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConfiguredPluginInstance + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConfiguredPluginPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ConfiguredPluginPage: + """ + Retrieve a specific page of ConfiguredPluginInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConfiguredPluginInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConfiguredPluginPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ConfiguredPluginPage: + """ + Asynchronously retrieve a specific page of ConfiguredPluginInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConfiguredPluginInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConfiguredPluginPage(self._version, response, self._solution) + + def get(self, plugin_sid: str) -> ConfiguredPluginContext: + """ + Constructs a ConfiguredPluginContext + + :param plugin_sid: The unique string that we created to identify the Flex Plugin resource. + """ + return ConfiguredPluginContext( + self._version, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=plugin_sid, + ) + + def __call__(self, plugin_sid: str) -> ConfiguredPluginContext: + """ + Constructs a ConfiguredPluginContext + + :param plugin_sid: The unique string that we created to identify the Flex Plugin resource. + """ + return ConfiguredPluginContext( + self._version, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=plugin_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.ConfiguredPluginList>" diff --git a/twilio/rest/flex_api/v1/plugin_configuration_archive.py b/twilio/rest/flex_api/v1/plugin_configuration_archive.py new file mode 100644 index 0000000000..3fec073333 --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin_configuration_archive.py @@ -0,0 +1,234 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PluginConfigurationArchiveInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Flex Plugin Configuration resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin Configuration resource and owns this resource. + :ivar name: The name of this Flex Plugin Configuration. + :ivar description: The description of the Flex Plugin Configuration resource. + :ivar archived: Whether the Flex Plugin Configuration is archived. The default value is false. + :ivar date_created: The date and time in GMT when the Flex Plugin Configuration was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin Configuration resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.name: Optional[str] = payload.get("name") + self.description: Optional[str] = payload.get("description") + self.archived: Optional[bool] = payload.get("archived") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[PluginConfigurationArchiveContext] = None + + @property + def _proxy(self) -> "PluginConfigurationArchiveContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginConfigurationArchiveContext for this PluginConfigurationArchiveInstance + """ + if self._context is None: + self._context = PluginConfigurationArchiveContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def update( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginConfigurationArchiveInstance": + """ + Update the PluginConfigurationArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginConfigurationArchiveInstance + """ + return self._proxy.update( + flex_metadata=flex_metadata, + ) + + async def update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginConfigurationArchiveInstance": + """ + Asynchronous coroutine to update the PluginConfigurationArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginConfigurationArchiveInstance + """ + return await self._proxy.update_async( + flex_metadata=flex_metadata, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.PluginConfigurationArchiveInstance {}>".format( + context + ) + + +class PluginConfigurationArchiveContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PluginConfigurationArchiveContext + + :param version: Version that contains the resource + :param sid: The SID of the Flex Plugin Configuration resource to archive. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/PluginService/Configurations/{sid}/Archive".format( + **self._solution + ) + + def update( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginConfigurationArchiveInstance: + """ + Update the PluginConfigurationArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginConfigurationArchiveInstance + """ + + data = values.of({}) + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginConfigurationArchiveInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginConfigurationArchiveInstance: + """ + Asynchronous coroutine to update the PluginConfigurationArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginConfigurationArchiveInstance + """ + + data = values.of({}) + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginConfigurationArchiveInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.PluginConfigurationArchiveContext {}>".format( + context + ) + + +class PluginConfigurationArchiveList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PluginConfigurationArchiveList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sid: str) -> PluginConfigurationArchiveContext: + """ + Constructs a PluginConfigurationArchiveContext + + :param sid: The SID of the Flex Plugin Configuration resource to archive. + """ + return PluginConfigurationArchiveContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PluginConfigurationArchiveContext: + """ + Constructs a PluginConfigurationArchiveContext + + :param sid: The SID of the Flex Plugin Configuration resource to archive. + """ + return PluginConfigurationArchiveContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.PluginConfigurationArchiveList>" diff --git a/twilio/rest/flex_api/v1/plugin_release.py b/twilio/rest/flex_api/v1/plugin_release.py new file mode 100644 index 0000000000..0694b05f8b --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin_release.py @@ -0,0 +1,537 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PluginReleaseInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Plugin Release resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Plugin Release resource and owns this resource. + :ivar configuration_sid: The SID of the Plugin Configuration resource to release. + :ivar date_created: The date and time in GMT when the Flex Plugin Release was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Plugin Release resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.configuration_sid: Optional[str] = payload.get("configuration_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[PluginReleaseContext] = None + + @property + def _proxy(self) -> "PluginReleaseContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginReleaseContext for this PluginReleaseInstance + """ + if self._context is None: + self._context = PluginReleaseContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginReleaseInstance": + """ + Fetch the PluginReleaseInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginReleaseInstance + """ + return self._proxy.fetch( + flex_metadata=flex_metadata, + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginReleaseInstance": + """ + Asynchronous coroutine to fetch the PluginReleaseInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginReleaseInstance + """ + return await self._proxy.fetch_async( + flex_metadata=flex_metadata, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.PluginReleaseInstance {}>".format(context) + + +class PluginReleaseContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PluginReleaseContext + + :param version: Version that contains the resource + :param sid: The SID of the Flex Plugin Release resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/PluginService/Releases/{sid}".format(**self._solution) + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginReleaseInstance: + """ + Fetch the PluginReleaseInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginReleaseInstance + """ + + data = values.of( + { + "Flex-Metadata": flex_metadata, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PluginReleaseInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginReleaseInstance: + """ + Asynchronous coroutine to fetch the PluginReleaseInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginReleaseInstance + """ + + data = values.of( + { + "Flex-Metadata": flex_metadata, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PluginReleaseInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.PluginReleaseContext {}>".format(context) + + +class PluginReleasePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PluginReleaseInstance: + """ + Build an instance of PluginReleaseInstance + + :param payload: Payload response from the API + """ + return PluginReleaseInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.PluginReleasePage>" + + +class PluginReleaseList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PluginReleaseList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/PluginService/Releases" + + def create( + self, configuration_id: str, flex_metadata: Union[str, object] = values.unset + ) -> PluginReleaseInstance: + """ + Create the PluginReleaseInstance + + :param configuration_id: The SID or the Version of the Flex Plugin Configuration to release. + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The created PluginReleaseInstance + """ + + data = values.of( + { + "ConfigurationId": configuration_id, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginReleaseInstance(self._version, payload) + + async def create_async( + self, configuration_id: str, flex_metadata: Union[str, object] = values.unset + ) -> PluginReleaseInstance: + """ + Asynchronously create the PluginReleaseInstance + + :param configuration_id: The SID or the Version of the Flex Plugin Configuration to release. + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The created PluginReleaseInstance + """ + + data = values.of( + { + "ConfigurationId": configuration_id, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginReleaseInstance(self._version, payload) + + def stream( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PluginReleaseInstance]: + """ + Streams PluginReleaseInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(flex_metadata=flex_metadata, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PluginReleaseInstance]: + """ + Asynchronously streams PluginReleaseInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginReleaseInstance]: + """ + Lists PluginReleaseInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginReleaseInstance]: + """ + Asynchronously lists PluginReleaseInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str flex_metadata: The Flex-Metadata HTTP request header + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PluginReleasePage: + """ + Retrieve a single page of PluginReleaseInstance records from the API. + Request is executed immediately + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PluginReleaseInstance + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PluginReleasePage(self._version, response) + + async def page_async( + self, + flex_metadata: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PluginReleasePage: + """ + Asynchronously retrieve a single page of PluginReleaseInstance records from the API. + Request is executed immediately + + :param flex_metadata: The Flex-Metadata HTTP request header + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PluginReleaseInstance + """ + data = values.of( + { + "Flex-Metadata": flex_metadata, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PluginReleasePage(self._version, response) + + def get_page(self, target_url: str) -> PluginReleasePage: + """ + Retrieve a specific page of PluginReleaseInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginReleaseInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PluginReleasePage(self._version, response) + + async def get_page_async(self, target_url: str) -> PluginReleasePage: + """ + Asynchronously retrieve a specific page of PluginReleaseInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginReleaseInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PluginReleasePage(self._version, response) + + def get(self, sid: str) -> PluginReleaseContext: + """ + Constructs a PluginReleaseContext + + :param sid: The SID of the Flex Plugin Release resource to fetch. + """ + return PluginReleaseContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PluginReleaseContext: + """ + Constructs a PluginReleaseContext + + :param sid: The SID of the Flex Plugin Release resource to fetch. + """ + return PluginReleaseContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.PluginReleaseList>" diff --git a/twilio/rest/flex_api/v1/plugin_version_archive.py b/twilio/rest/flex_api/v1/plugin_version_archive.py new file mode 100644 index 0000000000..be169d4d64 --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin_version_archive.py @@ -0,0 +1,256 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PluginVersionArchiveInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Flex Plugin Version resource. + :ivar plugin_sid: The SID of the Flex Plugin resource this Flex Plugin Version belongs to. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin Version resource and owns this resource. + :ivar version: The unique version of this Flex Plugin Version. + :ivar plugin_url: The URL of where the Flex Plugin Version JavaScript bundle is hosted on. + :ivar changelog: A changelog that describes the changes this Flex Plugin Version brings. + :ivar private: Whether to inject credentials while accessing this Plugin Version. The default value is false. + :ivar archived: Whether the Flex Plugin Version is archived. The default value is false. + :ivar date_created: The date and time in GMT when the Flex Plugin Version was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin Version resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + plugin_sid: Optional[str] = None, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.plugin_sid: Optional[str] = payload.get("plugin_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.version: Optional[str] = payload.get("version") + self.plugin_url: Optional[str] = payload.get("plugin_url") + self.changelog: Optional[str] = payload.get("changelog") + self.private: Optional[bool] = payload.get("private") + self.archived: Optional[bool] = payload.get("archived") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "plugin_sid": plugin_sid or self.plugin_sid, + "sid": sid or self.sid, + } + self._context: Optional[PluginVersionArchiveContext] = None + + @property + def _proxy(self) -> "PluginVersionArchiveContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginVersionArchiveContext for this PluginVersionArchiveInstance + """ + if self._context is None: + self._context = PluginVersionArchiveContext( + self._version, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + return self._context + + def update( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginVersionArchiveInstance": + """ + Update the PluginVersionArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginVersionArchiveInstance + """ + return self._proxy.update( + flex_metadata=flex_metadata, + ) + + async def update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginVersionArchiveInstance": + """ + Asynchronous coroutine to update the PluginVersionArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginVersionArchiveInstance + """ + return await self._proxy.update_async( + flex_metadata=flex_metadata, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.PluginVersionArchiveInstance {}>".format(context) + + +class PluginVersionArchiveContext(InstanceContext): + + def __init__(self, version: Version, plugin_sid: str, sid: str): + """ + Initialize the PluginVersionArchiveContext + + :param version: Version that contains the resource + :param plugin_sid: The SID of the Flex Plugin the resource to belongs to. + :param sid: The SID of the Flex Plugin Version resource to archive. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "plugin_sid": plugin_sid, + "sid": sid, + } + self._uri = "/PluginService/Plugins/{plugin_sid}/Versions/{sid}/Archive".format( + **self._solution + ) + + def update( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginVersionArchiveInstance: + """ + Update the PluginVersionArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginVersionArchiveInstance + """ + + data = values.of({}) + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginVersionArchiveInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> PluginVersionArchiveInstance: + """ + Asynchronous coroutine to update the PluginVersionArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginVersionArchiveInstance + """ + + data = values.of({}) + headers = values.of({}) + + if not ( + flex_metadata is values.unset + or (isinstance(flex_metadata, str) and not flex_metadata) + ): + headers["Flex-Metadata"] = flex_metadata + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PluginVersionArchiveInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.PluginVersionArchiveContext {}>".format(context) + + +class PluginVersionArchiveList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PluginVersionArchiveList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, plugin_sid: str, sid: str) -> PluginVersionArchiveContext: + """ + Constructs a PluginVersionArchiveContext + + :param plugin_sid: The SID of the Flex Plugin the resource to belongs to. + :param sid: The SID of the Flex Plugin Version resource to archive. + """ + return PluginVersionArchiveContext( + self._version, plugin_sid=plugin_sid, sid=sid + ) + + def __call__(self, plugin_sid: str, sid: str) -> PluginVersionArchiveContext: + """ + Constructs a PluginVersionArchiveContext + + :param plugin_sid: The SID of the Flex Plugin the resource to belongs to. + :param sid: The SID of the Flex Plugin Version resource to archive. + """ + return PluginVersionArchiveContext( + self._version, plugin_sid=plugin_sid, sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.PluginVersionArchiveList>" diff --git a/twilio/rest/flex_api/v1/provisioning_status.py b/twilio/rest/flex_api/v1/provisioning_status.py new file mode 100644 index 0000000000..2a7bc5b465 --- /dev/null +++ b/twilio/rest/flex_api/v1/provisioning_status.py @@ -0,0 +1,181 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ProvisioningStatusInstance(InstanceResource): + + class Status(object): + ACTIVE = "active" + IN_PROGRESS = "in-progress" + NOT_CONFIGURED = "not-configured" + FAILED = "failed" + + """ + :ivar status: + :ivar url: The absolute URL of the resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.status: Optional["ProvisioningStatusInstance.Status"] = payload.get( + "status" + ) + self.url: Optional[str] = payload.get("url") + + self._context: Optional[ProvisioningStatusContext] = None + + @property + def _proxy(self) -> "ProvisioningStatusContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ProvisioningStatusContext for this ProvisioningStatusInstance + """ + if self._context is None: + self._context = ProvisioningStatusContext( + self._version, + ) + return self._context + + def fetch(self) -> "ProvisioningStatusInstance": + """ + Fetch the ProvisioningStatusInstance + + + :returns: The fetched ProvisioningStatusInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ProvisioningStatusInstance": + """ + Asynchronous coroutine to fetch the ProvisioningStatusInstance + + + :returns: The fetched ProvisioningStatusInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.FlexApi.V1.ProvisioningStatusInstance>" + + +class ProvisioningStatusContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the ProvisioningStatusContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/account/provision/status" + + def fetch(self) -> ProvisioningStatusInstance: + """ + Fetch the ProvisioningStatusInstance + + + :returns: The fetched ProvisioningStatusInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ProvisioningStatusInstance( + self._version, + payload, + ) + + async def fetch_async(self) -> ProvisioningStatusInstance: + """ + Asynchronous coroutine to fetch the ProvisioningStatusInstance + + + :returns: The fetched ProvisioningStatusInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ProvisioningStatusInstance( + self._version, + payload, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.FlexApi.V1.ProvisioningStatusContext>" + + +class ProvisioningStatusList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ProvisioningStatusList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> ProvisioningStatusContext: + """ + Constructs a ProvisioningStatusContext + + """ + return ProvisioningStatusContext(self._version) + + def __call__(self) -> ProvisioningStatusContext: + """ + Constructs a ProvisioningStatusContext + + """ + return ProvisioningStatusContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.ProvisioningStatusList>" diff --git a/twilio/rest/flex_api/v1/web_channel.py b/twilio/rest/flex_api/v1/web_channel.py new file mode 100644 index 0000000000..46e44fcecd --- /dev/null +++ b/twilio/rest/flex_api/v1/web_channel.py @@ -0,0 +1,651 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class WebChannelInstance(InstanceResource): + + class ChatStatus(object): + INACTIVE = "inactive" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the WebChannel resource and owns this Workflow. + :ivar flex_flow_sid: The SID of the Flex Flow. + :ivar sid: The unique string that we created to identify the WebChannel resource. + :ivar url: The absolute URL of the WebChannel resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.flex_flow_sid: Optional[str] = payload.get("flex_flow_sid") + self.sid: Optional[str] = payload.get("sid") + self.url: Optional[str] = payload.get("url") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[WebChannelContext] = None + + @property + def _proxy(self) -> "WebChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WebChannelContext for this WebChannelInstance + """ + if self._context is None: + self._context = WebChannelContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the WebChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "WebChannelInstance": + """ + Fetch the WebChannelInstance + + + :returns: The fetched WebChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WebChannelInstance": + """ + Asynchronous coroutine to fetch the WebChannelInstance + + + :returns: The fetched WebChannelInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> "WebChannelInstance": + """ + Update the WebChannelInstance + + :param chat_status: + :param post_engagement_data: The post-engagement data. + + :returns: The updated WebChannelInstance + """ + return self._proxy.update( + chat_status=chat_status, + post_engagement_data=post_engagement_data, + ) + + async def update_async( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> "WebChannelInstance": + """ + Asynchronous coroutine to update the WebChannelInstance + + :param chat_status: + :param post_engagement_data: The post-engagement data. + + :returns: The updated WebChannelInstance + """ + return await self._proxy.update_async( + chat_status=chat_status, + post_engagement_data=post_engagement_data, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.WebChannelInstance {}>".format(context) + + +class WebChannelContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the WebChannelContext + + :param version: Version that contains the resource + :param sid: The SID of the WebChannel resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/WebChannels/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the WebChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebChannelInstance: + """ + Fetch the WebChannelInstance + + + :returns: The fetched WebChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WebChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WebChannelInstance: + """ + Asynchronous coroutine to fetch the WebChannelInstance + + + :returns: The fetched WebChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WebChannelInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> WebChannelInstance: + """ + Update the WebChannelInstance + + :param chat_status: + :param post_engagement_data: The post-engagement data. + + :returns: The updated WebChannelInstance + """ + + data = values.of( + { + "ChatStatus": chat_status, + "PostEngagementData": post_engagement_data, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebChannelInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + chat_status: Union["WebChannelInstance.ChatStatus", object] = values.unset, + post_engagement_data: Union[str, object] = values.unset, + ) -> WebChannelInstance: + """ + Asynchronous coroutine to update the WebChannelInstance + + :param chat_status: + :param post_engagement_data: The post-engagement data. + + :returns: The updated WebChannelInstance + """ + + data = values.of( + { + "ChatStatus": chat_status, + "PostEngagementData": post_engagement_data, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebChannelInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V1.WebChannelContext {}>".format(context) + + +class WebChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WebChannelInstance: + """ + Build an instance of WebChannelInstance + + :param payload: Payload response from the API + """ + return WebChannelInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.WebChannelPage>" + + +class WebChannelList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the WebChannelList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/WebChannels" + + def create( + self, + flex_flow_sid: str, + identity: str, + customer_friendly_name: str, + chat_friendly_name: str, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + ) -> WebChannelInstance: + """ + Create the WebChannelInstance + + :param flex_flow_sid: The SID of the Flex Flow. + :param identity: The chat identity. + :param customer_friendly_name: The chat participant's friendly name. + :param chat_friendly_name: The chat channel's friendly name. + :param chat_unique_name: The chat channel's unique name. + :param pre_engagement_data: The pre-engagement data. + + :returns: The created WebChannelInstance + """ + + data = values.of( + { + "FlexFlowSid": flex_flow_sid, + "Identity": identity, + "CustomerFriendlyName": customer_friendly_name, + "ChatFriendlyName": chat_friendly_name, + "ChatUniqueName": chat_unique_name, + "PreEngagementData": pre_engagement_data, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebChannelInstance(self._version, payload) + + async def create_async( + self, + flex_flow_sid: str, + identity: str, + customer_friendly_name: str, + chat_friendly_name: str, + chat_unique_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + ) -> WebChannelInstance: + """ + Asynchronously create the WebChannelInstance + + :param flex_flow_sid: The SID of the Flex Flow. + :param identity: The chat identity. + :param customer_friendly_name: The chat participant's friendly name. + :param chat_friendly_name: The chat channel's friendly name. + :param chat_unique_name: The chat channel's unique name. + :param pre_engagement_data: The pre-engagement data. + + :returns: The created WebChannelInstance + """ + + data = values.of( + { + "FlexFlowSid": flex_flow_sid, + "Identity": identity, + "CustomerFriendlyName": customer_friendly_name, + "ChatFriendlyName": chat_friendly_name, + "ChatUniqueName": chat_unique_name, + "PreEngagementData": pre_engagement_data, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebChannelInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WebChannelInstance]: + """ + Streams WebChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WebChannelInstance]: + """ + Asynchronously streams WebChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebChannelInstance]: + """ + Lists WebChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebChannelInstance]: + """ + Asynchronously lists WebChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebChannelPage: + """ + Retrieve a single page of WebChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebChannelPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebChannelPage: + """ + Asynchronously retrieve a single page of WebChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebChannelPage(self._version, response) + + def get_page(self, target_url: str) -> WebChannelPage: + """ + Retrieve a specific page of WebChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WebChannelPage(self._version, response) + + async def get_page_async(self, target_url: str) -> WebChannelPage: + """ + Asynchronously retrieve a specific page of WebChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WebChannelPage(self._version, response) + + def get(self, sid: str) -> WebChannelContext: + """ + Constructs a WebChannelContext + + :param sid: The SID of the WebChannel resource to update. + """ + return WebChannelContext(self._version, sid=sid) + + def __call__(self, sid: str) -> WebChannelContext: + """ + Constructs a WebChannelContext + + :param sid: The SID of the WebChannel resource to update. + """ + return WebChannelContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V1.WebChannelList>" diff --git a/twilio/rest/flex_api/v2/__init__.py b/twilio/rest/flex_api/v2/__init__.py new file mode 100644 index 0000000000..e05ffcdfb5 --- /dev/null +++ b/twilio/rest/flex_api/v2/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.flex_api.v2.flex_user import FlexUserList +from twilio.rest.flex_api.v2.web_channels import WebChannelsList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of FlexApi + + :param domain: The Twilio.flex_api domain + """ + super().__init__(domain, "v2") + self._flex_user: Optional[FlexUserList] = None + self._web_channels: Optional[WebChannelsList] = None + + @property + def flex_user(self) -> FlexUserList: + if self._flex_user is None: + self._flex_user = FlexUserList(self) + return self._flex_user + + @property + def web_channels(self) -> WebChannelsList: + if self._web_channels is None: + self._web_channels = WebChannelsList(self) + return self._web_channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V2>" diff --git a/twilio/rest/flex_api/v2/flex_user.py b/twilio/rest/flex_api/v2/flex_user.py new file mode 100644 index 0000000000..eb2228d015 --- /dev/null +++ b/twilio/rest/flex_api/v2/flex_user.py @@ -0,0 +1,358 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class FlexUserInstance(InstanceResource): + """ + :ivar account_sid: The unique SID of the account that created the resource. + :ivar instance_sid: The unique ID created by Twilio to identify a Flex instance. + :ivar user_sid: The unique SID identifier of the Twilio Unified User. + :ivar flex_user_sid: The unique SID identifier of the Flex User. + :ivar worker_sid: The unique SID identifier of the worker. + :ivar workspace_sid: The unique SID identifier of the workspace. + :ivar flex_team_sid: The unique SID identifier of the Flex Team. + :ivar username: Username of the User. + :ivar email: Email of the User. + :ivar locale: The locale preference of the user. + :ivar roles: The roles of the user. + :ivar created_date: The date that this user was created, given in ISO 8601 format. + :ivar updated_date: The date that this user was updated, given in ISO 8601 format. + :ivar version: The current version of the user. + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + instance_sid: Optional[str] = None, + flex_user_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.instance_sid: Optional[str] = payload.get("instance_sid") + self.user_sid: Optional[str] = payload.get("user_sid") + self.flex_user_sid: Optional[str] = payload.get("flex_user_sid") + self.worker_sid: Optional[str] = payload.get("worker_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.flex_team_sid: Optional[str] = payload.get("flex_team_sid") + self.username: Optional[str] = payload.get("username") + self.email: Optional[str] = payload.get("email") + self.locale: Optional[str] = payload.get("locale") + self.roles: Optional[List[str]] = payload.get("roles") + self.created_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("created_date") + ) + self.updated_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updated_date") + ) + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "instance_sid": instance_sid or self.instance_sid, + "flex_user_sid": flex_user_sid or self.flex_user_sid, + } + self._context: Optional[FlexUserContext] = None + + @property + def _proxy(self) -> "FlexUserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FlexUserContext for this FlexUserInstance + """ + if self._context is None: + self._context = FlexUserContext( + self._version, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + return self._context + + def fetch(self) -> "FlexUserInstance": + """ + Fetch the FlexUserInstance + + + :returns: The fetched FlexUserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FlexUserInstance": + """ + Asynchronous coroutine to fetch the FlexUserInstance + + + :returns: The fetched FlexUserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> "FlexUserInstance": + """ + Update the FlexUserInstance + + :param email: Email of the User. + :param user_sid: The unique SID identifier of the Twilio Unified User. + :param locale: The locale preference of the user. + + :returns: The updated FlexUserInstance + """ + return self._proxy.update( + email=email, + user_sid=user_sid, + locale=locale, + ) + + async def update_async( + self, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> "FlexUserInstance": + """ + Asynchronous coroutine to update the FlexUserInstance + + :param email: Email of the User. + :param user_sid: The unique SID identifier of the Twilio Unified User. + :param locale: The locale preference of the user. + + :returns: The updated FlexUserInstance + """ + return await self._proxy.update_async( + email=email, + user_sid=user_sid, + locale=locale, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V2.FlexUserInstance {}>".format(context) + + +class FlexUserContext(InstanceContext): + + def __init__(self, version: Version, instance_sid: str, flex_user_sid: str): + """ + Initialize the FlexUserContext + + :param version: Version that contains the resource + :param instance_sid: The unique ID created by Twilio to identify a Flex instance. + :param flex_user_sid: The unique id for the flex user. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "instance_sid": instance_sid, + "flex_user_sid": flex_user_sid, + } + self._uri = "/Instances/{instance_sid}/Users/{flex_user_sid}".format( + **self._solution + ) + + def fetch(self) -> FlexUserInstance: + """ + Fetch the FlexUserInstance + + + :returns: The fetched FlexUserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + + async def fetch_async(self) -> FlexUserInstance: + """ + Asynchronous coroutine to fetch the FlexUserInstance + + + :returns: The fetched FlexUserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + + def update( + self, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> FlexUserInstance: + """ + Update the FlexUserInstance + + :param email: Email of the User. + :param user_sid: The unique SID identifier of the Twilio Unified User. + :param locale: The locale preference of the user. + + :returns: The updated FlexUserInstance + """ + + data = values.of( + { + "Email": email, + "UserSid": user_sid, + "Locale": locale, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + + async def update_async( + self, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> FlexUserInstance: + """ + Asynchronous coroutine to update the FlexUserInstance + + :param email: Email of the User. + :param user_sid: The unique SID identifier of the Twilio Unified User. + :param locale: The locale preference of the user. + + :returns: The updated FlexUserInstance + """ + + data = values.of( + { + "Email": email, + "UserSid": user_sid, + "Locale": locale, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FlexApi.V2.FlexUserContext {}>".format(context) + + +class FlexUserList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the FlexUserList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, instance_sid: str, flex_user_sid: str) -> FlexUserContext: + """ + Constructs a FlexUserContext + + :param instance_sid: The unique ID created by Twilio to identify a Flex instance. + :param flex_user_sid: The unique id for the flex user. + """ + return FlexUserContext( + self._version, instance_sid=instance_sid, flex_user_sid=flex_user_sid + ) + + def __call__(self, instance_sid: str, flex_user_sid: str) -> FlexUserContext: + """ + Constructs a FlexUserContext + + :param instance_sid: The unique ID created by Twilio to identify a Flex instance. + :param flex_user_sid: The unique id for the flex user. + """ + return FlexUserContext( + self._version, instance_sid=instance_sid, flex_user_sid=flex_user_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V2.FlexUserList>" diff --git a/twilio/rest/flex_api/v2/web_channels.py b/twilio/rest/flex_api/v2/web_channels.py new file mode 100644 index 0000000000..8e5aff8226 --- /dev/null +++ b/twilio/rest/flex_api/v2/web_channels.py @@ -0,0 +1,154 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Flex + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WebChannelsInstance(InstanceResource): + """ + :ivar conversation_sid: The unique string representing the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource) created. + :ivar identity: The unique string representing the User created and should be authorized to participate in the Conversation. For more details, see [User Identity & Access Tokens](https://www.twilio.com/docs/conversations/identity). + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.conversation_sid: Optional[str] = payload.get("conversation_sid") + self.identity: Optional[str] = payload.get("identity") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.FlexApi.V2.WebChannelsInstance>" + + +class WebChannelsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the WebChannelsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/WebChats" + + def create( + self, + address_sid: str, + ui_version: Union[str, object] = values.unset, + chat_friendly_name: Union[str, object] = values.unset, + customer_friendly_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + ) -> WebChannelsInstance: + """ + Create the WebChannelsInstance + + :param address_sid: The SID of the Conversations Address. See [Address Configuration Resource](https://www.twilio.com/docs/conversations/api/address-configuration-resource) for configuration details. When a conversation is created on the Flex backend, the callback URL will be set to the corresponding Studio Flow SID or webhook URL in your address configuration. + :param ui_version: The Ui-Version HTTP request header + :param chat_friendly_name: The Conversation's friendly name. See the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource) for an example. + :param customer_friendly_name: The Conversation participant's friendly name. See the [Conversation Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) for an example. + :param pre_engagement_data: The pre-engagement data. + + :returns: The created WebChannelsInstance + """ + + data = values.of( + { + "AddressSid": address_sid, + "ChatFriendlyName": chat_friendly_name, + "CustomerFriendlyName": customer_friendly_name, + "PreEngagementData": pre_engagement_data, + } + ) + headers = values.of( + { + "Ui-Version": ui_version, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebChannelsInstance(self._version, payload) + + async def create_async( + self, + address_sid: str, + ui_version: Union[str, object] = values.unset, + chat_friendly_name: Union[str, object] = values.unset, + customer_friendly_name: Union[str, object] = values.unset, + pre_engagement_data: Union[str, object] = values.unset, + ) -> WebChannelsInstance: + """ + Asynchronously create the WebChannelsInstance + + :param address_sid: The SID of the Conversations Address. See [Address Configuration Resource](https://www.twilio.com/docs/conversations/api/address-configuration-resource) for configuration details. When a conversation is created on the Flex backend, the callback URL will be set to the corresponding Studio Flow SID or webhook URL in your address configuration. + :param ui_version: The Ui-Version HTTP request header + :param chat_friendly_name: The Conversation's friendly name. See the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource) for an example. + :param customer_friendly_name: The Conversation participant's friendly name. See the [Conversation Participant Resource](https://www.twilio.com/docs/conversations/api/conversation-participant-resource) for an example. + :param pre_engagement_data: The pre-engagement data. + + :returns: The created WebChannelsInstance + """ + + data = values.of( + { + "AddressSid": address_sid, + "ChatFriendlyName": chat_friendly_name, + "CustomerFriendlyName": customer_friendly_name, + "PreEngagementData": pre_engagement_data, + } + ) + headers = values.of( + { + "Ui-Version": ui_version, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebChannelsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FlexApi.V2.WebChannelsList>" diff --git a/twilio/rest/frontline_api/FrontlineApiBase.py b/twilio/rest/frontline_api/FrontlineApiBase.py new file mode 100644 index 0000000000..d9dadc16e9 --- /dev/null +++ b/twilio/rest/frontline_api/FrontlineApiBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.frontline_api.v1 import V1 + + +class FrontlineApiBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the FrontlineApi Domain + + :returns: Domain for FrontlineApi + """ + super().__init__(twilio, "https://frontline-api.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of FrontlineApi + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.FrontlineApi>" diff --git a/twilio/rest/frontline_api/__init__.py b/twilio/rest/frontline_api/__init__.py new file mode 100644 index 0000000000..300fafa320 --- /dev/null +++ b/twilio/rest/frontline_api/__init__.py @@ -0,0 +1,15 @@ +from warnings import warn + +from twilio.rest.frontline_api.FrontlineApiBase import FrontlineApiBase +from twilio.rest.frontline_api.v1.user import UserList + + +class FrontlineApi(FrontlineApiBase): + @property + def users(self) -> UserList: + warn( + "users is deprecated. Use v1.users instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.users diff --git a/twilio/rest/frontline_api/v1/__init__.py b/twilio/rest/frontline_api/v1/__init__.py new file mode 100644 index 0000000000..610ed37194 --- /dev/null +++ b/twilio/rest/frontline_api/v1/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Frontline + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.frontline_api.v1.user import UserList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of FrontlineApi + + :param domain: The Twilio.frontline_api domain + """ + super().__init__(domain, "v1") + self._users: Optional[UserList] = None + + @property + def users(self) -> UserList: + if self._users is None: + self._users = UserList(self) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.FrontlineApi.V1>" diff --git a/twilio/rest/frontline_api/v1/user.py b/twilio/rest/frontline_api/v1/user.py new file mode 100644 index 0000000000..a45ed2ffee --- /dev/null +++ b/twilio/rest/frontline_api/v1/user.py @@ -0,0 +1,326 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Frontline + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class UserInstance(InstanceResource): + + class StateType(object): + ACTIVE = "active" + DEACTIVATED = "deactivated" + + """ + :ivar sid: The unique string that we created to identify the User resource. + :ivar identity: The application-defined string that uniquely identifies the resource's User. This value is often a username or an email address, and is case-sensitive. + :ivar friendly_name: The string that you assigned to describe the User. + :ivar avatar: The avatar URL which will be shown in Frontline application. + :ivar state: + :ivar is_available: Whether the User is available for new conversations. Defaults to `false` for new users. + :ivar url: An absolute API resource URL for this user. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.identity: Optional[str] = payload.get("identity") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.avatar: Optional[str] = payload.get("avatar") + self.state: Optional["UserInstance.StateType"] = payload.get("state") + self.is_available: Optional[bool] = payload.get("is_available") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[UserContext] = None + + @property + def _proxy(self) -> "UserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + avatar: Union[str, object] = values.unset, + state: Union["UserInstance.StateType", object] = values.unset, + is_available: Union[bool, object] = values.unset, + ) -> "UserInstance": + """ + Update the UserInstance + + :param friendly_name: The string that you assigned to describe the User. + :param avatar: The avatar URL which will be shown in Frontline application. + :param state: + :param is_available: Whether the User is available for new conversations. Set to `false` to prevent User from receiving new inbound conversations if you are using [Pool Routing](https://www.twilio.com/docs/frontline/handle-incoming-conversations#3-pool-routing). + + :returns: The updated UserInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + avatar=avatar, + state=state, + is_available=is_available, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + avatar: Union[str, object] = values.unset, + state: Union["UserInstance.StateType", object] = values.unset, + is_available: Union[bool, object] = values.unset, + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param friendly_name: The string that you assigned to describe the User. + :param avatar: The avatar URL which will be shown in Frontline application. + :param state: + :param is_available: Whether the User is available for new conversations. Set to `false` to prevent User from receiving new inbound conversations if you are using [Pool Routing](https://www.twilio.com/docs/frontline/handle-incoming-conversations#3-pool-routing). + + :returns: The updated UserInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + avatar=avatar, + state=state, + is_available=is_available, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FrontlineApi.V1.UserInstance {}>".format(context) + + +class UserContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the UserContext + + :param version: Version that contains the resource + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Users/{sid}".format(**self._solution) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + avatar: Union[str, object] = values.unset, + state: Union["UserInstance.StateType", object] = values.unset, + is_available: Union[bool, object] = values.unset, + ) -> UserInstance: + """ + Update the UserInstance + + :param friendly_name: The string that you assigned to describe the User. + :param avatar: The avatar URL which will be shown in Frontline application. + :param state: + :param is_available: Whether the User is available for new conversations. Set to `false` to prevent User from receiving new inbound conversations if you are using [Pool Routing](https://www.twilio.com/docs/frontline/handle-incoming-conversations#3-pool-routing). + + :returns: The updated UserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Avatar": avatar, + "State": state, + "IsAvailable": serialize.boolean_to_string(is_available), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + avatar: Union[str, object] = values.unset, + state: Union["UserInstance.StateType", object] = values.unset, + is_available: Union[bool, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param friendly_name: The string that you assigned to describe the User. + :param avatar: The avatar URL which will be shown in Frontline application. + :param state: + :param is_available: Whether the User is available for new conversations. Set to `false` to prevent User from receiving new inbound conversations if you are using [Pool Routing](https://www.twilio.com/docs/frontline/handle-incoming-conversations#3-pool-routing). + + :returns: The updated UserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Avatar": avatar, + "State": state, + "IsAvailable": serialize.boolean_to_string(is_available), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.FrontlineApi.V1.UserContext {}>".format(context) + + +class UserList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the UserList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + return UserContext(self._version, sid=sid) + + def __call__(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: The SID of the User resource to update. This value can be either the `sid` or the `identity` of the User resource to update. + """ + return UserContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.FrontlineApi.V1.UserList>" diff --git a/twilio/rest/iam/IamBase.py b/twilio/rest/iam/IamBase.py new file mode 100644 index 0000000000..2882ec145b --- /dev/null +++ b/twilio/rest/iam/IamBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.iam.v1 import V1 + + +class IamBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Iam Domain + + :returns: Domain for Iam + """ + super().__init__(twilio, "https://iam.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Iam + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Iam>" diff --git a/twilio/rest/iam/__init__.py b/twilio/rest/iam/__init__.py new file mode 100644 index 0000000000..994ecee62f --- /dev/null +++ b/twilio/rest/iam/__init__.py @@ -0,0 +1,25 @@ +from warnings import warn + +from twilio.rest.iam.IamBase import IamBase +from twilio.rest.iam.v1.api_key import ApiKeyList +from twilio.rest.iam.v1.get_api_keys import GetApiKeysList + + +class Iam(IamBase): + @property + def api_key(self) -> ApiKeyList: + warn( + "api_key is deprecated. Use v1.api_key instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.api_key + + @property + def get_api_keys(self) -> GetApiKeysList: + warn( + "get_api_keys is deprecated. Use v1.get_api_keys instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.get_api_keys diff --git a/twilio/rest/iam/v1/__init__.py b/twilio/rest/iam/v1/__init__.py new file mode 100644 index 0000000000..08c45435a6 --- /dev/null +++ b/twilio/rest/iam/v1/__init__.py @@ -0,0 +1,67 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Iam + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.iam.v1.api_key import ApiKeyList +from twilio.rest.iam.v1.get_api_keys import GetApiKeysList +from twilio.rest.iam.v1.new_api_key import NewApiKeyList +from twilio.rest.iam.v1.token import TokenList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Iam + + :param domain: The Twilio.iam domain + """ + super().__init__(domain, "v1") + self._api_key: Optional[ApiKeyList] = None + self._get_api_keys: Optional[GetApiKeysList] = None + self._new_api_key: Optional[NewApiKeyList] = None + self._token: Optional[TokenList] = None + + @property + def api_key(self) -> ApiKeyList: + if self._api_key is None: + self._api_key = ApiKeyList(self) + return self._api_key + + @property + def get_api_keys(self) -> GetApiKeysList: + if self._get_api_keys is None: + self._get_api_keys = GetApiKeysList(self) + return self._get_api_keys + + @property + def new_api_key(self) -> NewApiKeyList: + if self._new_api_key is None: + self._new_api_key = NewApiKeyList(self) + return self._new_api_key + + @property + def token(self) -> TokenList: + if self._token is None: + self._token = TokenList(self) + return self._token + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Iam.V1>" diff --git a/twilio/rest/iam/v1/api_key.py b/twilio/rest/iam/v1/api_key.py new file mode 100644 index 0000000000..f07512c09b --- /dev/null +++ b/twilio/rest/iam/v1/api_key.py @@ -0,0 +1,342 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Iam + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ApiKeyInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Key resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar policy: The \\`Policy\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.policy: Optional[Dict[str, object]] = payload.get("policy") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ApiKeyContext] = None + + @property + def _proxy(self) -> "ApiKeyContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ApiKeyContext for this ApiKeyInstance + """ + if self._context is None: + self._context = ApiKeyContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ApiKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ApiKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ApiKeyInstance": + """ + Fetch the ApiKeyInstance + + + :returns: The fetched ApiKeyInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ApiKeyInstance": + """ + Asynchronous coroutine to fetch the ApiKeyInstance + + + :returns: The fetched ApiKeyInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> "ApiKeyInstance": + """ + Update the ApiKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: The updated ApiKeyInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + policy=policy, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> "ApiKeyInstance": + """ + Asynchronous coroutine to update the ApiKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: The updated ApiKeyInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + policy=policy, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Iam.V1.ApiKeyInstance {}>".format(context) + + +class ApiKeyContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ApiKeyContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Key resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Keys/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the ApiKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ApiKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ApiKeyInstance: + """ + Fetch the ApiKeyInstance + + + :returns: The fetched ApiKeyInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ApiKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ApiKeyInstance: + """ + Asynchronous coroutine to fetch the ApiKeyInstance + + + :returns: The fetched ApiKeyInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ApiKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> ApiKeyInstance: + """ + Update the ApiKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: The updated ApiKeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Policy": serialize.object(policy), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ApiKeyInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> ApiKeyInstance: + """ + Asynchronous coroutine to update the ApiKeyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: The updated ApiKeyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Policy": serialize.object(policy), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ApiKeyInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Iam.V1.ApiKeyContext {}>".format(context) + + +class ApiKeyList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ApiKeyList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sid: str) -> ApiKeyContext: + """ + Constructs a ApiKeyContext + + :param sid: The Twilio-provided string that uniquely identifies the Key resource to update. + """ + return ApiKeyContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ApiKeyContext: + """ + Constructs a ApiKeyContext + + :param sid: The Twilio-provided string that uniquely identifies the Key resource to update. + """ + return ApiKeyContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Iam.V1.ApiKeyList>" diff --git a/twilio/rest/iam/v1/get_api_keys.py b/twilio/rest/iam/v1/get_api_keys.py new file mode 100644 index 0000000000..03b29cdb38 --- /dev/null +++ b/twilio/rest/iam/v1/get_api_keys.py @@ -0,0 +1,304 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Iam + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class GetApiKeysInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Key resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Iam.V1.GetApiKeysInstance>" + + +class GetApiKeysPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> GetApiKeysInstance: + """ + Build an instance of GetApiKeysInstance + + :param payload: Payload response from the API + """ + return GetApiKeysInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Iam.V1.GetApiKeysPage>" + + +class GetApiKeysList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the GetApiKeysList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Keys" + + def stream( + self, + account_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[GetApiKeysInstance]: + """ + Streams GetApiKeysInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(account_sid=account_sid, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + account_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[GetApiKeysInstance]: + """ + Asynchronously streams GetApiKeysInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + account_sid=account_sid, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + account_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[GetApiKeysInstance]: + """ + Lists GetApiKeysInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + account_sid=account_sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + account_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[GetApiKeysInstance]: + """ + Asynchronously lists GetApiKeysInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + account_sid=account_sid, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + account_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> GetApiKeysPage: + """ + Retrieve a single page of GetApiKeysInstance records from the API. + Request is executed immediately + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of GetApiKeysInstance + """ + data = values.of( + { + "AccountSid": account_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return GetApiKeysPage(self._version, response) + + async def page_async( + self, + account_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> GetApiKeysPage: + """ + Asynchronously retrieve a single page of GetApiKeysInstance records from the API. + Request is executed immediately + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of GetApiKeysInstance + """ + data = values.of( + { + "AccountSid": account_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return GetApiKeysPage(self._version, response) + + def get_page(self, target_url: str) -> GetApiKeysPage: + """ + Retrieve a specific page of GetApiKeysInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of GetApiKeysInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return GetApiKeysPage(self._version, response) + + async def get_page_async(self, target_url: str) -> GetApiKeysPage: + """ + Asynchronously retrieve a specific page of GetApiKeysInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of GetApiKeysInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return GetApiKeysPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Iam.V1.GetApiKeysList>" diff --git a/twilio/rest/iam/v1/new_api_key.py b/twilio/rest/iam/v1/new_api_key.py new file mode 100644 index 0000000000..760ce79ca3 --- /dev/null +++ b/twilio/rest/iam/v1/new_api_key.py @@ -0,0 +1,157 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Iam + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NewApiKeyInstance(InstanceResource): + + class Keytype(object): + RESTRICTED = "restricted" + + """ + :ivar sid: The unique string that that we created to identify the NewKey resource. You will use this as the basic-auth `user` when authenticating to the API. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT that the API Key was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the new API Key was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar secret: The secret your application uses to sign Access Tokens and to authenticate to the REST API (you will use this as the basic-auth `password`). **Note that for security reasons, this field is ONLY returned when the API Key is first created.** + :ivar policy: Collection of allow assertions. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.secret: Optional[str] = payload.get("secret") + self.policy: Optional[Dict[str, object]] = payload.get("policy") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Iam.V1.NewApiKeyInstance>" + + +class NewApiKeyList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the NewApiKeyList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Keys" + + def create( + self, + account_sid: str, + friendly_name: Union[str, object] = values.unset, + key_type: Union["NewApiKeyInstance.Keytype", object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> NewApiKeyInstance: + """ + Create the NewApiKeyInstance + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param key_type: + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: The created NewApiKeyInstance + """ + + data = values.of( + { + "AccountSid": account_sid, + "FriendlyName": friendly_name, + "KeyType": key_type, + "Policy": serialize.object(policy), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NewApiKeyInstance(self._version, payload) + + async def create_async( + self, + account_sid: str, + friendly_name: Union[str, object] = values.unset, + key_type: Union["NewApiKeyInstance.Keytype", object] = values.unset, + policy: Union[object, object] = values.unset, + ) -> NewApiKeyInstance: + """ + Asynchronously create the NewApiKeyInstance + + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param key_type: + :param policy: The \\\\`Policy\\\\` object is a collection that specifies the allowed Twilio permissions for the restricted key. For more information on the permissions available with restricted API keys, refer to the [Twilio documentation](https://www.twilio.com/docs/iam/api-keys/restricted-api-keys#permissions-available-with-restricted-api-keys). + + :returns: The created NewApiKeyInstance + """ + + data = values.of( + { + "AccountSid": account_sid, + "FriendlyName": friendly_name, + "KeyType": key_type, + "Policy": serialize.object(policy), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NewApiKeyInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Iam.V1.NewApiKeyList>" diff --git a/twilio/rest/iam/v1/token.py b/twilio/rest/iam/v1/token.py new file mode 100644 index 0000000000..50d3d11930 --- /dev/null +++ b/twilio/rest/iam/v1/token.py @@ -0,0 +1,170 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Iam + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TokenInstance(InstanceResource): + """ + :ivar access_token: Token which carries the necessary information to access a Twilio resource directly. + :ivar refresh_token: Token which carries the information necessary to get a new access token. + :ivar id_token: Token which carries the information necessary of user profile. + :ivar token_type: Token type + :ivar expires_in: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.access_token: Optional[str] = payload.get("access_token") + self.refresh_token: Optional[str] = payload.get("refresh_token") + self.id_token: Optional[str] = payload.get("id_token") + self.token_type: Optional[str] = payload.get("token_type") + self.expires_in: Optional[int] = payload.get("expires_in") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Iam.V1.TokenInstance>" + + +class TokenList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TokenList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/token" + + def create( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Create the TokenInstance + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: The created TokenInstance + """ + + data = values.of( + { + "grant_type": grant_type, + "client_id": client_id, + "client_secret": client_secret, + "code": code, + "redirect_uri": redirect_uri, + "audience": audience, + "refresh_token": refresh_token, + "scope": scope, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TokenInstance(self._version, payload) + + async def create_async( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Asynchronously create the TokenInstance + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: The created TokenInstance + """ + + data = values.of( + { + "grant_type": grant_type, + "client_id": client_id, + "client_secret": client_secret, + "code": code, + "redirect_uri": redirect_uri, + "audience": audience, + "refresh_token": refresh_token, + "scope": scope, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TokenInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Iam.V1.TokenList>" diff --git a/twilio/rest/insights/InsightsBase.py b/twilio/rest/insights/InsightsBase.py new file mode 100644 index 0000000000..458122cec7 --- /dev/null +++ b/twilio/rest/insights/InsightsBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.insights.v1 import V1 + + +class InsightsBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Insights Domain + + :returns: Domain for Insights + """ + super().__init__(twilio, "https://insights.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Insights + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Insights>" diff --git a/twilio/rest/insights/__init__.py b/twilio/rest/insights/__init__.py new file mode 100644 index 0000000000..0f1457794c --- /dev/null +++ b/twilio/rest/insights/__init__.py @@ -0,0 +1,55 @@ +from warnings import warn + +from twilio.rest.insights.InsightsBase import InsightsBase +from twilio.rest.insights.v1.call import CallList +from twilio.rest.insights.v1.call_summaries import CallSummariesList +from twilio.rest.insights.v1.conference import ConferenceList +from twilio.rest.insights.v1.room import RoomList +from twilio.rest.insights.v1.setting import SettingList + + +class Insights(InsightsBase): + @property + def settings(self) -> SettingList: + warn( + "settings is deprecated. Use v1.settings instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.settings + + @property + def calls(self) -> CallList: + warn( + "calls is deprecated. Use v1.calls instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.calls + + @property + def call_summaries(self) -> CallSummariesList: + warn( + "call_summaries is deprecated. Use v1.call_summaries instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.call_summaries + + @property + def conferences(self) -> ConferenceList: + warn( + "conferences is deprecated. Use v1.conferences instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.conferences + + @property + def rooms(self) -> RoomList: + warn( + "rooms is deprecated. Use v1.rooms instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.rooms diff --git a/twilio/rest/insights/v1/__init__.py b/twilio/rest/insights/v1/__init__.py new file mode 100644 index 0000000000..8f7d1946f0 --- /dev/null +++ b/twilio/rest/insights/v1/__init__.py @@ -0,0 +1,75 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.insights.v1.call import CallList +from twilio.rest.insights.v1.call_summaries import CallSummariesList +from twilio.rest.insights.v1.conference import ConferenceList +from twilio.rest.insights.v1.room import RoomList +from twilio.rest.insights.v1.setting import SettingList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Insights + + :param domain: The Twilio.insights domain + """ + super().__init__(domain, "v1") + self._calls: Optional[CallList] = None + self._call_summaries: Optional[CallSummariesList] = None + self._conferences: Optional[ConferenceList] = None + self._rooms: Optional[RoomList] = None + self._settings: Optional[SettingList] = None + + @property + def calls(self) -> CallList: + if self._calls is None: + self._calls = CallList(self) + return self._calls + + @property + def call_summaries(self) -> CallSummariesList: + if self._call_summaries is None: + self._call_summaries = CallSummariesList(self) + return self._call_summaries + + @property + def conferences(self) -> ConferenceList: + if self._conferences is None: + self._conferences = ConferenceList(self) + return self._conferences + + @property + def rooms(self) -> RoomList: + if self._rooms is None: + self._rooms = RoomList(self) + return self._rooms + + @property + def settings(self) -> SettingList: + if self._settings is None: + self._settings = SettingList(self) + return self._settings + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Insights.V1>" diff --git a/twilio/rest/insights/v1/call/__init__.py b/twilio/rest/insights/v1/call/__init__.py new file mode 100644 index 0000000000..cb08aa58aa --- /dev/null +++ b/twilio/rest/insights/v1/call/__init__.py @@ -0,0 +1,275 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.insights.v1.call.annotation import AnnotationList +from twilio.rest.insights.v1.call.call_summary import CallSummaryList +from twilio.rest.insights.v1.call.event import EventList +from twilio.rest.insights.v1.call.metric import MetricList + + +class CallInstance(InstanceResource): + """ + :ivar sid: + :ivar url: + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CallContext] = None + + @property + def _proxy(self) -> "CallContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CallContext for this CallInstance + """ + if self._context is None: + self._context = CallContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "CallInstance": + """ + Fetch the CallInstance + + + :returns: The fetched CallInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CallInstance": + """ + Asynchronous coroutine to fetch the CallInstance + + + :returns: The fetched CallInstance + """ + return await self._proxy.fetch_async() + + @property + def annotation(self) -> AnnotationList: + """ + Access the annotation + """ + return self._proxy.annotation + + @property + def summary(self) -> CallSummaryList: + """ + Access the summary + """ + return self._proxy.summary + + @property + def events(self) -> EventList: + """ + Access the events + """ + return self._proxy.events + + @property + def metrics(self) -> MetricList: + """ + Access the metrics + """ + return self._proxy.metrics + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Insights.V1.CallInstance {}>".format(context) + + +class CallContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CallContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Voice/{sid}".format(**self._solution) + + self._annotation: Optional[AnnotationList] = None + self._summary: Optional[CallSummaryList] = None + self._events: Optional[EventList] = None + self._metrics: Optional[MetricList] = None + + def fetch(self) -> CallInstance: + """ + Fetch the CallInstance + + + :returns: The fetched CallInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CallInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CallInstance: + """ + Asynchronous coroutine to fetch the CallInstance + + + :returns: The fetched CallInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CallInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + @property + def annotation(self) -> AnnotationList: + """ + Access the annotation + """ + if self._annotation is None: + self._annotation = AnnotationList( + self._version, + self._solution["sid"], + ) + return self._annotation + + @property + def summary(self) -> CallSummaryList: + """ + Access the summary + """ + if self._summary is None: + self._summary = CallSummaryList( + self._version, + self._solution["sid"], + ) + return self._summary + + @property + def events(self) -> EventList: + """ + Access the events + """ + if self._events is None: + self._events = EventList( + self._version, + self._solution["sid"], + ) + return self._events + + @property + def metrics(self) -> MetricList: + """ + Access the metrics + """ + if self._metrics is None: + self._metrics = MetricList( + self._version, + self._solution["sid"], + ) + return self._metrics + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Insights.V1.CallContext {}>".format(context) + + +class CallList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CallList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sid: str) -> CallContext: + """ + Constructs a CallContext + + :param sid: + """ + return CallContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CallContext: + """ + Constructs a CallContext + + :param sid: + """ + return CallContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Insights.V1.CallList>" diff --git a/twilio/rest/insights/v1/call/annotation.py b/twilio/rest/insights/v1/call/annotation.py new file mode 100644 index 0000000000..6e705d3916 --- /dev/null +++ b/twilio/rest/insights/v1/call/annotation.py @@ -0,0 +1,395 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class AnnotationInstance(InstanceResource): + + class AnsweredBy(object): + UNKNOWN_ANSWERED_BY = "unknown_answered_by" + HUMAN = "human" + MACHINE = "machine" + + class ConnectivityIssue(object): + UNKNOWN_CONNECTIVITY_ISSUE = "unknown_connectivity_issue" + NO_CONNECTIVITY_ISSUE = "no_connectivity_issue" + INVALID_NUMBER = "invalid_number" + CALLER_ID = "caller_id" + DROPPED_CALL = "dropped_call" + NUMBER_REACHABILITY = "number_reachability" + + """ + :ivar call_sid: The unique SID identifier of the Call. + :ivar account_sid: The unique SID identifier of the Account. + :ivar answered_by: + :ivar connectivity_issue: + :ivar quality_issues: Specifies if the call had any subjective quality issues. Possible values are one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, or `static_noise`. + :ivar spam: Specifies if the call was a spam call. Use this to provide feedback on whether calls placed from your account were marked as spam, or if inbound calls received by your account were unwanted spam. Is of type Boolean: true, false. Use true if the call was a spam call. + :ivar call_score: Specifies the Call Score, if available. This is of type integer. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for rating the call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :ivar comment: Specifies any comments pertaining to the call. Twilio does not treat this field as PII, so no PII should be included in comments. + :ivar incident: Incident or support ticket associated with this call. The `incident` property is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): + super().__init__(version) + + self.call_sid: Optional[str] = payload.get("call_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.answered_by: Optional["AnnotationInstance.AnsweredBy"] = payload.get( + "answered_by" + ) + self.connectivity_issue: Optional["AnnotationInstance.ConnectivityIssue"] = ( + payload.get("connectivity_issue") + ) + self.quality_issues: Optional[List[str]] = payload.get("quality_issues") + self.spam: Optional[bool] = payload.get("spam") + self.call_score: Optional[int] = deserialize.integer(payload.get("call_score")) + self.comment: Optional[str] = payload.get("comment") + self.incident: Optional[str] = payload.get("incident") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "call_sid": call_sid, + } + self._context: Optional[AnnotationContext] = None + + @property + def _proxy(self) -> "AnnotationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AnnotationContext for this AnnotationInstance + """ + if self._context is None: + self._context = AnnotationContext( + self._version, + call_sid=self._solution["call_sid"], + ) + return self._context + + def fetch(self) -> "AnnotationInstance": + """ + Fetch the AnnotationInstance + + + :returns: The fetched AnnotationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AnnotationInstance": + """ + Asynchronous coroutine to fetch the AnnotationInstance + + + :returns: The fetched AnnotationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, + connectivity_issue: Union[ + "AnnotationInstance.ConnectivityIssue", object + ] = values.unset, + quality_issues: Union[str, object] = values.unset, + spam: Union[bool, object] = values.unset, + call_score: Union[int, object] = values.unset, + comment: Union[str, object] = values.unset, + incident: Union[str, object] = values.unset, + ) -> "AnnotationInstance": + """ + Update the AnnotationInstance + + :param answered_by: + :param connectivity_issue: + :param quality_issues: Specify if the call had any subjective quality issues. Possible values, one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. Use comma separated values to indicate multiple quality issues for the same call. + :param spam: A boolean flag to indicate if the call was a spam call. Use this to provide feedback on whether calls placed from your account were marked as spam, or if inbound calls received by your account were unwanted spam. Use `true` if the call was a spam call. + :param call_score: Specify the call score. This is of type integer. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for rating the call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param comment: Specify any comments pertaining to the call. `comment` has a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in the `comment`. + :param incident: Associate this call with an incident or support ticket. The `incident` parameter is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. + + :returns: The updated AnnotationInstance + """ + return self._proxy.update( + answered_by=answered_by, + connectivity_issue=connectivity_issue, + quality_issues=quality_issues, + spam=spam, + call_score=call_score, + comment=comment, + incident=incident, + ) + + async def update_async( + self, + answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, + connectivity_issue: Union[ + "AnnotationInstance.ConnectivityIssue", object + ] = values.unset, + quality_issues: Union[str, object] = values.unset, + spam: Union[bool, object] = values.unset, + call_score: Union[int, object] = values.unset, + comment: Union[str, object] = values.unset, + incident: Union[str, object] = values.unset, + ) -> "AnnotationInstance": + """ + Asynchronous coroutine to update the AnnotationInstance + + :param answered_by: + :param connectivity_issue: + :param quality_issues: Specify if the call had any subjective quality issues. Possible values, one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. Use comma separated values to indicate multiple quality issues for the same call. + :param spam: A boolean flag to indicate if the call was a spam call. Use this to provide feedback on whether calls placed from your account were marked as spam, or if inbound calls received by your account were unwanted spam. Use `true` if the call was a spam call. + :param call_score: Specify the call score. This is of type integer. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for rating the call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param comment: Specify any comments pertaining to the call. `comment` has a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in the `comment`. + :param incident: Associate this call with an incident or support ticket. The `incident` parameter is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. + + :returns: The updated AnnotationInstance + """ + return await self._proxy.update_async( + answered_by=answered_by, + connectivity_issue=connectivity_issue, + quality_issues=quality_issues, + spam=spam, + call_score=call_score, + comment=comment, + incident=incident, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Insights.V1.AnnotationInstance {}>".format(context) + + +class AnnotationContext(InstanceContext): + + def __init__(self, version: Version, call_sid: str): + """ + Initialize the AnnotationContext + + :param version: Version that contains the resource + :param call_sid: The unique string that Twilio created to identify this Call resource. It always starts with a CA. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "call_sid": call_sid, + } + self._uri = "/Voice/{call_sid}/Annotation".format(**self._solution) + + def fetch(self) -> AnnotationInstance: + """ + Fetch the AnnotationInstance + + + :returns: The fetched AnnotationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AnnotationInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], + ) + + async def fetch_async(self) -> AnnotationInstance: + """ + Asynchronous coroutine to fetch the AnnotationInstance + + + :returns: The fetched AnnotationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AnnotationInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], + ) + + def update( + self, + answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, + connectivity_issue: Union[ + "AnnotationInstance.ConnectivityIssue", object + ] = values.unset, + quality_issues: Union[str, object] = values.unset, + spam: Union[bool, object] = values.unset, + call_score: Union[int, object] = values.unset, + comment: Union[str, object] = values.unset, + incident: Union[str, object] = values.unset, + ) -> AnnotationInstance: + """ + Update the AnnotationInstance + + :param answered_by: + :param connectivity_issue: + :param quality_issues: Specify if the call had any subjective quality issues. Possible values, one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. Use comma separated values to indicate multiple quality issues for the same call. + :param spam: A boolean flag to indicate if the call was a spam call. Use this to provide feedback on whether calls placed from your account were marked as spam, or if inbound calls received by your account were unwanted spam. Use `true` if the call was a spam call. + :param call_score: Specify the call score. This is of type integer. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for rating the call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param comment: Specify any comments pertaining to the call. `comment` has a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in the `comment`. + :param incident: Associate this call with an incident or support ticket. The `incident` parameter is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. + + :returns: The updated AnnotationInstance + """ + + data = values.of( + { + "AnsweredBy": answered_by, + "ConnectivityIssue": connectivity_issue, + "QualityIssues": quality_issues, + "Spam": serialize.boolean_to_string(spam), + "CallScore": call_score, + "Comment": comment, + "Incident": incident, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AnnotationInstance( + self._version, payload, call_sid=self._solution["call_sid"] + ) + + async def update_async( + self, + answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, + connectivity_issue: Union[ + "AnnotationInstance.ConnectivityIssue", object + ] = values.unset, + quality_issues: Union[str, object] = values.unset, + spam: Union[bool, object] = values.unset, + call_score: Union[int, object] = values.unset, + comment: Union[str, object] = values.unset, + incident: Union[str, object] = values.unset, + ) -> AnnotationInstance: + """ + Asynchronous coroutine to update the AnnotationInstance + + :param answered_by: + :param connectivity_issue: + :param quality_issues: Specify if the call had any subjective quality issues. Possible values, one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. Use comma separated values to indicate multiple quality issues for the same call. + :param spam: A boolean flag to indicate if the call was a spam call. Use this to provide feedback on whether calls placed from your account were marked as spam, or if inbound calls received by your account were unwanted spam. Use `true` if the call was a spam call. + :param call_score: Specify the call score. This is of type integer. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for rating the call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param comment: Specify any comments pertaining to the call. `comment` has a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in the `comment`. + :param incident: Associate this call with an incident or support ticket. The `incident` parameter is of type string with a maximum character limit of 100. Twilio does not treat this field as PII, so no PII should be included in `incident`. + + :returns: The updated AnnotationInstance + """ + + data = values.of( + { + "AnsweredBy": answered_by, + "ConnectivityIssue": connectivity_issue, + "QualityIssues": quality_issues, + "Spam": serialize.boolean_to_string(spam), + "CallScore": call_score, + "Comment": comment, + "Incident": incident, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AnnotationInstance( + self._version, payload, call_sid=self._solution["call_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Insights.V1.AnnotationContext {}>".format(context) + + +class AnnotationList(ListResource): + + def __init__(self, version: Version, call_sid: str): + """ + Initialize the AnnotationList + + :param version: Version that contains the resource + :param call_sid: The unique SID identifier of the Call. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "call_sid": call_sid, + } + + def get(self) -> AnnotationContext: + """ + Constructs a AnnotationContext + + """ + return AnnotationContext(self._version, call_sid=self._solution["call_sid"]) + + def __call__(self) -> AnnotationContext: + """ + Constructs a AnnotationContext + + """ + return AnnotationContext(self._version, call_sid=self._solution["call_sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Insights.V1.AnnotationList>" diff --git a/twilio/rest/insights/v1/call/call_summary.py b/twilio/rest/insights/v1/call/call_summary.py new file mode 100644 index 0000000000..e21af100a1 --- /dev/null +++ b/twilio/rest/insights/v1/call/call_summary.py @@ -0,0 +1,321 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class CallSummaryInstance(InstanceResource): + + class AnsweredBy(object): + UNKNOWN = "unknown" + MACHINE_START = "machine_start" + MACHINE_END_BEEP = "machine_end_beep" + MACHINE_END_SILENCE = "machine_end_silence" + MACHINE_END_OTHER = "machine_end_other" + HUMAN = "human" + FAX = "fax" + + class CallState(object): + RINGING = "ringing" + COMPLETED = "completed" + BUSY = "busy" + FAIL = "fail" + NOANSWER = "noanswer" + CANCELED = "canceled" + ANSWERED = "answered" + UNDIALED = "undialed" + + class CallType(object): + CARRIER = "carrier" + SIP = "sip" + TRUNKING = "trunking" + CLIENT = "client" + WHATSAPP = "whatsapp" + + class ProcessingState(object): + COMPLETE = "complete" + PARTIAL = "partial" + + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar call_sid: The unique SID identifier of the Call. + :ivar call_type: + :ivar call_state: + :ivar answered_by: + :ivar processing_state: + :ivar created_time: The time at which the Call was created, given in ISO 8601 format. Can be different from `start_time` in the event of queueing due to CPS + :ivar start_time: The time at which the Call was started, given in ISO 8601 format. + :ivar end_time: The time at which the Call was ended, given in ISO 8601 format. + :ivar duration: Duration between when the call was initiated and the call was ended + :ivar connect_duration: Duration between when the call was answered and when it ended + :ivar _from: The calling party. + :ivar to: The called party. + :ivar carrier_edge: Contains metrics and properties for the Twilio media gateway of a PSTN call. + :ivar client_edge: Contains metrics and properties for the Twilio media gateway of a Client call. + :ivar sdk_edge: Contains metrics and properties for the SDK sensor library for Client calls. + :ivar sip_edge: Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. + :ivar tags: Tags applied to calls by Voice Insights analysis indicating a condition that could result in subjective degradation of the call quality. + :ivar url: The URL of this resource. + :ivar attributes: Attributes capturing call-flow-specific details. + :ivar properties: Contains edge-agnostic call-level details. + :ivar trust: Contains trusted communications details including Branded Call and verified caller ID. + :ivar annotation: Programmatically labeled annotations for the Call. Developers can update the Call Summary records with Annotation during or after a Call. Annotations can be updated as long as the Call Summary record is addressable via the API. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.call_type: Optional["CallSummaryInstance.CallType"] = payload.get( + "call_type" + ) + self.call_state: Optional["CallSummaryInstance.CallState"] = payload.get( + "call_state" + ) + self.answered_by: Optional["CallSummaryInstance.AnsweredBy"] = payload.get( + "answered_by" + ) + self.processing_state: Optional["CallSummaryInstance.ProcessingState"] = ( + payload.get("processing_state") + ) + self.created_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("created_time") + ) + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.duration: Optional[int] = deserialize.integer(payload.get("duration")) + self.connect_duration: Optional[int] = deserialize.integer( + payload.get("connect_duration") + ) + self._from: Optional[Dict[str, object]] = payload.get("from") + self.to: Optional[Dict[str, object]] = payload.get("to") + self.carrier_edge: Optional[Dict[str, object]] = payload.get("carrier_edge") + self.client_edge: Optional[Dict[str, object]] = payload.get("client_edge") + self.sdk_edge: Optional[Dict[str, object]] = payload.get("sdk_edge") + self.sip_edge: Optional[Dict[str, object]] = payload.get("sip_edge") + self.tags: Optional[List[str]] = payload.get("tags") + self.url: Optional[str] = payload.get("url") + self.attributes: Optional[Dict[str, object]] = payload.get("attributes") + self.properties: Optional[Dict[str, object]] = payload.get("properties") + self.trust: Optional[Dict[str, object]] = payload.get("trust") + self.annotation: Optional[Dict[str, object]] = payload.get("annotation") + + self._solution = { + "call_sid": call_sid, + } + self._context: Optional[CallSummaryContext] = None + + @property + def _proxy(self) -> "CallSummaryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CallSummaryContext for this CallSummaryInstance + """ + if self._context is None: + self._context = CallSummaryContext( + self._version, + call_sid=self._solution["call_sid"], + ) + return self._context + + def fetch( + self, + processing_state: Union[ + "CallSummaryInstance.ProcessingState", object + ] = values.unset, + ) -> "CallSummaryInstance": + """ + Fetch the CallSummaryInstance + + :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. + + :returns: The fetched CallSummaryInstance + """ + return self._proxy.fetch( + processing_state=processing_state, + ) + + async def fetch_async( + self, + processing_state: Union[ + "CallSummaryInstance.ProcessingState", object + ] = values.unset, + ) -> "CallSummaryInstance": + """ + Asynchronous coroutine to fetch the CallSummaryInstance + + :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. + + :returns: The fetched CallSummaryInstance + """ + return await self._proxy.fetch_async( + processing_state=processing_state, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Insights.V1.CallSummaryInstance {}>".format(context) + + +class CallSummaryContext(InstanceContext): + + def __init__(self, version: Version, call_sid: str): + """ + Initialize the CallSummaryContext + + :param version: Version that contains the resource + :param call_sid: The unique SID identifier of the Call. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "call_sid": call_sid, + } + self._uri = "/Voice/{call_sid}/Summary".format(**self._solution) + + def fetch( + self, + processing_state: Union[ + "CallSummaryInstance.ProcessingState", object + ] = values.unset, + ) -> CallSummaryInstance: + """ + Fetch the CallSummaryInstance + + :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. + + :returns: The fetched CallSummaryInstance + """ + + data = values.of( + { + "ProcessingState": processing_state, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return CallSummaryInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], + ) + + async def fetch_async( + self, + processing_state: Union[ + "CallSummaryInstance.ProcessingState", object + ] = values.unset, + ) -> CallSummaryInstance: + """ + Asynchronous coroutine to fetch the CallSummaryInstance + + :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. + + :returns: The fetched CallSummaryInstance + """ + + data = values.of( + { + "ProcessingState": processing_state, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return CallSummaryInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Insights.V1.CallSummaryContext {}>".format(context) + + +class CallSummaryList(ListResource): + + def __init__(self, version: Version, call_sid: str): + """ + Initialize the CallSummaryList + + :param version: Version that contains the resource + :param call_sid: The unique SID identifier of the Call. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "call_sid": call_sid, + } + + def get(self) -> CallSummaryContext: + """ + Constructs a CallSummaryContext + + """ + return CallSummaryContext(self._version, call_sid=self._solution["call_sid"]) + + def __call__(self) -> CallSummaryContext: + """ + Constructs a CallSummaryContext + + """ + return CallSummaryContext(self._version, call_sid=self._solution["call_sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Insights.V1.CallSummaryList>" diff --git a/twilio/rest/insights/v1/call/event.py b/twilio/rest/insights/v1/call/event.py new file mode 100644 index 0000000000..98dce5eb71 --- /dev/null +++ b/twilio/rest/insights/v1/call/event.py @@ -0,0 +1,337 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EventInstance(InstanceResource): + + class Level(object): + UNKNOWN = "UNKNOWN" + DEBUG = "DEBUG" + INFO = "INFO" + WARNING = "WARNING" + ERROR = "ERROR" + + class TwilioEdge(object): + UNKNOWN_EDGE = "unknown_edge" + CARRIER_EDGE = "carrier_edge" + SIP_EDGE = "sip_edge" + SDK_EDGE = "sdk_edge" + CLIENT_EDGE = "client_edge" + + """ + :ivar timestamp: Event time. + :ivar call_sid: The unique SID identifier of the Call. + :ivar account_sid: The unique SID identifier of the Account. + :ivar edge: + :ivar group: Event group. + :ivar level: + :ivar name: Event name. + :ivar carrier_edge: Represents the connection between Twilio and our immediate carrier partners. The events here describe the call lifecycle as reported by Twilio's carrier media gateways. + :ivar sip_edge: Represents the Twilio media gateway for SIP interface and SIP trunking calls. The events here describe the call lifecycle as reported by Twilio's public media gateways. + :ivar sdk_edge: Represents the Voice SDK running locally in the browser or in the Android/iOS application. The events here are emitted by the Voice SDK in response to certain call progress events, network changes, or call quality conditions. + :ivar client_edge: Represents the Twilio media gateway for Client calls. The events here describe the call lifecycle as reported by Twilio's Voice SDK media gateways. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): + super().__init__(version) + + self.timestamp: Optional[str] = payload.get("timestamp") + self.call_sid: Optional[str] = payload.get("call_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.edge: Optional["EventInstance.TwilioEdge"] = payload.get("edge") + self.group: Optional[str] = payload.get("group") + self.level: Optional["EventInstance.Level"] = payload.get("level") + self.name: Optional[str] = payload.get("name") + self.carrier_edge: Optional[Dict[str, object]] = payload.get("carrier_edge") + self.sip_edge: Optional[Dict[str, object]] = payload.get("sip_edge") + self.sdk_edge: Optional[Dict[str, object]] = payload.get("sdk_edge") + self.client_edge: Optional[Dict[str, object]] = payload.get("client_edge") + + self._solution = { + "call_sid": call_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Insights.V1.EventInstance {}>".format(context) + + +class EventPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EventInstance: + """ + Build an instance of EventInstance + + :param payload: Payload response from the API + """ + return EventInstance( + self._version, payload, call_sid=self._solution["call_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Insights.V1.EventPage>" + + +class EventList(ListResource): + + def __init__(self, version: Version, call_sid: str): + """ + Initialize the EventList + + :param version: Version that contains the resource + :param call_sid: The unique SID identifier of the Call. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "call_sid": call_sid, + } + self._uri = "/Voice/{call_sid}/Events".format(**self._solution) + + def stream( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EventInstance]: + """ + Streams EventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "EventInstance.TwilioEdge" edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(edge=edge, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EventInstance]: + """ + Asynchronously streams EventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "EventInstance.TwilioEdge" edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(edge=edge, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: + """ + Lists EventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "EventInstance.TwilioEdge" edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + edge=edge, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: + """ + Asynchronously lists EventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "EventInstance.TwilioEdge" edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + edge=edge, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventPage: + """ + Retrieve a single page of EventInstance records from the API. + Request is executed immediately + + :param edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventInstance + """ + data = values.of( + { + "Edge": edge, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response, self._solution) + + async def page_async( + self, + edge: Union["EventInstance.TwilioEdge", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventPage: + """ + Asynchronously retrieve a single page of EventInstance records from the API. + Request is executed immediately + + :param edge: The Edge of this Event. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventInstance + """ + data = values.of( + { + "Edge": edge, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> EventPage: + """ + Retrieve a specific page of EventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EventPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> EventPage: + """ + Asynchronously retrieve a specific page of EventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EventPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Insights.V1.EventList>" diff --git a/twilio/rest/insights/v1/call/metric.py b/twilio/rest/insights/v1/call/metric.py new file mode 100644 index 0000000000..77f770ae7c --- /dev/null +++ b/twilio/rest/insights/v1/call/metric.py @@ -0,0 +1,352 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MetricInstance(InstanceResource): + + class StreamDirection(object): + UNKNOWN = "unknown" + INBOUND = "inbound" + OUTBOUND = "outbound" + BOTH = "both" + + class TwilioEdge(object): + UNKNOWN_EDGE = "unknown_edge" + CARRIER_EDGE = "carrier_edge" + SIP_EDGE = "sip_edge" + SDK_EDGE = "sdk_edge" + CLIENT_EDGE = "client_edge" + + """ + :ivar timestamp: Timestamp of metric sample. Samples are taken every 10 seconds and contain the metrics for the previous 10 seconds. + :ivar call_sid: The unique SID identifier of the Call. + :ivar account_sid: The unique SID identifier of the Account. + :ivar edge: + :ivar direction: + :ivar carrier_edge: Contains metrics and properties for the Twilio media gateway of a PSTN call. + :ivar sip_edge: Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. + :ivar sdk_edge: Contains metrics and properties for the SDK sensor library for Client calls. + :ivar client_edge: Contains metrics and properties for the Twilio media gateway of a Client call. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): + super().__init__(version) + + self.timestamp: Optional[str] = payload.get("timestamp") + self.call_sid: Optional[str] = payload.get("call_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.edge: Optional["MetricInstance.TwilioEdge"] = payload.get("edge") + self.direction: Optional["MetricInstance.StreamDirection"] = payload.get( + "direction" + ) + self.carrier_edge: Optional[Dict[str, object]] = payload.get("carrier_edge") + self.sip_edge: Optional[Dict[str, object]] = payload.get("sip_edge") + self.sdk_edge: Optional[Dict[str, object]] = payload.get("sdk_edge") + self.client_edge: Optional[Dict[str, object]] = payload.get("client_edge") + + self._solution = { + "call_sid": call_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Insights.V1.MetricInstance {}>".format(context) + + +class MetricPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MetricInstance: + """ + Build an instance of MetricInstance + + :param payload: Payload response from the API + """ + return MetricInstance( + self._version, payload, call_sid=self._solution["call_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Insights.V1.MetricPage>" + + +class MetricList(ListResource): + + def __init__(self, version: Version, call_sid: str): + """ + Initialize the MetricList + + :param version: Version that contains the resource + :param call_sid: The unique SID identifier of the Call. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "call_sid": call_sid, + } + self._uri = "/Voice/{call_sid}/Metrics".format(**self._solution) + + def stream( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MetricInstance]: + """ + Streams MetricInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MetricInstance.TwilioEdge" edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param "MetricInstance.StreamDirection" direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(edge=edge, direction=direction, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MetricInstance]: + """ + Asynchronously streams MetricInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MetricInstance.TwilioEdge" edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param "MetricInstance.StreamDirection" direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + edge=edge, direction=direction, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MetricInstance]: + """ + Lists MetricInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MetricInstance.TwilioEdge" edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param "MetricInstance.StreamDirection" direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + edge=edge, + direction=direction, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MetricInstance]: + """ + Asynchronously lists MetricInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MetricInstance.TwilioEdge" edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param "MetricInstance.StreamDirection" direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + edge=edge, + direction=direction, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MetricPage: + """ + Retrieve a single page of MetricInstance records from the API. + Request is executed immediately + + :param edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MetricInstance + """ + data = values.of( + { + "Edge": edge, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MetricPage(self._version, response, self._solution) + + async def page_async( + self, + edge: Union["MetricInstance.TwilioEdge", object] = values.unset, + direction: Union["MetricInstance.StreamDirection", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MetricPage: + """ + Asynchronously retrieve a single page of MetricInstance records from the API. + Request is executed immediately + + :param edge: The Edge of this Metric. One of `unknown_edge`, `carrier_edge`, `sip_edge`, `sdk_edge` or `client_edge`. + :param direction: The Direction of this Metric. One of `unknown`, `inbound`, `outbound` or `both`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MetricInstance + """ + data = values.of( + { + "Edge": edge, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MetricPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MetricPage: + """ + Retrieve a specific page of MetricInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MetricInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MetricPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MetricPage: + """ + Asynchronously retrieve a specific page of MetricInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MetricInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MetricPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Insights.V1.MetricList>" diff --git a/twilio/rest/insights/v1/call_summaries.py b/twilio/rest/insights/v1/call_summaries.py new file mode 100644 index 0000000000..0a75e38454 --- /dev/null +++ b/twilio/rest/insights/v1/call_summaries.py @@ -0,0 +1,973 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CallSummariesInstance(InstanceResource): + + class AnsweredBy(object): + UNKNOWN = "unknown" + MACHINE_START = "machine_start" + MACHINE_END_BEEP = "machine_end_beep" + MACHINE_END_SILENCE = "machine_end_silence" + MACHINE_END_OTHER = "machine_end_other" + HUMAN = "human" + FAX = "fax" + + class CallState(object): + RINGING = "ringing" + COMPLETED = "completed" + BUSY = "busy" + FAIL = "fail" + NOANSWER = "noanswer" + CANCELED = "canceled" + ANSWERED = "answered" + UNDIALED = "undialed" + + class CallType(object): + CARRIER = "carrier" + SIP = "sip" + TRUNKING = "trunking" + CLIENT = "client" + WHATSAPP = "whatsapp" + + class ProcessingState(object): + COMPLETE = "complete" + PARTIAL = "partial" + + class ProcessingStateRequest(object): + COMPLETED = "completed" + STARTED = "started" + PARTIAL = "partial" + ALL = "all" + + class SortBy(object): + START_TIME = "start_time" + END_TIME = "end_time" + + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar call_sid: The unique SID identifier of the Call. + :ivar answered_by: + :ivar call_type: + :ivar call_state: + :ivar processing_state: + :ivar created_time: The time at which the Call was created, given in ISO 8601 format. Can be different from `start_time` in the event of queueing due to CPS + :ivar start_time: The time at which the Call was started, given in ISO 8601 format. + :ivar end_time: The time at which the Call was ended, given in ISO 8601 format. + :ivar duration: Duration between when the call was initiated and the call was ended + :ivar connect_duration: Duration between when the call was answered and when it ended + :ivar _from: The calling party. + :ivar to: The called party. + :ivar carrier_edge: Contains metrics and properties for the Twilio media gateway of a PSTN call. + :ivar client_edge: Contains metrics and properties for the Twilio media gateway of a Client call. + :ivar sdk_edge: Contains metrics and properties for the SDK sensor library for Client calls. + :ivar sip_edge: Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. + :ivar tags: Tags applied to calls by Voice Insights analysis indicating a condition that could result in subjective degradation of the call quality. + :ivar url: The URL of this resource. + :ivar attributes: Attributes capturing call-flow-specific details. + :ivar properties: Contains edge-agnostic call-level details. + :ivar trust: Contains trusted communications details including Branded Call and verified caller ID. + :ivar annotation: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.answered_by: Optional["CallSummariesInstance.AnsweredBy"] = payload.get( + "answered_by" + ) + self.call_type: Optional["CallSummariesInstance.CallType"] = payload.get( + "call_type" + ) + self.call_state: Optional["CallSummariesInstance.CallState"] = payload.get( + "call_state" + ) + self.processing_state: Optional["CallSummariesInstance.ProcessingState"] = ( + payload.get("processing_state") + ) + self.created_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("created_time") + ) + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.duration: Optional[int] = deserialize.integer(payload.get("duration")) + self.connect_duration: Optional[int] = deserialize.integer( + payload.get("connect_duration") + ) + self._from: Optional[Dict[str, object]] = payload.get("from") + self.to: Optional[Dict[str, object]] = payload.get("to") + self.carrier_edge: Optional[Dict[str, object]] = payload.get("carrier_edge") + self.client_edge: Optional[Dict[str, object]] = payload.get("client_edge") + self.sdk_edge: Optional[Dict[str, object]] = payload.get("sdk_edge") + self.sip_edge: Optional[Dict[str, object]] = payload.get("sip_edge") + self.tags: Optional[List[str]] = payload.get("tags") + self.url: Optional[str] = payload.get("url") + self.attributes: Optional[Dict[str, object]] = payload.get("attributes") + self.properties: Optional[Dict[str, object]] = payload.get("properties") + self.trust: Optional[Dict[str, object]] = payload.get("trust") + self.annotation: Optional[Dict[str, object]] = payload.get("annotation") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Insights.V1.CallSummariesInstance>" + + +class CallSummariesPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CallSummariesInstance: + """ + Build an instance of CallSummariesInstance + + :param payload: Payload response from the API + """ + return CallSummariesInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Insights.V1.CallSummariesPage>" + + +class CallSummariesList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CallSummariesList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Voice/Summaries" + + def stream( + self, + from_: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_carrier: Union[str, object] = values.unset, + to_carrier: Union[str, object] = values.unset, + from_country_code: Union[str, object] = values.unset, + to_country_code: Union[str, object] = values.unset, + verified_caller: Union[bool, object] = values.unset, + has_tag: Union[bool, object] = values.unset, + start_time: Union[str, object] = values.unset, + end_time: Union[str, object] = values.unset, + call_type: Union[str, object] = values.unset, + call_state: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + processing_state: Union[ + "CallSummariesInstance.ProcessingStateRequest", object + ] = values.unset, + sort_by: Union["CallSummariesInstance.SortBy", object] = values.unset, + subaccount: Union[str, object] = values.unset, + abnormal_session: Union[bool, object] = values.unset, + answered_by: Union["CallSummariesInstance.AnsweredBy", object] = values.unset, + answered_by_annotation: Union[str, object] = values.unset, + connectivity_issue_annotation: Union[str, object] = values.unset, + quality_issue_annotation: Union[str, object] = values.unset, + spam_annotation: Union[bool, object] = values.unset, + call_score_annotation: Union[str, object] = values.unset, + branded_enabled: Union[bool, object] = values.unset, + voice_integrity_enabled: Union[bool, object] = values.unset, + branded_bundle_sid: Union[str, object] = values.unset, + voice_integrity_bundle_sid: Union[str, object] = values.unset, + voice_integrity_use_case: Union[str, object] = values.unset, + business_profile_identity: Union[str, object] = values.unset, + business_profile_industry: Union[str, object] = values.unset, + business_profile_bundle_sid: Union[str, object] = values.unset, + business_profile_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CallSummariesInstance]: + """ + Streams CallSummariesInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str from_carrier: An origination carrier. + :param str to_carrier: A destination carrier. + :param str from_country_code: A source country code based on phone number in From. + :param str to_country_code: A destination country code. Based on phone number in To. + :param bool verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + :param bool has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). + :param str start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. + :param str end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. + :param str call_type: A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. + :param str call_state: A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. + :param str direction: A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. + :param "CallSummariesInstance.ProcessingStateRequest" processing_state: A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. + :param "CallSummariesInstance.SortBy" sort_by: A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. + :param str subaccount: A unique SID identifier of a Subaccount. + :param bool abnormal_session: A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. + :param "CallSummariesInstance.AnsweredBy" answered_by: An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. + :param str answered_by_annotation: Either machine or human. + :param str connectivity_issue_annotation: A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. + :param str quality_issue_annotation: A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. + :param bool spam_annotation: A boolean flag indicating spam calls. + :param str call_score_annotation: A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param bool branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' + :param bool voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' + :param str branded_bundle_sid: A unique SID identifier of the Branded Call. + :param str voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. + :param str voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. + :param str business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. + :param str business_profile_industry: A Business Industry of the calls. Is of type enum. One of 'automotive', 'agriculture', 'banking', 'consumer', 'construction', 'education', 'engineering', 'energy', 'oil_and_gas', 'fast_moving_consumer_goods', 'financial', 'fintech', 'food_and_beverage', 'government', 'healthcare', 'hospitality', 'insurance', 'legal', 'manufacturing', 'media', 'online', 'professional_services', 'raw_materials', 'real_estate', 'religion', 'retail', 'jewelry', 'technology', 'telecommunications', 'transportation', 'travel', 'electronics', 'not_for_profit' + :param str business_profile_bundle_sid: A unique SID identifier of the Business Profile. + :param str business_profile_type: A Business Profile Type of the calls. Is of type enum. One of 'primary', 'secondary'. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + from_=from_, + to=to, + from_carrier=from_carrier, + to_carrier=to_carrier, + from_country_code=from_country_code, + to_country_code=to_country_code, + verified_caller=verified_caller, + has_tag=has_tag, + start_time=start_time, + end_time=end_time, + call_type=call_type, + call_state=call_state, + direction=direction, + processing_state=processing_state, + sort_by=sort_by, + subaccount=subaccount, + abnormal_session=abnormal_session, + answered_by=answered_by, + answered_by_annotation=answered_by_annotation, + connectivity_issue_annotation=connectivity_issue_annotation, + quality_issue_annotation=quality_issue_annotation, + spam_annotation=spam_annotation, + call_score_annotation=call_score_annotation, + branded_enabled=branded_enabled, + voice_integrity_enabled=voice_integrity_enabled, + branded_bundle_sid=branded_bundle_sid, + voice_integrity_bundle_sid=voice_integrity_bundle_sid, + voice_integrity_use_case=voice_integrity_use_case, + business_profile_identity=business_profile_identity, + business_profile_industry=business_profile_industry, + business_profile_bundle_sid=business_profile_bundle_sid, + business_profile_type=business_profile_type, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + from_: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_carrier: Union[str, object] = values.unset, + to_carrier: Union[str, object] = values.unset, + from_country_code: Union[str, object] = values.unset, + to_country_code: Union[str, object] = values.unset, + verified_caller: Union[bool, object] = values.unset, + has_tag: Union[bool, object] = values.unset, + start_time: Union[str, object] = values.unset, + end_time: Union[str, object] = values.unset, + call_type: Union[str, object] = values.unset, + call_state: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + processing_state: Union[ + "CallSummariesInstance.ProcessingStateRequest", object + ] = values.unset, + sort_by: Union["CallSummariesInstance.SortBy", object] = values.unset, + subaccount: Union[str, object] = values.unset, + abnormal_session: Union[bool, object] = values.unset, + answered_by: Union["CallSummariesInstance.AnsweredBy", object] = values.unset, + answered_by_annotation: Union[str, object] = values.unset, + connectivity_issue_annotation: Union[str, object] = values.unset, + quality_issue_annotation: Union[str, object] = values.unset, + spam_annotation: Union[bool, object] = values.unset, + call_score_annotation: Union[str, object] = values.unset, + branded_enabled: Union[bool, object] = values.unset, + voice_integrity_enabled: Union[bool, object] = values.unset, + branded_bundle_sid: Union[str, object] = values.unset, + voice_integrity_bundle_sid: Union[str, object] = values.unset, + voice_integrity_use_case: Union[str, object] = values.unset, + business_profile_identity: Union[str, object] = values.unset, + business_profile_industry: Union[str, object] = values.unset, + business_profile_bundle_sid: Union[str, object] = values.unset, + business_profile_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CallSummariesInstance]: + """ + Asynchronously streams CallSummariesInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str from_carrier: An origination carrier. + :param str to_carrier: A destination carrier. + :param str from_country_code: A source country code based on phone number in From. + :param str to_country_code: A destination country code. Based on phone number in To. + :param bool verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + :param bool has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). + :param str start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. + :param str end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. + :param str call_type: A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. + :param str call_state: A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. + :param str direction: A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. + :param "CallSummariesInstance.ProcessingStateRequest" processing_state: A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. + :param "CallSummariesInstance.SortBy" sort_by: A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. + :param str subaccount: A unique SID identifier of a Subaccount. + :param bool abnormal_session: A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. + :param "CallSummariesInstance.AnsweredBy" answered_by: An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. + :param str answered_by_annotation: Either machine or human. + :param str connectivity_issue_annotation: A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. + :param str quality_issue_annotation: A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. + :param bool spam_annotation: A boolean flag indicating spam calls. + :param str call_score_annotation: A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param bool branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' + :param bool voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' + :param str branded_bundle_sid: A unique SID identifier of the Branded Call. + :param str voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. + :param str voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. + :param str business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. + :param str business_profile_industry: A Business Industry of the calls. Is of type enum. One of 'automotive', 'agriculture', 'banking', 'consumer', 'construction', 'education', 'engineering', 'energy', 'oil_and_gas', 'fast_moving_consumer_goods', 'financial', 'fintech', 'food_and_beverage', 'government', 'healthcare', 'hospitality', 'insurance', 'legal', 'manufacturing', 'media', 'online', 'professional_services', 'raw_materials', 'real_estate', 'religion', 'retail', 'jewelry', 'technology', 'telecommunications', 'transportation', 'travel', 'electronics', 'not_for_profit' + :param str business_profile_bundle_sid: A unique SID identifier of the Business Profile. + :param str business_profile_type: A Business Profile Type of the calls. Is of type enum. One of 'primary', 'secondary'. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + from_=from_, + to=to, + from_carrier=from_carrier, + to_carrier=to_carrier, + from_country_code=from_country_code, + to_country_code=to_country_code, + verified_caller=verified_caller, + has_tag=has_tag, + start_time=start_time, + end_time=end_time, + call_type=call_type, + call_state=call_state, + direction=direction, + processing_state=processing_state, + sort_by=sort_by, + subaccount=subaccount, + abnormal_session=abnormal_session, + answered_by=answered_by, + answered_by_annotation=answered_by_annotation, + connectivity_issue_annotation=connectivity_issue_annotation, + quality_issue_annotation=quality_issue_annotation, + spam_annotation=spam_annotation, + call_score_annotation=call_score_annotation, + branded_enabled=branded_enabled, + voice_integrity_enabled=voice_integrity_enabled, + branded_bundle_sid=branded_bundle_sid, + voice_integrity_bundle_sid=voice_integrity_bundle_sid, + voice_integrity_use_case=voice_integrity_use_case, + business_profile_identity=business_profile_identity, + business_profile_industry=business_profile_industry, + business_profile_bundle_sid=business_profile_bundle_sid, + business_profile_type=business_profile_type, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + from_: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_carrier: Union[str, object] = values.unset, + to_carrier: Union[str, object] = values.unset, + from_country_code: Union[str, object] = values.unset, + to_country_code: Union[str, object] = values.unset, + verified_caller: Union[bool, object] = values.unset, + has_tag: Union[bool, object] = values.unset, + start_time: Union[str, object] = values.unset, + end_time: Union[str, object] = values.unset, + call_type: Union[str, object] = values.unset, + call_state: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + processing_state: Union[ + "CallSummariesInstance.ProcessingStateRequest", object + ] = values.unset, + sort_by: Union["CallSummariesInstance.SortBy", object] = values.unset, + subaccount: Union[str, object] = values.unset, + abnormal_session: Union[bool, object] = values.unset, + answered_by: Union["CallSummariesInstance.AnsweredBy", object] = values.unset, + answered_by_annotation: Union[str, object] = values.unset, + connectivity_issue_annotation: Union[str, object] = values.unset, + quality_issue_annotation: Union[str, object] = values.unset, + spam_annotation: Union[bool, object] = values.unset, + call_score_annotation: Union[str, object] = values.unset, + branded_enabled: Union[bool, object] = values.unset, + voice_integrity_enabled: Union[bool, object] = values.unset, + branded_bundle_sid: Union[str, object] = values.unset, + voice_integrity_bundle_sid: Union[str, object] = values.unset, + voice_integrity_use_case: Union[str, object] = values.unset, + business_profile_identity: Union[str, object] = values.unset, + business_profile_industry: Union[str, object] = values.unset, + business_profile_bundle_sid: Union[str, object] = values.unset, + business_profile_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CallSummariesInstance]: + """ + Lists CallSummariesInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str from_carrier: An origination carrier. + :param str to_carrier: A destination carrier. + :param str from_country_code: A source country code based on phone number in From. + :param str to_country_code: A destination country code. Based on phone number in To. + :param bool verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + :param bool has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). + :param str start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. + :param str end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. + :param str call_type: A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. + :param str call_state: A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. + :param str direction: A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. + :param "CallSummariesInstance.ProcessingStateRequest" processing_state: A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. + :param "CallSummariesInstance.SortBy" sort_by: A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. + :param str subaccount: A unique SID identifier of a Subaccount. + :param bool abnormal_session: A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. + :param "CallSummariesInstance.AnsweredBy" answered_by: An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. + :param str answered_by_annotation: Either machine or human. + :param str connectivity_issue_annotation: A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. + :param str quality_issue_annotation: A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. + :param bool spam_annotation: A boolean flag indicating spam calls. + :param str call_score_annotation: A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param bool branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' + :param bool voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' + :param str branded_bundle_sid: A unique SID identifier of the Branded Call. + :param str voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. + :param str voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. + :param str business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. + :param str business_profile_industry: A Business Industry of the calls. Is of type enum. One of 'automotive', 'agriculture', 'banking', 'consumer', 'construction', 'education', 'engineering', 'energy', 'oil_and_gas', 'fast_moving_consumer_goods', 'financial', 'fintech', 'food_and_beverage', 'government', 'healthcare', 'hospitality', 'insurance', 'legal', 'manufacturing', 'media', 'online', 'professional_services', 'raw_materials', 'real_estate', 'religion', 'retail', 'jewelry', 'technology', 'telecommunications', 'transportation', 'travel', 'electronics', 'not_for_profit' + :param str business_profile_bundle_sid: A unique SID identifier of the Business Profile. + :param str business_profile_type: A Business Profile Type of the calls. Is of type enum. One of 'primary', 'secondary'. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + from_=from_, + to=to, + from_carrier=from_carrier, + to_carrier=to_carrier, + from_country_code=from_country_code, + to_country_code=to_country_code, + verified_caller=verified_caller, + has_tag=has_tag, + start_time=start_time, + end_time=end_time, + call_type=call_type, + call_state=call_state, + direction=direction, + processing_state=processing_state, + sort_by=sort_by, + subaccount=subaccount, + abnormal_session=abnormal_session, + answered_by=answered_by, + answered_by_annotation=answered_by_annotation, + connectivity_issue_annotation=connectivity_issue_annotation, + quality_issue_annotation=quality_issue_annotation, + spam_annotation=spam_annotation, + call_score_annotation=call_score_annotation, + branded_enabled=branded_enabled, + voice_integrity_enabled=voice_integrity_enabled, + branded_bundle_sid=branded_bundle_sid, + voice_integrity_bundle_sid=voice_integrity_bundle_sid, + voice_integrity_use_case=voice_integrity_use_case, + business_profile_identity=business_profile_identity, + business_profile_industry=business_profile_industry, + business_profile_bundle_sid=business_profile_bundle_sid, + business_profile_type=business_profile_type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + from_: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_carrier: Union[str, object] = values.unset, + to_carrier: Union[str, object] = values.unset, + from_country_code: Union[str, object] = values.unset, + to_country_code: Union[str, object] = values.unset, + verified_caller: Union[bool, object] = values.unset, + has_tag: Union[bool, object] = values.unset, + start_time: Union[str, object] = values.unset, + end_time: Union[str, object] = values.unset, + call_type: Union[str, object] = values.unset, + call_state: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + processing_state: Union[ + "CallSummariesInstance.ProcessingStateRequest", object + ] = values.unset, + sort_by: Union["CallSummariesInstance.SortBy", object] = values.unset, + subaccount: Union[str, object] = values.unset, + abnormal_session: Union[bool, object] = values.unset, + answered_by: Union["CallSummariesInstance.AnsweredBy", object] = values.unset, + answered_by_annotation: Union[str, object] = values.unset, + connectivity_issue_annotation: Union[str, object] = values.unset, + quality_issue_annotation: Union[str, object] = values.unset, + spam_annotation: Union[bool, object] = values.unset, + call_score_annotation: Union[str, object] = values.unset, + branded_enabled: Union[bool, object] = values.unset, + voice_integrity_enabled: Union[bool, object] = values.unset, + branded_bundle_sid: Union[str, object] = values.unset, + voice_integrity_bundle_sid: Union[str, object] = values.unset, + voice_integrity_use_case: Union[str, object] = values.unset, + business_profile_identity: Union[str, object] = values.unset, + business_profile_industry: Union[str, object] = values.unset, + business_profile_bundle_sid: Union[str, object] = values.unset, + business_profile_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CallSummariesInstance]: + """ + Asynchronously lists CallSummariesInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param str from_carrier: An origination carrier. + :param str to_carrier: A destination carrier. + :param str from_country_code: A source country code based on phone number in From. + :param str to_country_code: A destination country code. Based on phone number in To. + :param bool verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + :param bool has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). + :param str start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. + :param str end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. + :param str call_type: A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. + :param str call_state: A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. + :param str direction: A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. + :param "CallSummariesInstance.ProcessingStateRequest" processing_state: A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. + :param "CallSummariesInstance.SortBy" sort_by: A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. + :param str subaccount: A unique SID identifier of a Subaccount. + :param bool abnormal_session: A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. + :param "CallSummariesInstance.AnsweredBy" answered_by: An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. + :param str answered_by_annotation: Either machine or human. + :param str connectivity_issue_annotation: A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. + :param str quality_issue_annotation: A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. + :param bool spam_annotation: A boolean flag indicating spam calls. + :param str call_score_annotation: A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param bool branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' + :param bool voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' + :param str branded_bundle_sid: A unique SID identifier of the Branded Call. + :param str voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. + :param str voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. + :param str business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. + :param str business_profile_industry: A Business Industry of the calls. Is of type enum. One of 'automotive', 'agriculture', 'banking', 'consumer', 'construction', 'education', 'engineering', 'energy', 'oil_and_gas', 'fast_moving_consumer_goods', 'financial', 'fintech', 'food_and_beverage', 'government', 'healthcare', 'hospitality', 'insurance', 'legal', 'manufacturing', 'media', 'online', 'professional_services', 'raw_materials', 'real_estate', 'religion', 'retail', 'jewelry', 'technology', 'telecommunications', 'transportation', 'travel', 'electronics', 'not_for_profit' + :param str business_profile_bundle_sid: A unique SID identifier of the Business Profile. + :param str business_profile_type: A Business Profile Type of the calls. Is of type enum. One of 'primary', 'secondary'. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + from_=from_, + to=to, + from_carrier=from_carrier, + to_carrier=to_carrier, + from_country_code=from_country_code, + to_country_code=to_country_code, + verified_caller=verified_caller, + has_tag=has_tag, + start_time=start_time, + end_time=end_time, + call_type=call_type, + call_state=call_state, + direction=direction, + processing_state=processing_state, + sort_by=sort_by, + subaccount=subaccount, + abnormal_session=abnormal_session, + answered_by=answered_by, + answered_by_annotation=answered_by_annotation, + connectivity_issue_annotation=connectivity_issue_annotation, + quality_issue_annotation=quality_issue_annotation, + spam_annotation=spam_annotation, + call_score_annotation=call_score_annotation, + branded_enabled=branded_enabled, + voice_integrity_enabled=voice_integrity_enabled, + branded_bundle_sid=branded_bundle_sid, + voice_integrity_bundle_sid=voice_integrity_bundle_sid, + voice_integrity_use_case=voice_integrity_use_case, + business_profile_identity=business_profile_identity, + business_profile_industry=business_profile_industry, + business_profile_bundle_sid=business_profile_bundle_sid, + business_profile_type=business_profile_type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + from_: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_carrier: Union[str, object] = values.unset, + to_carrier: Union[str, object] = values.unset, + from_country_code: Union[str, object] = values.unset, + to_country_code: Union[str, object] = values.unset, + verified_caller: Union[bool, object] = values.unset, + has_tag: Union[bool, object] = values.unset, + start_time: Union[str, object] = values.unset, + end_time: Union[str, object] = values.unset, + call_type: Union[str, object] = values.unset, + call_state: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + processing_state: Union[ + "CallSummariesInstance.ProcessingStateRequest", object + ] = values.unset, + sort_by: Union["CallSummariesInstance.SortBy", object] = values.unset, + subaccount: Union[str, object] = values.unset, + abnormal_session: Union[bool, object] = values.unset, + answered_by: Union["CallSummariesInstance.AnsweredBy", object] = values.unset, + answered_by_annotation: Union[str, object] = values.unset, + connectivity_issue_annotation: Union[str, object] = values.unset, + quality_issue_annotation: Union[str, object] = values.unset, + spam_annotation: Union[bool, object] = values.unset, + call_score_annotation: Union[str, object] = values.unset, + branded_enabled: Union[bool, object] = values.unset, + voice_integrity_enabled: Union[bool, object] = values.unset, + branded_bundle_sid: Union[str, object] = values.unset, + voice_integrity_bundle_sid: Union[str, object] = values.unset, + voice_integrity_use_case: Union[str, object] = values.unset, + business_profile_identity: Union[str, object] = values.unset, + business_profile_industry: Union[str, object] = values.unset, + business_profile_bundle_sid: Union[str, object] = values.unset, + business_profile_type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CallSummariesPage: + """ + Retrieve a single page of CallSummariesInstance records from the API. + Request is executed immediately + + :param from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param from_carrier: An origination carrier. + :param to_carrier: A destination carrier. + :param from_country_code: A source country code based on phone number in From. + :param to_country_code: A destination country code. Based on phone number in To. + :param verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + :param has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). + :param start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. + :param end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. + :param call_type: A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. + :param call_state: A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. + :param direction: A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. + :param processing_state: A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. + :param sort_by: A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. + :param subaccount: A unique SID identifier of a Subaccount. + :param abnormal_session: A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. + :param answered_by: An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. + :param answered_by_annotation: Either machine or human. + :param connectivity_issue_annotation: A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. + :param quality_issue_annotation: A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. + :param spam_annotation: A boolean flag indicating spam calls. + :param call_score_annotation: A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' + :param voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' + :param branded_bundle_sid: A unique SID identifier of the Branded Call. + :param voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. + :param voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. + :param business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. + :param business_profile_industry: A Business Industry of the calls. Is of type enum. One of 'automotive', 'agriculture', 'banking', 'consumer', 'construction', 'education', 'engineering', 'energy', 'oil_and_gas', 'fast_moving_consumer_goods', 'financial', 'fintech', 'food_and_beverage', 'government', 'healthcare', 'hospitality', 'insurance', 'legal', 'manufacturing', 'media', 'online', 'professional_services', 'raw_materials', 'real_estate', 'religion', 'retail', 'jewelry', 'technology', 'telecommunications', 'transportation', 'travel', 'electronics', 'not_for_profit' + :param business_profile_bundle_sid: A unique SID identifier of the Business Profile. + :param business_profile_type: A Business Profile Type of the calls. Is of type enum. One of 'primary', 'secondary'. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CallSummariesInstance + """ + data = values.of( + { + "From": from_, + "To": to, + "FromCarrier": from_carrier, + "ToCarrier": to_carrier, + "FromCountryCode": from_country_code, + "ToCountryCode": to_country_code, + "VerifiedCaller": serialize.boolean_to_string(verified_caller), + "HasTag": serialize.boolean_to_string(has_tag), + "StartTime": start_time, + "EndTime": end_time, + "CallType": call_type, + "CallState": call_state, + "Direction": direction, + "ProcessingState": processing_state, + "SortBy": sort_by, + "Subaccount": subaccount, + "AbnormalSession": serialize.boolean_to_string(abnormal_session), + "AnsweredBy": answered_by, + "AnsweredByAnnotation": answered_by_annotation, + "ConnectivityIssueAnnotation": connectivity_issue_annotation, + "QualityIssueAnnotation": quality_issue_annotation, + "SpamAnnotation": serialize.boolean_to_string(spam_annotation), + "CallScoreAnnotation": call_score_annotation, + "BrandedEnabled": serialize.boolean_to_string(branded_enabled), + "VoiceIntegrityEnabled": serialize.boolean_to_string( + voice_integrity_enabled + ), + "BrandedBundleSid": branded_bundle_sid, + "VoiceIntegrityBundleSid": voice_integrity_bundle_sid, + "VoiceIntegrityUseCase": voice_integrity_use_case, + "BusinessProfileIdentity": business_profile_identity, + "BusinessProfileIndustry": business_profile_industry, + "BusinessProfileBundleSid": business_profile_bundle_sid, + "BusinessProfileType": business_profile_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CallSummariesPage(self._version, response) + + async def page_async( + self, + from_: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_carrier: Union[str, object] = values.unset, + to_carrier: Union[str, object] = values.unset, + from_country_code: Union[str, object] = values.unset, + to_country_code: Union[str, object] = values.unset, + verified_caller: Union[bool, object] = values.unset, + has_tag: Union[bool, object] = values.unset, + start_time: Union[str, object] = values.unset, + end_time: Union[str, object] = values.unset, + call_type: Union[str, object] = values.unset, + call_state: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + processing_state: Union[ + "CallSummariesInstance.ProcessingStateRequest", object + ] = values.unset, + sort_by: Union["CallSummariesInstance.SortBy", object] = values.unset, + subaccount: Union[str, object] = values.unset, + abnormal_session: Union[bool, object] = values.unset, + answered_by: Union["CallSummariesInstance.AnsweredBy", object] = values.unset, + answered_by_annotation: Union[str, object] = values.unset, + connectivity_issue_annotation: Union[str, object] = values.unset, + quality_issue_annotation: Union[str, object] = values.unset, + spam_annotation: Union[bool, object] = values.unset, + call_score_annotation: Union[str, object] = values.unset, + branded_enabled: Union[bool, object] = values.unset, + voice_integrity_enabled: Union[bool, object] = values.unset, + branded_bundle_sid: Union[str, object] = values.unset, + voice_integrity_bundle_sid: Union[str, object] = values.unset, + voice_integrity_use_case: Union[str, object] = values.unset, + business_profile_identity: Union[str, object] = values.unset, + business_profile_industry: Union[str, object] = values.unset, + business_profile_bundle_sid: Union[str, object] = values.unset, + business_profile_type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CallSummariesPage: + """ + Asynchronously retrieve a single page of CallSummariesInstance records from the API. + Request is executed immediately + + :param from_: A calling party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param to: A called party. Could be an E.164 number, a SIP URI, or a Twilio Client registered name. + :param from_carrier: An origination carrier. + :param to_carrier: A destination carrier. + :param from_country_code: A source country code based on phone number in From. + :param to_country_code: A destination country code. Based on phone number in To. + :param verified_caller: A boolean flag indicating whether or not the caller was verified using SHAKEN/STIR.One of 'true' or 'false'. + :param has_tag: A boolean flag indicating the presence of one or more [Voice Insights Call Tags](https://www.twilio.com/docs/voice/voice-insights/api/call/details-call-tags). + :param start_time: A Start time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 4h. + :param end_time: An End Time of the calls. xm (x minutes), xh (x hours), xd (x days), 1w, 30m, 3d, 4w or datetime-ISO. Defaults to 0m. + :param call_type: A Call Type of the calls. One of `carrier`, `sip`, `trunking` or `client`. + :param call_state: A Call State of the calls. One of `ringing`, `completed`, `busy`, `fail`, `noanswer`, `canceled`, `answered`, `undialed`. + :param direction: A Direction of the calls. One of `outbound_api`, `outbound_dial`, `inbound`, `trunking_originating`, `trunking_terminating`. + :param processing_state: A Processing State of the Call Summaries. One of `completed`, `partial` or `all`. + :param sort_by: A Sort By criterion for the returned list of Call Summaries. One of `start_time` or `end_time`. + :param subaccount: A unique SID identifier of a Subaccount. + :param abnormal_session: A boolean flag indicating an abnormal session where the last SIP response was not 200 OK. + :param answered_by: An Answered By value for the calls based on `Answering Machine Detection (AMD)`. One of `unknown`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `human` or `fax`. + :param answered_by_annotation: Either machine or human. + :param connectivity_issue_annotation: A Connectivity Issue with the calls. One of `no_connectivity_issue`, `invalid_number`, `caller_id`, `dropped_call`, or `number_reachability`. + :param quality_issue_annotation: A subjective Quality Issue with the calls. One of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, `static_noise`. + :param spam_annotation: A boolean flag indicating spam calls. + :param call_score_annotation: A Call Score of the calls. Use a range of 1-5 to indicate the call experience score, with the following mapping as a reference for the rated call [5: Excellent, 4: Good, 3 : Fair, 2 : Poor, 1: Bad]. + :param branded_enabled: A boolean flag indicating whether or not the calls were branded using Twilio Branded Calls. One of 'true' or 'false' + :param voice_integrity_enabled: A boolean flag indicating whether or not the phone number had voice integrity enabled.One of 'true' or 'false' + :param branded_bundle_sid: A unique SID identifier of the Branded Call. + :param voice_integrity_bundle_sid: A unique SID identifier of the Voice Integrity Profile. + :param voice_integrity_use_case: A Voice Integrity Use Case . Is of type enum. One of 'abandoned_cart', 'appointment_reminders', 'appointment_scheduling', 'asset_management', 'automated_support', 'call_tracking', 'click_to_call', 'contact_tracing', 'contactless_delivery', 'customer_support', 'dating/social', 'delivery_notifications', 'distance_learning', 'emergency_notifications', 'employee_notifications', 'exam_proctoring', 'field_notifications', 'first_responder', 'fraud_alerts', 'group_messaging', 'identify_&_verification', 'intelligent_routing', 'lead_alerts', 'lead_distribution', 'lead_generation', 'lead_management', 'lead_nurturing', 'marketing_events', 'mass_alerts', 'meetings/collaboration', 'order_notifications', 'outbound_dialer', 'pharmacy', 'phone_system', 'purchase_confirmation', 'remote_appointments', 'rewards_program', 'self-service', 'service_alerts', 'shift_management', 'survey/research', 'telehealth', 'telemarketing', 'therapy_(individual+group)'. + :param business_profile_identity: A Business Identity of the calls. Is of type enum. One of 'direct_customer', 'isv_reseller_or_partner'. + :param business_profile_industry: A Business Industry of the calls. Is of type enum. One of 'automotive', 'agriculture', 'banking', 'consumer', 'construction', 'education', 'engineering', 'energy', 'oil_and_gas', 'fast_moving_consumer_goods', 'financial', 'fintech', 'food_and_beverage', 'government', 'healthcare', 'hospitality', 'insurance', 'legal', 'manufacturing', 'media', 'online', 'professional_services', 'raw_materials', 'real_estate', 'religion', 'retail', 'jewelry', 'technology', 'telecommunications', 'transportation', 'travel', 'electronics', 'not_for_profit' + :param business_profile_bundle_sid: A unique SID identifier of the Business Profile. + :param business_profile_type: A Business Profile Type of the calls. Is of type enum. One of 'primary', 'secondary'. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CallSummariesInstance + """ + data = values.of( + { + "From": from_, + "To": to, + "FromCarrier": from_carrier, + "ToCarrier": to_carrier, + "FromCountryCode": from_country_code, + "ToCountryCode": to_country_code, + "VerifiedCaller": serialize.boolean_to_string(verified_caller), + "HasTag": serialize.boolean_to_string(has_tag), + "StartTime": start_time, + "EndTime": end_time, + "CallType": call_type, + "CallState": call_state, + "Direction": direction, + "ProcessingState": processing_state, + "SortBy": sort_by, + "Subaccount": subaccount, + "AbnormalSession": serialize.boolean_to_string(abnormal_session), + "AnsweredBy": answered_by, + "AnsweredByAnnotation": answered_by_annotation, + "ConnectivityIssueAnnotation": connectivity_issue_annotation, + "QualityIssueAnnotation": quality_issue_annotation, + "SpamAnnotation": serialize.boolean_to_string(spam_annotation), + "CallScoreAnnotation": call_score_annotation, + "BrandedEnabled": serialize.boolean_to_string(branded_enabled), + "VoiceIntegrityEnabled": serialize.boolean_to_string( + voice_integrity_enabled + ), + "BrandedBundleSid": branded_bundle_sid, + "VoiceIntegrityBundleSid": voice_integrity_bundle_sid, + "VoiceIntegrityUseCase": voice_integrity_use_case, + "BusinessProfileIdentity": business_profile_identity, + "BusinessProfileIndustry": business_profile_industry, + "BusinessProfileBundleSid": business_profile_bundle_sid, + "BusinessProfileType": business_profile_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CallSummariesPage(self._version, response) + + def get_page(self, target_url: str) -> CallSummariesPage: + """ + Retrieve a specific page of CallSummariesInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CallSummariesInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CallSummariesPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CallSummariesPage: + """ + Asynchronously retrieve a specific page of CallSummariesInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CallSummariesInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CallSummariesPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Insights.V1.CallSummariesList>" diff --git a/twilio/rest/insights/v1/conference/__init__.py b/twilio/rest/insights/v1/conference/__init__.py new file mode 100644 index 0000000000..ef3c51dac3 --- /dev/null +++ b/twilio/rest/insights/v1/conference/__init__.py @@ -0,0 +1,732 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.insights.v1.conference.conference_participant import ( + ConferenceParticipantList, +) + + +class ConferenceInstance(InstanceResource): + + class ConferenceEndReason(object): + LAST_PARTICIPANT_LEFT = "last_participant_left" + CONFERENCE_ENDED_VIA_API = "conference_ended_via_api" + PARTICIPANT_WITH_END_CONFERENCE_ON_EXIT_LEFT = ( + "participant_with_end_conference_on_exit_left" + ) + LAST_PARTICIPANT_KICKED = "last_participant_kicked" + PARTICIPANT_WITH_END_CONFERENCE_ON_EXIT_KICKED = ( + "participant_with_end_conference_on_exit_kicked" + ) + + class ConferenceStatus(object): + IN_PROGRESS = "in_progress" + NOT_STARTED = "not_started" + COMPLETED = "completed" + SUMMARY_TIMEOUT = "summary_timeout" + + class ProcessingState(object): + COMPLETE = "complete" + IN_PROGRESS = "in_progress" + TIMEOUT = "timeout" + + class Region(object): + US1 = "us1" + US2 = "us2" + AU1 = "au1" + BR1 = "br1" + IE1 = "ie1" + JP1 = "jp1" + SG1 = "sg1" + DE1 = "de1" + IN1 = "in1" + + class Tag(object): + INVALID_REQUESTED_REGION = "invalid_requested_region" + DUPLICATE_IDENTITY = "duplicate_identity" + START_FAILURE = "start_failure" + REGION_CONFIGURATION_ISSUES = "region_configuration_issues" + QUALITY_WARNINGS = "quality_warnings" + PARTICIPANT_BEHAVIOR_ISSUES = "participant_behavior_issues" + HIGH_PACKET_LOSS = "high_packet_loss" + HIGH_JITTER = "high_jitter" + HIGH_LATENCY = "high_latency" + LOW_MOS = "low_mos" + DETECTED_SILENCE = "detected_silence" + NO_CONCURRENT_PARTICIPANTS = "no_concurrent_participants" + + """ + :ivar conference_sid: The unique SID identifier of the Conference. + :ivar account_sid: The unique SID identifier of the Account. + :ivar friendly_name: Custom label for the conference resource, up to 64 characters. + :ivar create_time: Conference creation date and time in ISO 8601 format. + :ivar start_time: Timestamp in ISO 8601 format when the conference started. Conferences do not start until at least two participants join, at least one of whom has startConferenceOnEnter=true. + :ivar end_time: Conference end date and time in ISO 8601 format. + :ivar duration_seconds: Conference duration in seconds. + :ivar connect_duration_seconds: Duration of the between conference start event and conference end event in seconds. + :ivar status: + :ivar max_participants: Maximum number of concurrent participants as specified by the configuration. + :ivar max_concurrent_participants: Actual maximum number of concurrent participants in the conference. + :ivar unique_participants: Unique conference participants based on caller ID. + :ivar end_reason: + :ivar ended_by: Call SID of the participant whose actions ended the conference. + :ivar mixer_region: + :ivar mixer_region_requested: + :ivar recording_enabled: Boolean. Indicates whether recording was enabled at the conference mixer. + :ivar detected_issues: Potential issues detected by Twilio during the conference. + :ivar tags: Tags for detected conference conditions and participant behaviors which may be of interest. + :ivar tag_info: Object. Contains details about conference tags including severity. + :ivar processing_state: + :ivar url: The URL of this resource. + :ivar links: Contains a dictionary of URL links to nested resources of this Conference. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conference_sid: Optional[str] = None, + ): + super().__init__(version) + + self.conference_sid: Optional[str] = payload.get("conference_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.create_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("create_time") + ) + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.duration_seconds: Optional[int] = deserialize.integer( + payload.get("duration_seconds") + ) + self.connect_duration_seconds: Optional[int] = deserialize.integer( + payload.get("connect_duration_seconds") + ) + self.status: Optional["ConferenceInstance.ConferenceStatus"] = payload.get( + "status" + ) + self.max_participants: Optional[int] = deserialize.integer( + payload.get("max_participants") + ) + self.max_concurrent_participants: Optional[int] = deserialize.integer( + payload.get("max_concurrent_participants") + ) + self.unique_participants: Optional[int] = deserialize.integer( + payload.get("unique_participants") + ) + self.end_reason: Optional["ConferenceInstance.ConferenceEndReason"] = ( + payload.get("end_reason") + ) + self.ended_by: Optional[str] = payload.get("ended_by") + self.mixer_region: Optional["ConferenceInstance.Region"] = payload.get( + "mixer_region" + ) + self.mixer_region_requested: Optional["ConferenceInstance.Region"] = ( + payload.get("mixer_region_requested") + ) + self.recording_enabled: Optional[bool] = payload.get("recording_enabled") + self.detected_issues: Optional[Dict[str, object]] = payload.get( + "detected_issues" + ) + self.tags: Optional[List["ConferenceInstance.Tag"]] = payload.get("tags") + self.tag_info: Optional[Dict[str, object]] = payload.get("tag_info") + self.processing_state: Optional["ConferenceInstance.ProcessingState"] = ( + payload.get("processing_state") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "conference_sid": conference_sid or self.conference_sid, + } + self._context: Optional[ConferenceContext] = None + + @property + def _proxy(self) -> "ConferenceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConferenceContext for this ConferenceInstance + """ + if self._context is None: + self._context = ConferenceContext( + self._version, + conference_sid=self._solution["conference_sid"], + ) + return self._context + + def fetch(self) -> "ConferenceInstance": + """ + Fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConferenceInstance": + """ + Asynchronous coroutine to fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + return await self._proxy.fetch_async() + + @property + def conference_participants(self) -> ConferenceParticipantList: + """ + Access the conference_participants + """ + return self._proxy.conference_participants + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Insights.V1.ConferenceInstance {}>".format(context) + + +class ConferenceContext(InstanceContext): + + def __init__(self, version: Version, conference_sid: str): + """ + Initialize the ConferenceContext + + :param version: Version that contains the resource + :param conference_sid: The unique SID identifier of the Conference. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conference_sid": conference_sid, + } + self._uri = "/Conferences/{conference_sid}".format(**self._solution) + + self._conference_participants: Optional[ConferenceParticipantList] = None + + def fetch(self) -> ConferenceInstance: + """ + Fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ConferenceInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], + ) + + async def fetch_async(self) -> ConferenceInstance: + """ + Asynchronous coroutine to fetch the ConferenceInstance + + + :returns: The fetched ConferenceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ConferenceInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], + ) + + @property + def conference_participants(self) -> ConferenceParticipantList: + """ + Access the conference_participants + """ + if self._conference_participants is None: + self._conference_participants = ConferenceParticipantList( + self._version, + self._solution["conference_sid"], + ) + return self._conference_participants + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Insights.V1.ConferenceContext {}>".format(context) + + +class ConferencePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConferenceInstance: + """ + Build an instance of ConferenceInstance + + :param payload: Payload response from the API + """ + return ConferenceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Insights.V1.ConferencePage>" + + +class ConferenceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ConferenceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Conferences" + + def stream( + self, + conference_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + mixer_region: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, + subaccount: Union[str, object] = values.unset, + detected_issues: Union[str, object] = values.unset, + end_reason: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConferenceInstance]: + """ + Streams ConferenceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str conference_sid: The SID of the conference. + :param str friendly_name: Custom label for the conference resource, up to 64 characters. + :param str status: Conference status. + :param str created_after: Conferences created after the provided timestamp specified in ISO 8601 format + :param str created_before: Conferences created before the provided timestamp specified in ISO 8601 format. + :param str mixer_region: Twilio region where the conference media was mixed. + :param str tags: Tags applied by Twilio for common potential configuration, quality, or performance issues. + :param str subaccount: Account SID for the subaccount whose resources you wish to retrieve. + :param str detected_issues: Potential configuration, behavior, or performance issues detected during the conference. + :param str end_reason: Conference end reason; e.g. last participant left, modified by API, etc. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + conference_sid=conference_sid, + friendly_name=friendly_name, + status=status, + created_after=created_after, + created_before=created_before, + mixer_region=mixer_region, + tags=tags, + subaccount=subaccount, + detected_issues=detected_issues, + end_reason=end_reason, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + conference_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + mixer_region: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, + subaccount: Union[str, object] = values.unset, + detected_issues: Union[str, object] = values.unset, + end_reason: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConferenceInstance]: + """ + Asynchronously streams ConferenceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str conference_sid: The SID of the conference. + :param str friendly_name: Custom label for the conference resource, up to 64 characters. + :param str status: Conference status. + :param str created_after: Conferences created after the provided timestamp specified in ISO 8601 format + :param str created_before: Conferences created before the provided timestamp specified in ISO 8601 format. + :param str mixer_region: Twilio region where the conference media was mixed. + :param str tags: Tags applied by Twilio for common potential configuration, quality, or performance issues. + :param str subaccount: Account SID for the subaccount whose resources you wish to retrieve. + :param str detected_issues: Potential configuration, behavior, or performance issues detected during the conference. + :param str end_reason: Conference end reason; e.g. last participant left, modified by API, etc. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + conference_sid=conference_sid, + friendly_name=friendly_name, + status=status, + created_after=created_after, + created_before=created_before, + mixer_region=mixer_region, + tags=tags, + subaccount=subaccount, + detected_issues=detected_issues, + end_reason=end_reason, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + conference_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + mixer_region: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, + subaccount: Union[str, object] = values.unset, + detected_issues: Union[str, object] = values.unset, + end_reason: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConferenceInstance]: + """ + Lists ConferenceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str conference_sid: The SID of the conference. + :param str friendly_name: Custom label for the conference resource, up to 64 characters. + :param str status: Conference status. + :param str created_after: Conferences created after the provided timestamp specified in ISO 8601 format + :param str created_before: Conferences created before the provided timestamp specified in ISO 8601 format. + :param str mixer_region: Twilio region where the conference media was mixed. + :param str tags: Tags applied by Twilio for common potential configuration, quality, or performance issues. + :param str subaccount: Account SID for the subaccount whose resources you wish to retrieve. + :param str detected_issues: Potential configuration, behavior, or performance issues detected during the conference. + :param str end_reason: Conference end reason; e.g. last participant left, modified by API, etc. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + conference_sid=conference_sid, + friendly_name=friendly_name, + status=status, + created_after=created_after, + created_before=created_before, + mixer_region=mixer_region, + tags=tags, + subaccount=subaccount, + detected_issues=detected_issues, + end_reason=end_reason, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + conference_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + mixer_region: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, + subaccount: Union[str, object] = values.unset, + detected_issues: Union[str, object] = values.unset, + end_reason: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConferenceInstance]: + """ + Asynchronously lists ConferenceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str conference_sid: The SID of the conference. + :param str friendly_name: Custom label for the conference resource, up to 64 characters. + :param str status: Conference status. + :param str created_after: Conferences created after the provided timestamp specified in ISO 8601 format + :param str created_before: Conferences created before the provided timestamp specified in ISO 8601 format. + :param str mixer_region: Twilio region where the conference media was mixed. + :param str tags: Tags applied by Twilio for common potential configuration, quality, or performance issues. + :param str subaccount: Account SID for the subaccount whose resources you wish to retrieve. + :param str detected_issues: Potential configuration, behavior, or performance issues detected during the conference. + :param str end_reason: Conference end reason; e.g. last participant left, modified by API, etc. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + conference_sid=conference_sid, + friendly_name=friendly_name, + status=status, + created_after=created_after, + created_before=created_before, + mixer_region=mixer_region, + tags=tags, + subaccount=subaccount, + detected_issues=detected_issues, + end_reason=end_reason, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + conference_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + mixer_region: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, + subaccount: Union[str, object] = values.unset, + detected_issues: Union[str, object] = values.unset, + end_reason: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConferencePage: + """ + Retrieve a single page of ConferenceInstance records from the API. + Request is executed immediately + + :param conference_sid: The SID of the conference. + :param friendly_name: Custom label for the conference resource, up to 64 characters. + :param status: Conference status. + :param created_after: Conferences created after the provided timestamp specified in ISO 8601 format + :param created_before: Conferences created before the provided timestamp specified in ISO 8601 format. + :param mixer_region: Twilio region where the conference media was mixed. + :param tags: Tags applied by Twilio for common potential configuration, quality, or performance issues. + :param subaccount: Account SID for the subaccount whose resources you wish to retrieve. + :param detected_issues: Potential configuration, behavior, or performance issues detected during the conference. + :param end_reason: Conference end reason; e.g. last participant left, modified by API, etc. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConferenceInstance + """ + data = values.of( + { + "ConferenceSid": conference_sid, + "FriendlyName": friendly_name, + "Status": status, + "CreatedAfter": created_after, + "CreatedBefore": created_before, + "MixerRegion": mixer_region, + "Tags": tags, + "Subaccount": subaccount, + "DetectedIssues": detected_issues, + "EndReason": end_reason, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConferencePage(self._version, response) + + async def page_async( + self, + conference_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + created_after: Union[str, object] = values.unset, + created_before: Union[str, object] = values.unset, + mixer_region: Union[str, object] = values.unset, + tags: Union[str, object] = values.unset, + subaccount: Union[str, object] = values.unset, + detected_issues: Union[str, object] = values.unset, + end_reason: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConferencePage: + """ + Asynchronously retrieve a single page of ConferenceInstance records from the API. + Request is executed immediately + + :param conference_sid: The SID of the conference. + :param friendly_name: Custom label for the conference resource, up to 64 characters. + :param status: Conference status. + :param created_after: Conferences created after the provided timestamp specified in ISO 8601 format + :param created_before: Conferences created before the provided timestamp specified in ISO 8601 format. + :param mixer_region: Twilio region where the conference media was mixed. + :param tags: Tags applied by Twilio for common potential configuration, quality, or performance issues. + :param subaccount: Account SID for the subaccount whose resources you wish to retrieve. + :param detected_issues: Potential configuration, behavior, or performance issues detected during the conference. + :param end_reason: Conference end reason; e.g. last participant left, modified by API, etc. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConferenceInstance + """ + data = values.of( + { + "ConferenceSid": conference_sid, + "FriendlyName": friendly_name, + "Status": status, + "CreatedAfter": created_after, + "CreatedBefore": created_before, + "MixerRegion": mixer_region, + "Tags": tags, + "Subaccount": subaccount, + "DetectedIssues": detected_issues, + "EndReason": end_reason, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConferencePage(self._version, response) + + def get_page(self, target_url: str) -> ConferencePage: + """ + Retrieve a specific page of ConferenceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConferenceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConferencePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ConferencePage: + """ + Asynchronously retrieve a specific page of ConferenceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConferenceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConferencePage(self._version, response) + + def get(self, conference_sid: str) -> ConferenceContext: + """ + Constructs a ConferenceContext + + :param conference_sid: The unique SID identifier of the Conference. + """ + return ConferenceContext(self._version, conference_sid=conference_sid) + + def __call__(self, conference_sid: str) -> ConferenceContext: + """ + Constructs a ConferenceContext + + :param conference_sid: The unique SID identifier of the Conference. + """ + return ConferenceContext(self._version, conference_sid=conference_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Insights.V1.ConferenceList>" diff --git a/twilio/rest/insights/v1/conference/conference_participant.py b/twilio/rest/insights/v1/conference/conference_participant.py new file mode 100644 index 0000000000..171f4f1f87 --- /dev/null +++ b/twilio/rest/insights/v1/conference/conference_participant.py @@ -0,0 +1,655 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ConferenceParticipantInstance(InstanceResource): + + class CallDirection(object): + INBOUND = "inbound" + OUTBOUND = "outbound" + + class CallStatus(object): + ANSWERED = "answered" + COMPLETED = "completed" + BUSY = "busy" + FAIL = "fail" + NOANSWER = "noanswer" + RINGING = "ringing" + CANCELED = "canceled" + + class CallType(object): + CARRIER = "carrier" + CLIENT = "client" + SIP = "sip" + + class JitterBufferSize(object): + LARGE = "large" + SMALL = "small" + MEDIUM = "medium" + OFF = "off" + + class ProcessingState(object): + COMPLETE = "complete" + IN_PROGRESS = "in_progress" + TIMEOUT = "timeout" + + class Region(object): + US1 = "us1" + US2 = "us2" + AU1 = "au1" + BR1 = "br1" + IE1 = "ie1" + JP1 = "jp1" + SG1 = "sg1" + DE1 = "de1" + IN1 = "in1" + + """ + :ivar participant_sid: SID for this participant. + :ivar label: The user-specified label of this participant. + :ivar conference_sid: The unique SID identifier of the Conference. + :ivar call_sid: Unique SID identifier of the call that generated the Participant resource. + :ivar account_sid: The unique SID identifier of the Account. + :ivar call_direction: + :ivar _from: Caller ID of the calling party. + :ivar to: Called party. + :ivar call_status: + :ivar country_code: ISO alpha-2 country code of the participant based on caller ID or called number. + :ivar is_moderator: Boolean. Indicates whether participant had startConferenceOnEnter=true or endConferenceOnExit=true. + :ivar join_time: ISO 8601 timestamp of participant join event. + :ivar leave_time: ISO 8601 timestamp of participant leave event. + :ivar duration_seconds: Participant durations in seconds. + :ivar outbound_queue_length: Add Participant API only. Estimated time in queue at call creation. + :ivar outbound_time_in_queue: Add Participant API only. Actual time in queue in seconds. + :ivar jitter_buffer_size: + :ivar is_coach: Boolean. Indicated whether participant was a coach. + :ivar coached_participants: Call SIDs coached by this participant. + :ivar participant_region: + :ivar conference_region: + :ivar call_type: + :ivar processing_state: + :ivar properties: Participant properties and metadata. + :ivar events: Object containing information of actions taken by participants. Contains a dictionary of URL links to nested resources of this Conference Participant. + :ivar metrics: Object. Contains participant call quality metrics. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + conference_sid: str, + participant_sid: Optional[str] = None, + ): + super().__init__(version) + + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.label: Optional[str] = payload.get("label") + self.conference_sid: Optional[str] = payload.get("conference_sid") + self.call_sid: Optional[str] = payload.get("call_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.call_direction: Optional["ConferenceParticipantInstance.CallDirection"] = ( + payload.get("call_direction") + ) + self._from: Optional[str] = payload.get("from") + self.to: Optional[str] = payload.get("to") + self.call_status: Optional["ConferenceParticipantInstance.CallStatus"] = ( + payload.get("call_status") + ) + self.country_code: Optional[str] = payload.get("country_code") + self.is_moderator: Optional[bool] = payload.get("is_moderator") + self.join_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("join_time") + ) + self.leave_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("leave_time") + ) + self.duration_seconds: Optional[int] = deserialize.integer( + payload.get("duration_seconds") + ) + self.outbound_queue_length: Optional[int] = deserialize.integer( + payload.get("outbound_queue_length") + ) + self.outbound_time_in_queue: Optional[int] = deserialize.integer( + payload.get("outbound_time_in_queue") + ) + self.jitter_buffer_size: Optional[ + "ConferenceParticipantInstance.JitterBufferSize" + ] = payload.get("jitter_buffer_size") + self.is_coach: Optional[bool] = payload.get("is_coach") + self.coached_participants: Optional[List[str]] = payload.get( + "coached_participants" + ) + self.participant_region: Optional["ConferenceParticipantInstance.Region"] = ( + payload.get("participant_region") + ) + self.conference_region: Optional["ConferenceParticipantInstance.Region"] = ( + payload.get("conference_region") + ) + self.call_type: Optional["ConferenceParticipantInstance.CallType"] = ( + payload.get("call_type") + ) + self.processing_state: Optional[ + "ConferenceParticipantInstance.ProcessingState" + ] = payload.get("processing_state") + self.properties: Optional[Dict[str, object]] = payload.get("properties") + self.events: Optional[Dict[str, object]] = payload.get("events") + self.metrics: Optional[Dict[str, object]] = payload.get("metrics") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "conference_sid": conference_sid, + "participant_sid": participant_sid or self.participant_sid, + } + self._context: Optional[ConferenceParticipantContext] = None + + @property + def _proxy(self) -> "ConferenceParticipantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConferenceParticipantContext for this ConferenceParticipantInstance + """ + if self._context is None: + self._context = ConferenceParticipantContext( + self._version, + conference_sid=self._solution["conference_sid"], + participant_sid=self._solution["participant_sid"], + ) + return self._context + + def fetch( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> "ConferenceParticipantInstance": + """ + Fetch the ConferenceParticipantInstance + + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param metrics: Object. Contains participant call quality metrics. + + :returns: The fetched ConferenceParticipantInstance + """ + return self._proxy.fetch( + events=events, + metrics=metrics, + ) + + async def fetch_async( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> "ConferenceParticipantInstance": + """ + Asynchronous coroutine to fetch the ConferenceParticipantInstance + + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param metrics: Object. Contains participant call quality metrics. + + :returns: The fetched ConferenceParticipantInstance + """ + return await self._proxy.fetch_async( + events=events, + metrics=metrics, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Insights.V1.ConferenceParticipantInstance {}>".format(context) + + +class ConferenceParticipantContext(InstanceContext): + + def __init__(self, version: Version, conference_sid: str, participant_sid: str): + """ + Initialize the ConferenceParticipantContext + + :param version: Version that contains the resource + :param conference_sid: The unique SID identifier of the Conference. + :param participant_sid: The unique SID identifier of the Participant. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conference_sid": conference_sid, + "participant_sid": participant_sid, + } + self._uri = ( + "/Conferences/{conference_sid}/Participants/{participant_sid}".format( + **self._solution + ) + ) + + def fetch( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> ConferenceParticipantInstance: + """ + Fetch the ConferenceParticipantInstance + + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param metrics: Object. Contains participant call quality metrics. + + :returns: The fetched ConferenceParticipantInstance + """ + + data = values.of( + { + "Events": events, + "Metrics": metrics, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return ConferenceParticipantInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], + participant_sid=self._solution["participant_sid"], + ) + + async def fetch_async( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> ConferenceParticipantInstance: + """ + Asynchronous coroutine to fetch the ConferenceParticipantInstance + + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param metrics: Object. Contains participant call quality metrics. + + :returns: The fetched ConferenceParticipantInstance + """ + + data = values.of( + { + "Events": events, + "Metrics": metrics, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return ConferenceParticipantInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], + participant_sid=self._solution["participant_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Insights.V1.ConferenceParticipantContext {}>".format(context) + + +class ConferenceParticipantPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConferenceParticipantInstance: + """ + Build an instance of ConferenceParticipantInstance + + :param payload: Payload response from the API + """ + return ConferenceParticipantInstance( + self._version, payload, conference_sid=self._solution["conference_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Insights.V1.ConferenceParticipantPage>" + + +class ConferenceParticipantList(ListResource): + + def __init__(self, version: Version, conference_sid: str): + """ + Initialize the ConferenceParticipantList + + :param version: Version that contains the resource + :param conference_sid: The unique SID identifier of the Conference. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conference_sid": conference_sid, + } + self._uri = "/Conferences/{conference_sid}/Participants".format( + **self._solution + ) + + def stream( + self, + participant_sid: Union[str, object] = values.unset, + label: Union[str, object] = values.unset, + events: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConferenceParticipantInstance]: + """ + Streams ConferenceParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str participant_sid: The unique SID identifier of the Participant. + :param str label: User-specified label for a participant. + :param str events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + participant_sid=participant_sid, + label=label, + events=events, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + participant_sid: Union[str, object] = values.unset, + label: Union[str, object] = values.unset, + events: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConferenceParticipantInstance]: + """ + Asynchronously streams ConferenceParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str participant_sid: The unique SID identifier of the Participant. + :param str label: User-specified label for a participant. + :param str events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + participant_sid=participant_sid, + label=label, + events=events, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + participant_sid: Union[str, object] = values.unset, + label: Union[str, object] = values.unset, + events: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConferenceParticipantInstance]: + """ + Lists ConferenceParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str participant_sid: The unique SID identifier of the Participant. + :param str label: User-specified label for a participant. + :param str events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + participant_sid=participant_sid, + label=label, + events=events, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + participant_sid: Union[str, object] = values.unset, + label: Union[str, object] = values.unset, + events: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConferenceParticipantInstance]: + """ + Asynchronously lists ConferenceParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str participant_sid: The unique SID identifier of the Participant. + :param str label: User-specified label for a participant. + :param str events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + participant_sid=participant_sid, + label=label, + events=events, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + participant_sid: Union[str, object] = values.unset, + label: Union[str, object] = values.unset, + events: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConferenceParticipantPage: + """ + Retrieve a single page of ConferenceParticipantInstance records from the API. + Request is executed immediately + + :param participant_sid: The unique SID identifier of the Participant. + :param label: User-specified label for a participant. + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConferenceParticipantInstance + """ + data = values.of( + { + "ParticipantSid": participant_sid, + "Label": label, + "Events": events, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConferenceParticipantPage(self._version, response, self._solution) + + async def page_async( + self, + participant_sid: Union[str, object] = values.unset, + label: Union[str, object] = values.unset, + events: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConferenceParticipantPage: + """ + Asynchronously retrieve a single page of ConferenceParticipantInstance records from the API. + Request is executed immediately + + :param participant_sid: The unique SID identifier of the Participant. + :param label: User-specified label for a participant. + :param events: Conference events generated by application or participant activity; e.g. `hold`, `mute`, etc. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConferenceParticipantInstance + """ + data = values.of( + { + "ParticipantSid": participant_sid, + "Label": label, + "Events": events, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConferenceParticipantPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ConferenceParticipantPage: + """ + Retrieve a specific page of ConferenceParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConferenceParticipantInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConferenceParticipantPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ConferenceParticipantPage: + """ + Asynchronously retrieve a specific page of ConferenceParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConferenceParticipantInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConferenceParticipantPage(self._version, response, self._solution) + + def get(self, participant_sid: str) -> ConferenceParticipantContext: + """ + Constructs a ConferenceParticipantContext + + :param participant_sid: The unique SID identifier of the Participant. + """ + return ConferenceParticipantContext( + self._version, + conference_sid=self._solution["conference_sid"], + participant_sid=participant_sid, + ) + + def __call__(self, participant_sid: str) -> ConferenceParticipantContext: + """ + Constructs a ConferenceParticipantContext + + :param participant_sid: The unique SID identifier of the Participant. + """ + return ConferenceParticipantContext( + self._version, + conference_sid=self._solution["conference_sid"], + participant_sid=participant_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Insights.V1.ConferenceParticipantList>" diff --git a/twilio/rest/insights/v1/room/__init__.py b/twilio/rest/insights/v1/room/__init__.py new file mode 100644 index 0000000000..6fe0c476b5 --- /dev/null +++ b/twilio/rest/insights/v1/room/__init__.py @@ -0,0 +1,664 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.insights.v1.room.participant import ParticipantList + + +class RoomInstance(InstanceResource): + + class Codec(object): + VP8 = "VP8" + H264 = "H264" + VP9 = "VP9" + OPUS = "opus" + + class CreatedMethod(object): + SDK = "sdk" + AD_HOC = "ad_hoc" + API = "api" + + class EdgeLocation(object): + ASHBURN = "ashburn" + DUBLIN = "dublin" + FRANKFURT = "frankfurt" + SINGAPORE = "singapore" + SYDNEY = "sydney" + SAO_PAULO = "sao_paulo" + ROAMING = "roaming" + UMATILLA = "umatilla" + TOKYO = "tokyo" + + class EndReason(object): + ROOM_ENDED_VIA_API = "room_ended_via_api" + TIMEOUT = "timeout" + + class ProcessingState(object): + COMPLETE = "complete" + IN_PROGRESS = "in_progress" + TIMEOUT = "timeout" + NOT_STARTED = "not_started" + + class RoomStatus(object): + IN_PROGRESS = "in_progress" + COMPLETED = "completed" + + class RoomType(object): + GO = "go" + PEER_TO_PEER = "peer_to_peer" + GROUP = "group" + GROUP_SMALL = "group_small" + + class TwilioRealm(object): + US1 = "us1" + US2 = "us2" + AU1 = "au1" + BR1 = "br1" + IE1 = "ie1" + JP1 = "jp1" + SG1 = "sg1" + IN1 = "in1" + DE1 = "de1" + GLL = "gll" + STAGE_US1 = "stage_us1" + STAGE_US2 = "stage_us2" + DEV_US1 = "dev_us1" + DEV_US2 = "dev_us2" + STAGE_DE1 = "stage_de1" + STAGE_IN1 = "stage_in1" + STAGE_IE1 = "stage_ie1" + STAGE_BR1 = "stage_br1" + STAGE_AU1 = "stage_au1" + STAGE_SG1 = "stage_sg1" + STAGE_JP1 = "stage_jp1" + OUTSIDE = "outside" + + """ + :ivar account_sid: Account SID associated with this room. + :ivar room_sid: Unique identifier for the room. + :ivar room_name: Room friendly name. + :ivar create_time: Creation time of the room. + :ivar end_time: End time for the room. + :ivar room_type: + :ivar room_status: + :ivar status_callback: Webhook provided for status callbacks. + :ivar status_callback_method: HTTP method provided for status callback URL. + :ivar created_method: + :ivar end_reason: + :ivar max_participants: Max number of total participants allowed by the application settings. + :ivar unique_participants: Number of participants. May include duplicate identities for participants who left and rejoined. + :ivar unique_participant_identities: Unique number of participant identities. + :ivar concurrent_participants: Actual number of concurrent participants. + :ivar max_concurrent_participants: Maximum number of participants allowed in the room at the same time allowed by the application settings. + :ivar codecs: Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + :ivar media_region: + :ivar duration_sec: Total room duration from create time to end time. + :ivar total_participant_duration_sec: Combined amount of participant time in the room. + :ivar total_recording_duration_sec: Combined amount of recorded seconds for participants in the room. + :ivar processing_state: + :ivar recording_enabled: Boolean indicating if recording is enabled for the room. + :ivar edge_location: + :ivar url: URL for the room resource. + :ivar links: Room subresources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], room_sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.room_sid: Optional[str] = payload.get("room_sid") + self.room_name: Optional[str] = payload.get("room_name") + self.create_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("create_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.room_type: Optional["RoomInstance.RoomType"] = payload.get("room_type") + self.room_status: Optional["RoomInstance.RoomStatus"] = payload.get( + "room_status" + ) + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.created_method: Optional["RoomInstance.CreatedMethod"] = payload.get( + "created_method" + ) + self.end_reason: Optional["RoomInstance.EndReason"] = payload.get("end_reason") + self.max_participants: Optional[int] = deserialize.integer( + payload.get("max_participants") + ) + self.unique_participants: Optional[int] = deserialize.integer( + payload.get("unique_participants") + ) + self.unique_participant_identities: Optional[int] = deserialize.integer( + payload.get("unique_participant_identities") + ) + self.concurrent_participants: Optional[int] = deserialize.integer( + payload.get("concurrent_participants") + ) + self.max_concurrent_participants: Optional[int] = deserialize.integer( + payload.get("max_concurrent_participants") + ) + self.codecs: Optional[List["RoomInstance.Codec"]] = payload.get("codecs") + self.media_region: Optional["RoomInstance.TwilioRealm"] = payload.get( + "media_region" + ) + self.duration_sec: Optional[int] = payload.get("duration_sec") + self.total_participant_duration_sec: Optional[int] = payload.get( + "total_participant_duration_sec" + ) + self.total_recording_duration_sec: Optional[int] = payload.get( + "total_recording_duration_sec" + ) + self.processing_state: Optional["RoomInstance.ProcessingState"] = payload.get( + "processing_state" + ) + self.recording_enabled: Optional[bool] = payload.get("recording_enabled") + self.edge_location: Optional["RoomInstance.EdgeLocation"] = payload.get( + "edge_location" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "room_sid": room_sid or self.room_sid, + } + self._context: Optional[RoomContext] = None + + @property + def _proxy(self) -> "RoomContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoomContext for this RoomInstance + """ + if self._context is None: + self._context = RoomContext( + self._version, + room_sid=self._solution["room_sid"], + ) + return self._context + + def fetch(self) -> "RoomInstance": + """ + Fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RoomInstance": + """ + Asynchronous coroutine to fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + return await self._proxy.fetch_async() + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + return self._proxy.participants + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Insights.V1.RoomInstance {}>".format(context) + + +class RoomContext(InstanceContext): + + def __init__(self, version: Version, room_sid: str): + """ + Initialize the RoomContext + + :param version: Version that contains the resource + :param room_sid: The SID of the Room resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + } + self._uri = "/Video/Rooms/{room_sid}".format(**self._solution) + + self._participants: Optional[ParticipantList] = None + + def fetch(self) -> RoomInstance: + """ + Fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RoomInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ) + + async def fetch_async(self) -> RoomInstance: + """ + Asynchronous coroutine to fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RoomInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + ) + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + if self._participants is None: + self._participants = ParticipantList( + self._version, + self._solution["room_sid"], + ) + return self._participants + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Insights.V1.RoomContext {}>".format(context) + + +class RoomPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoomInstance: + """ + Build an instance of RoomInstance + + :param payload: Payload response from the API + """ + return RoomInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Insights.V1.RoomPage>" + + +class RoomList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RoomList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Video/Rooms" + + def stream( + self, + room_type: Union[List["RoomInstance.RoomType"], object] = values.unset, + codec: Union[List["RoomInstance.Codec"], object] = values.unset, + room_name: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoomInstance]: + """ + Streams RoomInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["RoomInstance.RoomType"] room_type: Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. + :param List["RoomInstance.Codec"] codec: Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + :param str room_name: Room friendly name. + :param datetime created_after: Only read rooms that started on or after this ISO 8601 timestamp. + :param datetime created_before: Only read rooms that started before this ISO 8601 timestamp. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + room_type=room_type, + codec=codec, + room_name=room_name, + created_after=created_after, + created_before=created_before, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + room_type: Union[List["RoomInstance.RoomType"], object] = values.unset, + codec: Union[List["RoomInstance.Codec"], object] = values.unset, + room_name: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoomInstance]: + """ + Asynchronously streams RoomInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["RoomInstance.RoomType"] room_type: Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. + :param List["RoomInstance.Codec"] codec: Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + :param str room_name: Room friendly name. + :param datetime created_after: Only read rooms that started on or after this ISO 8601 timestamp. + :param datetime created_before: Only read rooms that started before this ISO 8601 timestamp. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + room_type=room_type, + codec=codec, + room_name=room_name, + created_after=created_after, + created_before=created_before, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + room_type: Union[List["RoomInstance.RoomType"], object] = values.unset, + codec: Union[List["RoomInstance.Codec"], object] = values.unset, + room_name: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoomInstance]: + """ + Lists RoomInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["RoomInstance.RoomType"] room_type: Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. + :param List["RoomInstance.Codec"] codec: Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + :param str room_name: Room friendly name. + :param datetime created_after: Only read rooms that started on or after this ISO 8601 timestamp. + :param datetime created_before: Only read rooms that started before this ISO 8601 timestamp. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + room_type=room_type, + codec=codec, + room_name=room_name, + created_after=created_after, + created_before=created_before, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + room_type: Union[List["RoomInstance.RoomType"], object] = values.unset, + codec: Union[List["RoomInstance.Codec"], object] = values.unset, + room_name: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoomInstance]: + """ + Asynchronously lists RoomInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["RoomInstance.RoomType"] room_type: Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. + :param List["RoomInstance.Codec"] codec: Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + :param str room_name: Room friendly name. + :param datetime created_after: Only read rooms that started on or after this ISO 8601 timestamp. + :param datetime created_before: Only read rooms that started before this ISO 8601 timestamp. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + room_type=room_type, + codec=codec, + room_name=room_name, + created_after=created_after, + created_before=created_before, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + room_type: Union[List["RoomInstance.RoomType"], object] = values.unset, + codec: Union[List["RoomInstance.Codec"], object] = values.unset, + room_name: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RoomPage: + """ + Retrieve a single page of RoomInstance records from the API. + Request is executed immediately + + :param room_type: Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. + :param codec: Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + :param room_name: Room friendly name. + :param created_after: Only read rooms that started on or after this ISO 8601 timestamp. + :param created_before: Only read rooms that started before this ISO 8601 timestamp. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoomInstance + """ + data = values.of( + { + "RoomType": serialize.map(room_type, lambda e: e), + "Codec": serialize.map(codec, lambda e: e), + "RoomName": room_name, + "CreatedAfter": serialize.iso8601_datetime(created_after), + "CreatedBefore": serialize.iso8601_datetime(created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RoomPage(self._version, response) + + async def page_async( + self, + room_type: Union[List["RoomInstance.RoomType"], object] = values.unset, + codec: Union[List["RoomInstance.Codec"], object] = values.unset, + room_name: Union[str, object] = values.unset, + created_after: Union[datetime, object] = values.unset, + created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RoomPage: + """ + Asynchronously retrieve a single page of RoomInstance records from the API. + Request is executed immediately + + :param room_type: Type of room. Can be `go`, `peer_to_peer`, `group`, or `group_small`. + :param codec: Codecs used by participants in the room. Can be `VP8`, `H264`, or `VP9`. + :param room_name: Room friendly name. + :param created_after: Only read rooms that started on or after this ISO 8601 timestamp. + :param created_before: Only read rooms that started before this ISO 8601 timestamp. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoomInstance + """ + data = values.of( + { + "RoomType": serialize.map(room_type, lambda e: e), + "Codec": serialize.map(codec, lambda e: e), + "RoomName": room_name, + "CreatedAfter": serialize.iso8601_datetime(created_after), + "CreatedBefore": serialize.iso8601_datetime(created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RoomPage(self._version, response) + + def get_page(self, target_url: str) -> RoomPage: + """ + Retrieve a specific page of RoomInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoomInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RoomPage(self._version, response) + + async def get_page_async(self, target_url: str) -> RoomPage: + """ + Asynchronously retrieve a specific page of RoomInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoomInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RoomPage(self._version, response) + + def get(self, room_sid: str) -> RoomContext: + """ + Constructs a RoomContext + + :param room_sid: The SID of the Room resource. + """ + return RoomContext(self._version, room_sid=room_sid) + + def __call__(self, room_sid: str) -> RoomContext: + """ + Constructs a RoomContext + + :param room_sid: The SID of the Room resource. + """ + return RoomContext(self._version, room_sid=room_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Insights.V1.RoomList>" diff --git a/twilio/rest/insights/v1/room/participant.py b/twilio/rest/insights/v1/room/participant.py new file mode 100644 index 0000000000..d0d3e592e0 --- /dev/null +++ b/twilio/rest/insights/v1/room/participant.py @@ -0,0 +1,516 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ParticipantInstance(InstanceResource): + + class Codec(object): + VP8 = "VP8" + H264 = "H264" + VP9 = "VP9" + OPUS = "opus" + + class EdgeLocation(object): + ASHBURN = "ashburn" + DUBLIN = "dublin" + FRANKFURT = "frankfurt" + SINGAPORE = "singapore" + SYDNEY = "sydney" + SAO_PAULO = "sao_paulo" + ROAMING = "roaming" + UMATILLA = "umatilla" + TOKYO = "tokyo" + + class RoomStatus(object): + IN_PROGRESS = "in_progress" + CONNECTED = "connected" + COMPLETED = "completed" + DISCONNECTED = "disconnected" + + class TwilioRealm(object): + US1 = "us1" + US2 = "us2" + AU1 = "au1" + BR1 = "br1" + IE1 = "ie1" + JP1 = "jp1" + SG1 = "sg1" + IN1 = "in1" + DE1 = "de1" + GLL = "gll" + STAGE_US1 = "stage_us1" + DEV_US1 = "dev_us1" + STAGE_AU1 = "stage_au1" + STAGE_SG1 = "stage_sg1" + STAGE_BR1 = "stage_br1" + STAGE_IN1 = "stage_in1" + STAGE_JP1 = "stage_jp1" + STAGE_DE1 = "stage_de1" + STAGE_IE1 = "stage_ie1" + STAGE_US2 = "stage_us2" + DEV_US2 = "dev_us2" + OUTSIDE = "outside" + + """ + :ivar participant_sid: Unique identifier for the participant. + :ivar participant_identity: The application-defined string that uniquely identifies the participant within a Room. + :ivar join_time: When the participant joined the room. + :ivar leave_time: When the participant left the room. + :ivar duration_sec: Amount of time in seconds the participant was in the room. + :ivar account_sid: Account SID associated with the room. + :ivar room_sid: Unique identifier for the room. + :ivar status: + :ivar codecs: Codecs detected from the participant. Can be `VP8`, `H264`, or `VP9`. + :ivar end_reason: Reason the participant left the room. See [the list of possible values here](https://www.twilio.com/docs/video/troubleshooting/video-log-analyzer-api#end_reason). + :ivar error_code: Errors encountered by the participant. + :ivar error_code_url: Twilio error code dictionary link. + :ivar media_region: + :ivar properties: Object containing information about the participant's data from the room. See [below](https://www.twilio.com/docs/video/troubleshooting/video-log-analyzer-api#properties) for more information. + :ivar edge_location: + :ivar publisher_info: Object containing information about the SDK name and version. See [below](https://www.twilio.com/docs/video/troubleshooting/video-log-analyzer-api#publisher_info) for more information. + :ivar url: URL of the participant resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + room_sid: str, + participant_sid: Optional[str] = None, + ): + super().__init__(version) + + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.participant_identity: Optional[str] = payload.get("participant_identity") + self.join_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("join_time") + ) + self.leave_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("leave_time") + ) + self.duration_sec: Optional[int] = payload.get("duration_sec") + self.account_sid: Optional[str] = payload.get("account_sid") + self.room_sid: Optional[str] = payload.get("room_sid") + self.status: Optional["ParticipantInstance.RoomStatus"] = payload.get("status") + self.codecs: Optional[List["ParticipantInstance.Codec"]] = payload.get("codecs") + self.end_reason: Optional[str] = payload.get("end_reason") + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.error_code_url: Optional[str] = payload.get("error_code_url") + self.media_region: Optional["ParticipantInstance.TwilioRealm"] = payload.get( + "media_region" + ) + self.properties: Optional[Dict[str, object]] = payload.get("properties") + self.edge_location: Optional["ParticipantInstance.EdgeLocation"] = payload.get( + "edge_location" + ) + self.publisher_info: Optional[Dict[str, object]] = payload.get("publisher_info") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "room_sid": room_sid, + "participant_sid": participant_sid or self.participant_sid, + } + self._context: Optional[ParticipantContext] = None + + @property + def _proxy(self) -> "ParticipantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ParticipantContext for this ParticipantInstance + """ + if self._context is None: + self._context = ParticipantContext( + self._version, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + return self._context + + def fetch(self) -> "ParticipantInstance": + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ParticipantInstance": + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Insights.V1.ParticipantInstance {}>".format(context) + + +class ParticipantContext(InstanceContext): + + def __init__(self, version: Version, room_sid: str, participant_sid: str): + """ + Initialize the ParticipantContext + + :param version: Version that contains the resource + :param room_sid: The SID of the Room resource. + :param participant_sid: The SID of the Participant resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "participant_sid": participant_sid, + } + self._uri = "/Video/Rooms/{room_sid}/Participants/{participant_sid}".format( + **self._solution + ) + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Insights.V1.ParticipantContext {}>".format(context) + + +class ParticipantPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: + """ + Build an instance of ParticipantInstance + + :param payload: Payload response from the API + """ + return ParticipantInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Insights.V1.ParticipantPage>" + + +class ParticipantList(ListResource): + + def __init__(self, version: Version, room_sid: str): + """ + Initialize the ParticipantList + + :param version: Version that contains the resource + :param room_sid: The SID of the Room resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + } + self._uri = "/Video/Rooms/{room_sid}/Participants".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantInstance]: + """ + Streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ParticipantInstance]: + """ + Asynchronously streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Asynchronously lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Asynchronously retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ParticipantPage: + """ + Retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ParticipantPage: + """ + Asynchronously retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + def get(self, participant_sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param participant_sid: The SID of the Participant resource. + """ + return ParticipantContext( + self._version, + room_sid=self._solution["room_sid"], + participant_sid=participant_sid, + ) + + def __call__(self, participant_sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param participant_sid: The SID of the Participant resource. + """ + return ParticipantContext( + self._version, + room_sid=self._solution["room_sid"], + participant_sid=participant_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Insights.V1.ParticipantList>" diff --git a/twilio/rest/insights/v1/setting.py b/twilio/rest/insights/v1/setting.py new file mode 100644 index 0000000000..3c6b746f07 --- /dev/null +++ b/twilio/rest/insights/v1/setting.py @@ -0,0 +1,318 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SettingInstance(InstanceResource): + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar advanced_features: A boolean flag indicating whether Advanced Features for Voice Insights are enabled. + :ivar voice_trace: A boolean flag indicating whether Voice Trace is enabled. + :ivar url: The URL of this resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.advanced_features: Optional[bool] = payload.get("advanced_features") + self.voice_trace: Optional[bool] = payload.get("voice_trace") + self.url: Optional[str] = payload.get("url") + + self._context: Optional[SettingContext] = None + + @property + def _proxy(self) -> "SettingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SettingContext for this SettingInstance + """ + if self._context is None: + self._context = SettingContext( + self._version, + ) + return self._context + + def fetch( + self, subaccount_sid: Union[str, object] = values.unset + ) -> "SettingInstance": + """ + Fetch the SettingInstance + + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: The fetched SettingInstance + """ + return self._proxy.fetch( + subaccount_sid=subaccount_sid, + ) + + async def fetch_async( + self, subaccount_sid: Union[str, object] = values.unset + ) -> "SettingInstance": + """ + Asynchronous coroutine to fetch the SettingInstance + + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: The fetched SettingInstance + """ + return await self._proxy.fetch_async( + subaccount_sid=subaccount_sid, + ) + + def update( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> "SettingInstance": + """ + Update the SettingInstance + + :param advanced_features: A boolean flag to enable Advanced Features for Voice Insights. + :param voice_trace: A boolean flag to enable Voice Trace. + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: The updated SettingInstance + """ + return self._proxy.update( + advanced_features=advanced_features, + voice_trace=voice_trace, + subaccount_sid=subaccount_sid, + ) + + async def update_async( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> "SettingInstance": + """ + Asynchronous coroutine to update the SettingInstance + + :param advanced_features: A boolean flag to enable Advanced Features for Voice Insights. + :param voice_trace: A boolean flag to enable Voice Trace. + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: The updated SettingInstance + """ + return await self._proxy.update_async( + advanced_features=advanced_features, + voice_trace=voice_trace, + subaccount_sid=subaccount_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Insights.V1.SettingInstance>" + + +class SettingContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the SettingContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/Voice/Settings" + + def fetch( + self, subaccount_sid: Union[str, object] = values.unset + ) -> SettingInstance: + """ + Fetch the SettingInstance + + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: The fetched SettingInstance + """ + + data = values.of( + { + "SubaccountSid": subaccount_sid, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return SettingInstance( + self._version, + payload, + ) + + async def fetch_async( + self, subaccount_sid: Union[str, object] = values.unset + ) -> SettingInstance: + """ + Asynchronous coroutine to fetch the SettingInstance + + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: The fetched SettingInstance + """ + + data = values.of( + { + "SubaccountSid": subaccount_sid, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return SettingInstance( + self._version, + payload, + ) + + def update( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> SettingInstance: + """ + Update the SettingInstance + + :param advanced_features: A boolean flag to enable Advanced Features for Voice Insights. + :param voice_trace: A boolean flag to enable Voice Trace. + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: The updated SettingInstance + """ + + data = values.of( + { + "AdvancedFeatures": serialize.boolean_to_string(advanced_features), + "VoiceTrace": serialize.boolean_to_string(voice_trace), + "SubaccountSid": subaccount_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SettingInstance(self._version, payload) + + async def update_async( + self, + advanced_features: Union[bool, object] = values.unset, + voice_trace: Union[bool, object] = values.unset, + subaccount_sid: Union[str, object] = values.unset, + ) -> SettingInstance: + """ + Asynchronous coroutine to update the SettingInstance + + :param advanced_features: A boolean flag to enable Advanced Features for Voice Insights. + :param voice_trace: A boolean flag to enable Voice Trace. + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :returns: The updated SettingInstance + """ + + data = values.of( + { + "AdvancedFeatures": serialize.boolean_to_string(advanced_features), + "VoiceTrace": serialize.boolean_to_string(voice_trace), + "SubaccountSid": subaccount_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SettingInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Insights.V1.SettingContext>" + + +class SettingList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SettingList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> SettingContext: + """ + Constructs a SettingContext + + """ + return SettingContext(self._version) + + def __call__(self) -> SettingContext: + """ + Constructs a SettingContext + + """ + return SettingContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Insights.V1.SettingList>" diff --git a/twilio/rest/intelligence/IntelligenceBase.py b/twilio/rest/intelligence/IntelligenceBase.py new file mode 100644 index 0000000000..0546bc15ae --- /dev/null +++ b/twilio/rest/intelligence/IntelligenceBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.intelligence.v2 import V2 + + +class IntelligenceBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Intelligence Domain + + :returns: Domain for Intelligence + """ + super().__init__(twilio, "https://intelligence.twilio.com") + self._v2: Optional[V2] = None + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Intelligence + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence>" diff --git a/twilio/rest/intelligence/__init__.py b/twilio/rest/intelligence/__init__.py new file mode 100644 index 0000000000..6d565b433c --- /dev/null +++ b/twilio/rest/intelligence/__init__.py @@ -0,0 +1,13 @@ +from twilio.rest.intelligence.IntelligenceBase import IntelligenceBase +from twilio.rest.intelligence.v2.service import ServiceList +from twilio.rest.intelligence.v2.transcript import TranscriptList + + +class Intelligence(IntelligenceBase): + @property + def transcripts(self) -> TranscriptList: + return self.v2.transcripts + + @property + def services(self) -> ServiceList: + return self.v2.services diff --git a/twilio/rest/intelligence/v2/__init__.py b/twilio/rest/intelligence/v2/__init__.py new file mode 100644 index 0000000000..4999146f93 --- /dev/null +++ b/twilio/rest/intelligence/v2/__init__.py @@ -0,0 +1,99 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.intelligence.v2.custom_operator import CustomOperatorList +from twilio.rest.intelligence.v2.operator import OperatorList +from twilio.rest.intelligence.v2.operator_attachment import OperatorAttachmentList +from twilio.rest.intelligence.v2.operator_attachments import OperatorAttachmentsList +from twilio.rest.intelligence.v2.operator_type import OperatorTypeList +from twilio.rest.intelligence.v2.prebuilt_operator import PrebuiltOperatorList +from twilio.rest.intelligence.v2.service import ServiceList +from twilio.rest.intelligence.v2.transcript import TranscriptList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Intelligence + + :param domain: The Twilio.intelligence domain + """ + super().__init__(domain, "v2") + self._custom_operators: Optional[CustomOperatorList] = None + self._operators: Optional[OperatorList] = None + self._operator_attachment: Optional[OperatorAttachmentList] = None + self._operator_attachments: Optional[OperatorAttachmentsList] = None + self._operator_type: Optional[OperatorTypeList] = None + self._prebuilt_operators: Optional[PrebuiltOperatorList] = None + self._services: Optional[ServiceList] = None + self._transcripts: Optional[TranscriptList] = None + + @property + def custom_operators(self) -> CustomOperatorList: + if self._custom_operators is None: + self._custom_operators = CustomOperatorList(self) + return self._custom_operators + + @property + def operators(self) -> OperatorList: + if self._operators is None: + self._operators = OperatorList(self) + return self._operators + + @property + def operator_attachment(self) -> OperatorAttachmentList: + if self._operator_attachment is None: + self._operator_attachment = OperatorAttachmentList(self) + return self._operator_attachment + + @property + def operator_attachments(self) -> OperatorAttachmentsList: + if self._operator_attachments is None: + self._operator_attachments = OperatorAttachmentsList(self) + return self._operator_attachments + + @property + def operator_type(self) -> OperatorTypeList: + if self._operator_type is None: + self._operator_type = OperatorTypeList(self) + return self._operator_type + + @property + def prebuilt_operators(self) -> PrebuiltOperatorList: + if self._prebuilt_operators is None: + self._prebuilt_operators = PrebuiltOperatorList(self) + return self._prebuilt_operators + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + @property + def transcripts(self) -> TranscriptList: + if self._transcripts is None: + self._transcripts = TranscriptList(self) + return self._transcripts + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence.V2>" diff --git a/twilio/rest/intelligence/v2/custom_operator.py b/twilio/rest/intelligence/v2/custom_operator.py new file mode 100644 index 0000000000..3dd73d47bb --- /dev/null +++ b/twilio/rest/intelligence/v2/custom_operator.py @@ -0,0 +1,716 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CustomOperatorInstance(InstanceResource): + + class Availability(object): + INTERNAL = "internal" + BETA = "beta" + PUBLIC = "public" + RETIRED = "retired" + + """ + :ivar account_sid: The unique SID identifier of the Account the Custom Operator belongs to. + :ivar sid: A 34 character string that uniquely identifies this Custom Operator. + :ivar friendly_name: A human-readable name of this resource, up to 64 characters. + :ivar description: A human-readable description of this resource, longer than the friendly name. + :ivar author: The creator of the Custom Operator. Custom Operators can only be created by a Twilio Account. + :ivar operator_type: Operator Type for this Operator. References an existing Operator Type resource. + :ivar version: Numeric Custom Operator version. Incremented with each update on the resource, used to ensure integrity when updating the Custom Operator. + :ivar availability: + :ivar config: Operator configuration, following the schema defined by the Operator Type. Only available on Operators created by the Account. + :ivar date_created: The date that this Custom Operator was created, given in ISO 8601 format. + :ivar date_updated: The date that this Custom Operator was updated, given in ISO 8601 format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.author: Optional[str] = payload.get("author") + self.operator_type: Optional[str] = payload.get("operator_type") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.availability: Optional["CustomOperatorInstance.Availability"] = ( + payload.get("availability") + ) + self.config: Optional[Dict[str, object]] = payload.get("config") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CustomOperatorContext] = None + + @property + def _proxy(self) -> "CustomOperatorContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CustomOperatorContext for this CustomOperatorInstance + """ + if self._context is None: + self._context = CustomOperatorContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CustomOperatorInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CustomOperatorInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CustomOperatorInstance": + """ + Fetch the CustomOperatorInstance + + + :returns: The fetched CustomOperatorInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CustomOperatorInstance": + """ + Asynchronous coroutine to fetch the CustomOperatorInstance + + + :returns: The fetched CustomOperatorInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> "CustomOperatorInstance": + """ + Update the CustomOperatorInstance + + :param friendly_name: A human-readable name of this resource, up to 64 characters. + :param config: Operator configuration, following the schema defined by the Operator Type. + :param if_match: The If-Match HTTP request header + + :returns: The updated CustomOperatorInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + config=config, + if_match=if_match, + ) + + async def update_async( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> "CustomOperatorInstance": + """ + Asynchronous coroutine to update the CustomOperatorInstance + + :param friendly_name: A human-readable name of this resource, up to 64 characters. + :param config: Operator configuration, following the schema defined by the Operator Type. + :param if_match: The If-Match HTTP request header + + :returns: The updated CustomOperatorInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + config=config, + if_match=if_match, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.CustomOperatorInstance {}>".format(context) + + +class CustomOperatorContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CustomOperatorContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this Custom Operator. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Operators/Custom/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CustomOperatorInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CustomOperatorInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CustomOperatorInstance: + """ + Fetch the CustomOperatorInstance + + + :returns: The fetched CustomOperatorInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CustomOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CustomOperatorInstance: + """ + Asynchronous coroutine to fetch the CustomOperatorInstance + + + :returns: The fetched CustomOperatorInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CustomOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> CustomOperatorInstance: + """ + Update the CustomOperatorInstance + + :param friendly_name: A human-readable name of this resource, up to 64 characters. + :param config: Operator configuration, following the schema defined by the Operator Type. + :param if_match: The If-Match HTTP request header + + :returns: The updated CustomOperatorInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Config": serialize.object(config), + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomOperatorInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> CustomOperatorInstance: + """ + Asynchronous coroutine to update the CustomOperatorInstance + + :param friendly_name: A human-readable name of this resource, up to 64 characters. + :param config: Operator configuration, following the schema defined by the Operator Type. + :param if_match: The If-Match HTTP request header + + :returns: The updated CustomOperatorInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Config": serialize.object(config), + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomOperatorInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.CustomOperatorContext {}>".format(context) + + +class CustomOperatorPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CustomOperatorInstance: + """ + Build an instance of CustomOperatorInstance + + :param payload: Payload response from the API + """ + return CustomOperatorInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence.V2.CustomOperatorPage>" + + +class CustomOperatorList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CustomOperatorList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Operators/Custom" + + def create( + self, friendly_name: str, operator_type: str, config: object + ) -> CustomOperatorInstance: + """ + Create the CustomOperatorInstance + + :param friendly_name: A human readable description of the new Operator, up to 64 characters. + :param operator_type: Operator Type for this Operator. References an existing Operator Type resource. + :param config: Operator configuration, following the schema defined by the Operator Type. + + :returns: The created CustomOperatorInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "OperatorType": operator_type, + "Config": serialize.object(config), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomOperatorInstance(self._version, payload) + + async def create_async( + self, friendly_name: str, operator_type: str, config: object + ) -> CustomOperatorInstance: + """ + Asynchronously create the CustomOperatorInstance + + :param friendly_name: A human readable description of the new Operator, up to 64 characters. + :param operator_type: Operator Type for this Operator. References an existing Operator Type resource. + :param config: Operator configuration, following the schema defined by the Operator Type. + + :returns: The created CustomOperatorInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "OperatorType": operator_type, + "Config": serialize.object(config), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomOperatorInstance(self._version, payload) + + def stream( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CustomOperatorInstance]: + """ + Streams CustomOperatorInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "CustomOperatorInstance.Availability" availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Custom Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CustomOperatorInstance]: + """ + Asynchronously streams CustomOperatorInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "CustomOperatorInstance.Availability" availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Custom Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomOperatorInstance]: + """ + Lists CustomOperatorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "CustomOperatorInstance.Availability" availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Custom Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomOperatorInstance]: + """ + Asynchronously lists CustomOperatorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "CustomOperatorInstance.Availability" availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Custom Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CustomOperatorPage: + """ + Retrieve a single page of CustomOperatorInstance records from the API. + Request is executed immediately + + :param availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param language_code: Returns Custom Operators that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CustomOperatorInstance + """ + data = values.of( + { + "Availability": availability, + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomOperatorPage(self._version, response) + + async def page_async( + self, + availability: Union[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CustomOperatorPage: + """ + Asynchronously retrieve a single page of CustomOperatorInstance records from the API. + Request is executed immediately + + :param availability: Returns Custom Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param language_code: Returns Custom Operators that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CustomOperatorInstance + """ + data = values.of( + { + "Availability": availability, + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomOperatorPage(self._version, response) + + def get_page(self, target_url: str) -> CustomOperatorPage: + """ + Retrieve a specific page of CustomOperatorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomOperatorInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CustomOperatorPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CustomOperatorPage: + """ + Asynchronously retrieve a specific page of CustomOperatorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomOperatorInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CustomOperatorPage(self._version, response) + + def get(self, sid: str) -> CustomOperatorContext: + """ + Constructs a CustomOperatorContext + + :param sid: A 34 character string that uniquely identifies this Custom Operator. + """ + return CustomOperatorContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CustomOperatorContext: + """ + Constructs a CustomOperatorContext + + :param sid: A 34 character string that uniquely identifies this Custom Operator. + """ + return CustomOperatorContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence.V2.CustomOperatorList>" diff --git a/twilio/rest/intelligence/v2/operator.py b/twilio/rest/intelligence/v2/operator.py new file mode 100644 index 0000000000..984c46d724 --- /dev/null +++ b/twilio/rest/intelligence/v2/operator.py @@ -0,0 +1,476 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class OperatorInstance(InstanceResource): + + class Availability(object): + INTERNAL = "internal" + BETA = "beta" + PUBLIC = "public" + RETIRED = "retired" + + """ + :ivar account_sid: The unique SID identifier of the Account the Operator belongs to. + :ivar sid: A 34 character string that uniquely identifies this Operator. + :ivar friendly_name: A human-readable name of this resource, up to 64 characters. + :ivar description: A human-readable description of this resource, longer than the friendly name. + :ivar author: The creator of the Operator. Either Twilio or the creating Account. + :ivar operator_type: Operator Type for this Operator. References an existing Operator Type resource. + :ivar version: Numeric Operator version. Incremented with each update on the resource, used to ensure integrity when updating the Operator. + :ivar availability: + :ivar config: Operator configuration, following the schema defined by the Operator Type. Only available on Custom Operators created by the Account. + :ivar date_created: The date that this Operator was created, given in ISO 8601 format. + :ivar date_updated: The date that this Operator was updated, given in ISO 8601 format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.author: Optional[str] = payload.get("author") + self.operator_type: Optional[str] = payload.get("operator_type") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.availability: Optional["OperatorInstance.Availability"] = payload.get( + "availability" + ) + self.config: Optional[Dict[str, object]] = payload.get("config") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[OperatorContext] = None + + @property + def _proxy(self) -> "OperatorContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperatorContext for this OperatorInstance + """ + if self._context is None: + self._context = OperatorContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "OperatorInstance": + """ + Fetch the OperatorInstance + + + :returns: The fetched OperatorInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OperatorInstance": + """ + Asynchronous coroutine to fetch the OperatorInstance + + + :returns: The fetched OperatorInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.OperatorInstance {}>".format(context) + + +class OperatorContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the OperatorContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this Operator. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Operators/{sid}".format(**self._solution) + + def fetch(self) -> OperatorInstance: + """ + Fetch the OperatorInstance + + + :returns: The fetched OperatorInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return OperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> OperatorInstance: + """ + Asynchronous coroutine to fetch the OperatorInstance + + + :returns: The fetched OperatorInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return OperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.OperatorContext {}>".format(context) + + +class OperatorPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> OperatorInstance: + """ + Build an instance of OperatorInstance + + :param payload: Payload response from the API + """ + return OperatorInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence.V2.OperatorPage>" + + +class OperatorList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OperatorList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Operators" + + def stream( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[OperatorInstance]: + """ + Streams OperatorInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "OperatorInstance.Availability" availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[OperatorInstance]: + """ + Asynchronously streams OperatorInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "OperatorInstance.Availability" availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OperatorInstance]: + """ + Lists OperatorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "OperatorInstance.Availability" availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OperatorInstance]: + """ + Asynchronously lists OperatorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "OperatorInstance.Availability" availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OperatorPage: + """ + Retrieve a single page of OperatorInstance records from the API. + Request is executed immediately + + :param availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param language_code: Returns Operators that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OperatorInstance + """ + data = values.of( + { + "Availability": availability, + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OperatorPage(self._version, response) + + async def page_async( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OperatorPage: + """ + Asynchronously retrieve a single page of OperatorInstance records from the API. + Request is executed immediately + + :param availability: Returns Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param language_code: Returns Operators that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OperatorInstance + """ + data = values.of( + { + "Availability": availability, + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OperatorPage(self._version, response) + + def get_page(self, target_url: str) -> OperatorPage: + """ + Retrieve a specific page of OperatorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OperatorInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return OperatorPage(self._version, response) + + async def get_page_async(self, target_url: str) -> OperatorPage: + """ + Asynchronously retrieve a specific page of OperatorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OperatorInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return OperatorPage(self._version, response) + + def get(self, sid: str) -> OperatorContext: + """ + Constructs a OperatorContext + + :param sid: A 34 character string that uniquely identifies this Operator. + """ + return OperatorContext(self._version, sid=sid) + + def __call__(self, sid: str) -> OperatorContext: + """ + Constructs a OperatorContext + + :param sid: A 34 character string that uniquely identifies this Operator. + """ + return OperatorContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence.V2.OperatorList>" diff --git a/twilio/rest/intelligence/v2/operator_attachment.py b/twilio/rest/intelligence/v2/operator_attachment.py new file mode 100644 index 0000000000..6080bc5ebf --- /dev/null +++ b/twilio/rest/intelligence/v2/operator_attachment.py @@ -0,0 +1,247 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class OperatorAttachmentInstance(InstanceResource): + """ + :ivar service_sid: The unique SID identifier of the Service. + :ivar operator_sid: The unique SID identifier of the Operator. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: Optional[str] = None, + operator_sid: Optional[str] = None, + ): + super().__init__(version) + + self.service_sid: Optional[str] = payload.get("service_sid") + self.operator_sid: Optional[str] = payload.get("operator_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid or self.service_sid, + "operator_sid": operator_sid or self.operator_sid, + } + self._context: Optional[OperatorAttachmentContext] = None + + @property + def _proxy(self) -> "OperatorAttachmentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperatorAttachmentContext for this OperatorAttachmentInstance + """ + if self._context is None: + self._context = OperatorAttachmentContext( + self._version, + service_sid=self._solution["service_sid"], + operator_sid=self._solution["operator_sid"], + ) + return self._context + + def create(self) -> "OperatorAttachmentInstance": + """ + Create the OperatorAttachmentInstance + + + :returns: The created OperatorAttachmentInstance + """ + return self._proxy.create() + + async def create_async(self) -> "OperatorAttachmentInstance": + """ + Asynchronous coroutine to create the OperatorAttachmentInstance + + + :returns: The created OperatorAttachmentInstance + """ + return await self._proxy.create_async() + + def delete(self) -> bool: + """ + Deletes the OperatorAttachmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OperatorAttachmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.OperatorAttachmentInstance {}>".format(context) + + +class OperatorAttachmentContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, operator_sid: str): + """ + Initialize the OperatorAttachmentContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param operator_sid: The unique SID identifier of the Operator. Allows both Custom and Pre-built Operators. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "operator_sid": operator_sid, + } + self._uri = "/Services/{service_sid}/Operators/{operator_sid}".format( + **self._solution + ) + + def create(self) -> OperatorAttachmentInstance: + """ + Create the OperatorAttachmentInstance + + + :returns: The created OperatorAttachmentInstance + """ + data = values.of({}) + + payload = self._version.create(method="POST", uri=self._uri, data=data) + + return OperatorAttachmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + operator_sid=self._solution["operator_sid"], + ) + + async def create_async(self) -> OperatorAttachmentInstance: + """ + Asynchronous coroutine to create the OperatorAttachmentInstance + + + :returns: The created OperatorAttachmentInstance + """ + data = values.of({}) + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data + ) + + return OperatorAttachmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + operator_sid=self._solution["operator_sid"], + ) + + def delete(self) -> bool: + """ + Deletes the OperatorAttachmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OperatorAttachmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.OperatorAttachmentContext {}>".format(context) + + +class OperatorAttachmentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OperatorAttachmentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, service_sid: str, operator_sid: str) -> OperatorAttachmentContext: + """ + Constructs a OperatorAttachmentContext + + :param service_sid: The unique SID identifier of the Service. + :param operator_sid: The unique SID identifier of the Operator. Allows both Custom and Pre-built Operators. + """ + return OperatorAttachmentContext( + self._version, service_sid=service_sid, operator_sid=operator_sid + ) + + def __call__( + self, service_sid: str, operator_sid: str + ) -> OperatorAttachmentContext: + """ + Constructs a OperatorAttachmentContext + + :param service_sid: The unique SID identifier of the Service. + :param operator_sid: The unique SID identifier of the Operator. Allows both Custom and Pre-built Operators. + """ + return OperatorAttachmentContext( + self._version, service_sid=service_sid, operator_sid=operator_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence.V2.OperatorAttachmentList>" diff --git a/twilio/rest/intelligence/v2/operator_attachments.py b/twilio/rest/intelligence/v2/operator_attachments.py new file mode 100644 index 0000000000..19a875f76b --- /dev/null +++ b/twilio/rest/intelligence/v2/operator_attachments.py @@ -0,0 +1,192 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class OperatorAttachmentsInstance(InstanceResource): + """ + :ivar service_sid: The unique SID identifier of the Service. + :ivar operator_sids: List of Operator SIDs attached to the service. Includes both Custom and Pre-built Operators. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: Optional[str] = None, + ): + super().__init__(version) + + self.service_sid: Optional[str] = payload.get("service_sid") + self.operator_sids: Optional[List[str]] = payload.get("operator_sids") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid or self.service_sid, + } + self._context: Optional[OperatorAttachmentsContext] = None + + @property + def _proxy(self) -> "OperatorAttachmentsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperatorAttachmentsContext for this OperatorAttachmentsInstance + """ + if self._context is None: + self._context = OperatorAttachmentsContext( + self._version, + service_sid=self._solution["service_sid"], + ) + return self._context + + def fetch(self) -> "OperatorAttachmentsInstance": + """ + Fetch the OperatorAttachmentsInstance + + + :returns: The fetched OperatorAttachmentsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OperatorAttachmentsInstance": + """ + Asynchronous coroutine to fetch the OperatorAttachmentsInstance + + + :returns: The fetched OperatorAttachmentsInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.OperatorAttachmentsInstance {}>".format(context) + + +class OperatorAttachmentsContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the OperatorAttachmentsContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Operators".format(**self._solution) + + def fetch(self) -> OperatorAttachmentsInstance: + """ + Fetch the OperatorAttachmentsInstance + + + :returns: The fetched OperatorAttachmentsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return OperatorAttachmentsInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + ) + + async def fetch_async(self) -> OperatorAttachmentsInstance: + """ + Asynchronous coroutine to fetch the OperatorAttachmentsInstance + + + :returns: The fetched OperatorAttachmentsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return OperatorAttachmentsInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.OperatorAttachmentsContext {}>".format(context) + + +class OperatorAttachmentsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OperatorAttachmentsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, service_sid: str) -> OperatorAttachmentsContext: + """ + Constructs a OperatorAttachmentsContext + + :param service_sid: The unique SID identifier of the Service. + """ + return OperatorAttachmentsContext(self._version, service_sid=service_sid) + + def __call__(self, service_sid: str) -> OperatorAttachmentsContext: + """ + Constructs a OperatorAttachmentsContext + + :param service_sid: The unique SID identifier of the Service. + """ + return OperatorAttachmentsContext(self._version, service_sid=service_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence.V2.OperatorAttachmentsList>" diff --git a/twilio/rest/intelligence/v2/operator_type.py b/twilio/rest/intelligence/v2/operator_type.py new file mode 100644 index 0000000000..b14e677ad2 --- /dev/null +++ b/twilio/rest/intelligence/v2/operator_type.py @@ -0,0 +1,458 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class OperatorTypeInstance(InstanceResource): + + class Availability(object): + INTERNAL = "internal" + BETA = "beta" + GENERAL_AVAILABILITY = "general-availability" + RETIRED = "retired" + DEPRECATED = "deprecated" + + class OutputType(object): + TEXT_CLASSIFICATION = "text-classification" + TEXT_EXTRACTION = "text-extraction" + TEXT_EXTRACTION_NORMALIZED = "text-extraction-normalized" + TEXT_GENERATION = "text-generation" + + class Provider(object): + TWILIO = "twilio" + AMAZON = "amazon" + OPENAI = "openai" + + """ + :ivar name: A unique name that references an Operator's Operator Type. + :ivar sid: A 34 character string that uniquely identifies this Operator Type. + :ivar friendly_name: A human-readable name of this resource, up to 64 characters. + :ivar description: A human-readable description of this resource, longer than the friendly name. + :ivar docs_link: Additional documentation for the Operator Type. + :ivar output_type: + :ivar supported_languages: List of languages this Operator Type supports. + :ivar provider: + :ivar availability: + :ivar configurable: Operators can be created from configurable Operator Types. + :ivar config_schema: JSON Schema for configuring an Operator with this Operator Type. Following https://json-schema.org/ + :ivar date_created: The date that this Operator Type was created, given in ISO 8601 format. + :ivar date_updated: The date that this Operator Type was updated, given in ISO 8601 format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.name: Optional[str] = payload.get("name") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.docs_link: Optional[str] = payload.get("docs_link") + self.output_type: Optional["OperatorTypeInstance.OutputType"] = payload.get( + "output_type" + ) + self.supported_languages: Optional[List[str]] = payload.get( + "supported_languages" + ) + self.provider: Optional["OperatorTypeInstance.Provider"] = payload.get( + "provider" + ) + self.availability: Optional["OperatorTypeInstance.Availability"] = payload.get( + "availability" + ) + self.configurable: Optional[bool] = payload.get("configurable") + self.config_schema: Optional[Dict[str, object]] = payload.get("config_schema") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[OperatorTypeContext] = None + + @property + def _proxy(self) -> "OperatorTypeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperatorTypeContext for this OperatorTypeInstance + """ + if self._context is None: + self._context = OperatorTypeContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "OperatorTypeInstance": + """ + Fetch the OperatorTypeInstance + + + :returns: The fetched OperatorTypeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OperatorTypeInstance": + """ + Asynchronous coroutine to fetch the OperatorTypeInstance + + + :returns: The fetched OperatorTypeInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.OperatorTypeInstance {}>".format(context) + + +class OperatorTypeContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the OperatorTypeContext + + :param version: Version that contains the resource + :param sid: Either a 34 character string that uniquely identifies this Operator Type or the unique name that references an Operator Type. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/OperatorTypes/{sid}".format(**self._solution) + + def fetch(self) -> OperatorTypeInstance: + """ + Fetch the OperatorTypeInstance + + + :returns: The fetched OperatorTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return OperatorTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> OperatorTypeInstance: + """ + Asynchronous coroutine to fetch the OperatorTypeInstance + + + :returns: The fetched OperatorTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return OperatorTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.OperatorTypeContext {}>".format(context) + + +class OperatorTypePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> OperatorTypeInstance: + """ + Build an instance of OperatorTypeInstance + + :param payload: Payload response from the API + """ + return OperatorTypeInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence.V2.OperatorTypePage>" + + +class OperatorTypeList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OperatorTypeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/OperatorTypes" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[OperatorTypeInstance]: + """ + Streams OperatorTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[OperatorTypeInstance]: + """ + Asynchronously streams OperatorTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OperatorTypeInstance]: + """ + Lists OperatorTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OperatorTypeInstance]: + """ + Asynchronously lists OperatorTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OperatorTypePage: + """ + Retrieve a single page of OperatorTypeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OperatorTypeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OperatorTypePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OperatorTypePage: + """ + Asynchronously retrieve a single page of OperatorTypeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OperatorTypeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OperatorTypePage(self._version, response) + + def get_page(self, target_url: str) -> OperatorTypePage: + """ + Retrieve a specific page of OperatorTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OperatorTypeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return OperatorTypePage(self._version, response) + + async def get_page_async(self, target_url: str) -> OperatorTypePage: + """ + Asynchronously retrieve a specific page of OperatorTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OperatorTypeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return OperatorTypePage(self._version, response) + + def get(self, sid: str) -> OperatorTypeContext: + """ + Constructs a OperatorTypeContext + + :param sid: Either a 34 character string that uniquely identifies this Operator Type or the unique name that references an Operator Type. + """ + return OperatorTypeContext(self._version, sid=sid) + + def __call__(self, sid: str) -> OperatorTypeContext: + """ + Constructs a OperatorTypeContext + + :param sid: Either a 34 character string that uniquely identifies this Operator Type or the unique name that references an Operator Type. + """ + return OperatorTypeContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence.V2.OperatorTypeList>" diff --git a/twilio/rest/intelligence/v2/prebuilt_operator.py b/twilio/rest/intelligence/v2/prebuilt_operator.py new file mode 100644 index 0000000000..50693f29c2 --- /dev/null +++ b/twilio/rest/intelligence/v2/prebuilt_operator.py @@ -0,0 +1,488 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PrebuiltOperatorInstance(InstanceResource): + + class Availability(object): + INTERNAL = "internal" + BETA = "beta" + PUBLIC = "public" + RETIRED = "retired" + + """ + :ivar account_sid: The unique SID identifier of the Account the Pre-built Operator belongs to. + :ivar sid: A 34 character string that uniquely identifies this Pre-built Operator. + :ivar friendly_name: A human-readable name of this resource, up to 64 characters. + :ivar description: A human-readable description of this resource, longer than the friendly name. + :ivar author: The creator of the Operator. Pre-built Operators can only be created by Twilio. + :ivar operator_type: Operator Type for this Operator. References an existing Operator Type resource. + :ivar version: Numeric Operator version. Incremented with each update on the resource, used to ensure integrity when updating the Operator. + :ivar availability: + :ivar config: Operator configuration, following the schema defined by the Operator Type. Only available on Custom Operators created by the Account, will be empty for Pre-Built Operators. + :ivar date_created: The date that this Pre-built Operator was created, given in ISO 8601 format. + :ivar date_updated: The date that this Pre-built Operator was updated, given in ISO 8601 format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.author: Optional[str] = payload.get("author") + self.operator_type: Optional[str] = payload.get("operator_type") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.availability: Optional["PrebuiltOperatorInstance.Availability"] = ( + payload.get("availability") + ) + self.config: Optional[Dict[str, object]] = payload.get("config") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[PrebuiltOperatorContext] = None + + @property + def _proxy(self) -> "PrebuiltOperatorContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PrebuiltOperatorContext for this PrebuiltOperatorInstance + """ + if self._context is None: + self._context = PrebuiltOperatorContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "PrebuiltOperatorInstance": + """ + Fetch the PrebuiltOperatorInstance + + + :returns: The fetched PrebuiltOperatorInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PrebuiltOperatorInstance": + """ + Asynchronous coroutine to fetch the PrebuiltOperatorInstance + + + :returns: The fetched PrebuiltOperatorInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.PrebuiltOperatorInstance {}>".format(context) + + +class PrebuiltOperatorContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PrebuiltOperatorContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this Pre-built Operator. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Operators/PreBuilt/{sid}".format(**self._solution) + + def fetch(self) -> PrebuiltOperatorInstance: + """ + Fetch the PrebuiltOperatorInstance + + + :returns: The fetched PrebuiltOperatorInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PrebuiltOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> PrebuiltOperatorInstance: + """ + Asynchronous coroutine to fetch the PrebuiltOperatorInstance + + + :returns: The fetched PrebuiltOperatorInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PrebuiltOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.PrebuiltOperatorContext {}>".format(context) + + +class PrebuiltOperatorPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PrebuiltOperatorInstance: + """ + Build an instance of PrebuiltOperatorInstance + + :param payload: Payload response from the API + """ + return PrebuiltOperatorInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence.V2.PrebuiltOperatorPage>" + + +class PrebuiltOperatorList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PrebuiltOperatorList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Operators/PreBuilt" + + def stream( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PrebuiltOperatorInstance]: + """ + Streams PrebuiltOperatorInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "PrebuiltOperatorInstance.Availability" availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Pre-built Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PrebuiltOperatorInstance]: + """ + Asynchronously streams PrebuiltOperatorInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "PrebuiltOperatorInstance.Availability" availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Pre-built Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PrebuiltOperatorInstance]: + """ + Lists PrebuiltOperatorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "PrebuiltOperatorInstance.Availability" availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Pre-built Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PrebuiltOperatorInstance]: + """ + Asynchronously lists PrebuiltOperatorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "PrebuiltOperatorInstance.Availability" availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param str language_code: Returns Pre-built Operators that support the provided language code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PrebuiltOperatorPage: + """ + Retrieve a single page of PrebuiltOperatorInstance records from the API. + Request is executed immediately + + :param availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param language_code: Returns Pre-built Operators that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PrebuiltOperatorInstance + """ + data = values.of( + { + "Availability": availability, + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PrebuiltOperatorPage(self._version, response) + + async def page_async( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PrebuiltOperatorPage: + """ + Asynchronously retrieve a single page of PrebuiltOperatorInstance records from the API. + Request is executed immediately + + :param availability: Returns Pre-built Operators with the provided availability type. Possible values: internal, beta, public, retired. + :param language_code: Returns Pre-built Operators that support the provided language code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PrebuiltOperatorInstance + """ + data = values.of( + { + "Availability": availability, + "LanguageCode": language_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PrebuiltOperatorPage(self._version, response) + + def get_page(self, target_url: str) -> PrebuiltOperatorPage: + """ + Retrieve a specific page of PrebuiltOperatorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PrebuiltOperatorInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PrebuiltOperatorPage(self._version, response) + + async def get_page_async(self, target_url: str) -> PrebuiltOperatorPage: + """ + Asynchronously retrieve a specific page of PrebuiltOperatorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PrebuiltOperatorInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PrebuiltOperatorPage(self._version, response) + + def get(self, sid: str) -> PrebuiltOperatorContext: + """ + Constructs a PrebuiltOperatorContext + + :param sid: A 34 character string that uniquely identifies this Pre-built Operator. + """ + return PrebuiltOperatorContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PrebuiltOperatorContext: + """ + Constructs a PrebuiltOperatorContext + + :param sid: A 34 character string that uniquely identifies this Pre-built Operator. + """ + return PrebuiltOperatorContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence.V2.PrebuiltOperatorList>" diff --git a/twilio/rest/intelligence/v2/service.py b/twilio/rest/intelligence/v2/service.py new file mode 100644 index 0000000000..fac3eb8473 --- /dev/null +++ b/twilio/rest/intelligence/v2/service.py @@ -0,0 +1,787 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ServiceInstance(InstanceResource): + + class HttpMethod(object): + GET = "GET" + POST = "POST" + NULL = "NULL" + + """ + :ivar account_sid: The unique SID identifier of the Account the Service belongs to. + :ivar auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :ivar media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :ivar auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :ivar data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :ivar date_created: The date that this Service was created, given in ISO 8601 format. + :ivar date_updated: The date that this Service was updated, given in ISO 8601 format. + :ivar friendly_name: A human readable description of this resource, up to 64 characters. + :ivar language_code: The language code set during Service creation determines the Transcription language for all call recordings processed by that Service. The default is en-US if no language code is set. A Service can only support one language code, and it cannot be updated once it's set. + :ivar sid: A 34 character string that uniquely identifies this Service. + :ivar unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :ivar url: The URL of this resource. + :ivar webhook_url: The URL Twilio will request when executing the Webhook. + :ivar webhook_http_method: + :ivar read_only_attached_operator_sids: Operator sids attached to this service, read only + :ivar version: The version number of this Service. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.auto_redaction: Optional[bool] = payload.get("auto_redaction") + self.media_redaction: Optional[bool] = payload.get("media_redaction") + self.auto_transcribe: Optional[bool] = payload.get("auto_transcribe") + self.data_logging: Optional[bool] = payload.get("data_logging") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.language_code: Optional[str] = payload.get("language_code") + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.url: Optional[str] = payload.get("url") + self.webhook_url: Optional[str] = payload.get("webhook_url") + self.webhook_http_method: Optional["ServiceInstance.HttpMethod"] = payload.get( + "webhook_http_method" + ) + self.read_only_attached_operator_sids: Optional[List[str]] = payload.get( + "read_only_attached_operator_sids" + ) + self.version: Optional[int] = deserialize.integer(payload.get("version")) + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + if_match: Union[str, object] = values.unset, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param if_match: The If-Match HTTP request header + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + if_match=if_match, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + unique_name=unique_name, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param if_match: The If-Match HTTP request header + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + if_match=if_match, + auto_transcribe=auto_transcribe, + data_logging=data_logging, + friendly_name=friendly_name, + unique_name=unique_name, + auto_redaction=auto_redaction, + media_redaction=media_redaction, + webhook_url=webhook_url, + webhook_http_method=webhook_http_method, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.ServiceInstance {}>".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this Service. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param if_match: The If-Match HTTP request header + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "AutoTranscribe": serialize.boolean_to_string(auto_transcribe), + "DataLogging": serialize.boolean_to_string(data_logging), + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "AutoRedaction": serialize.boolean_to_string(auto_redaction), + "MediaRedaction": serialize.boolean_to_string(media_redaction), + "WebhookUrl": webhook_url, + "WebhookHttpMethod": webhook_http_method, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param if_match: The If-Match HTTP request header + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "AutoTranscribe": serialize.boolean_to_string(auto_transcribe), + "DataLogging": serialize.boolean_to_string(data_logging), + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "AutoRedaction": serialize.boolean_to_string(auto_redaction), + "MediaRedaction": serialize.boolean_to_string(media_redaction), + "WebhookUrl": webhook_url, + "WebhookHttpMethod": webhook_http_method, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.ServiceContext {}>".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence.V2.ServicePage>" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create( + self, + unique_name: str, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param language_code: The language code set during Service creation determines the Transcription language for all call recordings processed by that Service. The default is en-US if no language code is set. A Service can only support one language code, and it cannot be updated once it's set. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "AutoTranscribe": serialize.boolean_to_string(auto_transcribe), + "DataLogging": serialize.boolean_to_string(data_logging), + "FriendlyName": friendly_name, + "LanguageCode": language_code, + "AutoRedaction": serialize.boolean_to_string(auto_redaction), + "MediaRedaction": serialize.boolean_to_string(media_redaction), + "WebhookUrl": webhook_url, + "WebhookHttpMethod": webhook_http_method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async( + self, + unique_name: str, + auto_transcribe: Union[bool, object] = values.unset, + data_logging: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + auto_redaction: Union[bool, object] = values.unset, + media_redaction: Union[bool, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + webhook_http_method: Union["ServiceInstance.HttpMethod", object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param unique_name: Provides a unique and addressable name to be assigned to this Service, assigned by the developer, to be optionally used in addition to SID. + :param auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :param data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param language_code: The language code set during Service creation determines the Transcription language for all call recordings processed by that Service. The default is en-US if no language code is set. A Service can only support one language code, and it cannot be updated once it's set. + :param auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :param media_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts media made on this service. The auto_redaction flag must be enabled, results in error otherwise. + :param webhook_url: The URL Twilio will request when executing the Webhook. + :param webhook_http_method: + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "AutoTranscribe": serialize.boolean_to_string(auto_transcribe), + "DataLogging": serialize.boolean_to_string(data_logging), + "FriendlyName": friendly_name, + "LanguageCode": language_code, + "AutoRedaction": serialize.boolean_to_string(auto_redaction), + "MediaRedaction": serialize.boolean_to_string(media_redaction), + "WebhookUrl": webhook_url, + "WebhookHttpMethod": webhook_http_method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: A 34 character string that uniquely identifies this Service. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: A 34 character string that uniquely identifies this Service. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence.V2.ServiceList>" diff --git a/twilio/rest/intelligence/v2/transcript/__init__.py b/twilio/rest/intelligence/v2/transcript/__init__.py new file mode 100644 index 0000000000..c2141bb5da --- /dev/null +++ b/twilio/rest/intelligence/v2/transcript/__init__.py @@ -0,0 +1,775 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.intelligence.v2.transcript.media import MediaList +from twilio.rest.intelligence.v2.transcript.operator_result import OperatorResultList +from twilio.rest.intelligence.v2.transcript.sentence import SentenceList + + +class TranscriptInstance(InstanceResource): + + class Status(object): + QUEUED = "queued" + IN_PROGRESS = "in-progress" + COMPLETED = "completed" + FAILED = "failed" + CANCELED = "canceled" + + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Service. + :ivar sid: A 34 character string that uniquely identifies this Transcript. + :ivar date_created: The date that this Transcript was created, given in ISO 8601 format. + :ivar date_updated: The date that this Transcript was updated, given in ISO 8601 format. + :ivar status: + :ivar channel: Media Channel describing Transcript Source and Participant Mapping + :ivar data_logging: Data logging allows Twilio to improve the quality of the speech recognition & language understanding services through using customer data to refine, fine tune and evaluate machine learning models. Note: Data logging cannot be activated via API, only via www.twilio.com, as it requires additional consent. + :ivar language_code: The default language code of the audio. + :ivar customer_key: + :ivar media_start_time: The date that this Transcript's media was started, given in ISO 8601 format. + :ivar duration: The duration of this Transcript's source + :ivar url: The URL of this resource. + :ivar redaction: If the transcript has been redacted, a redacted alternative of the transcript will be available. + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.sid: Optional[str] = payload.get("sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.status: Optional["TranscriptInstance.Status"] = payload.get("status") + self.channel: Optional[Dict[str, object]] = payload.get("channel") + self.data_logging: Optional[bool] = payload.get("data_logging") + self.language_code: Optional[str] = payload.get("language_code") + self.customer_key: Optional[str] = payload.get("customer_key") + self.media_start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("media_start_time") + ) + self.duration: Optional[int] = deserialize.integer(payload.get("duration")) + self.url: Optional[str] = payload.get("url") + self.redaction: Optional[bool] = payload.get("redaction") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[TranscriptContext] = None + + @property + def _proxy(self) -> "TranscriptContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TranscriptContext for this TranscriptInstance + """ + if self._context is None: + self._context = TranscriptContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TranscriptInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TranscriptInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TranscriptInstance": + """ + Fetch the TranscriptInstance + + + :returns: The fetched TranscriptInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TranscriptInstance": + """ + Asynchronous coroutine to fetch the TranscriptInstance + + + :returns: The fetched TranscriptInstance + """ + return await self._proxy.fetch_async() + + @property + def media(self) -> MediaList: + """ + Access the media + """ + return self._proxy.media + + @property + def operator_results(self) -> OperatorResultList: + """ + Access the operator_results + """ + return self._proxy.operator_results + + @property + def sentences(self) -> SentenceList: + """ + Access the sentences + """ + return self._proxy.sentences + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.TranscriptInstance {}>".format(context) + + +class TranscriptContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the TranscriptContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this Transcript. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Transcripts/{sid}".format(**self._solution) + + self._media: Optional[MediaList] = None + self._operator_results: Optional[OperatorResultList] = None + self._sentences: Optional[SentenceList] = None + + def delete(self) -> bool: + """ + Deletes the TranscriptInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TranscriptInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TranscriptInstance: + """ + Fetch the TranscriptInstance + + + :returns: The fetched TranscriptInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TranscriptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TranscriptInstance: + """ + Asynchronous coroutine to fetch the TranscriptInstance + + + :returns: The fetched TranscriptInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TranscriptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + @property + def media(self) -> MediaList: + """ + Access the media + """ + if self._media is None: + self._media = MediaList( + self._version, + self._solution["sid"], + ) + return self._media + + @property + def operator_results(self) -> OperatorResultList: + """ + Access the operator_results + """ + if self._operator_results is None: + self._operator_results = OperatorResultList( + self._version, + self._solution["sid"], + ) + return self._operator_results + + @property + def sentences(self) -> SentenceList: + """ + Access the sentences + """ + if self._sentences is None: + self._sentences = SentenceList( + self._version, + self._solution["sid"], + ) + return self._sentences + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.TranscriptContext {}>".format(context) + + +class TranscriptPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TranscriptInstance: + """ + Build an instance of TranscriptInstance + + :param payload: Payload response from the API + """ + return TranscriptInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence.V2.TranscriptPage>" + + +class TranscriptList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TranscriptList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Transcripts" + + def create( + self, + service_sid: str, + channel: object, + customer_key: Union[str, object] = values.unset, + media_start_time: Union[datetime, object] = values.unset, + ) -> TranscriptInstance: + """ + Create the TranscriptInstance + + :param service_sid: The unique SID identifier of the Service. + :param channel: JSON object describing Media Channel including Source and Participants + :param customer_key: Used to store client provided metadata. Maximum of 64 double-byte UTF8 characters. + :param media_start_time: The date that this Transcript's media was started, given in ISO 8601 format. + + :returns: The created TranscriptInstance + """ + + data = values.of( + { + "ServiceSid": service_sid, + "Channel": serialize.object(channel), + "CustomerKey": customer_key, + "MediaStartTime": serialize.iso8601_datetime(media_start_time), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TranscriptInstance(self._version, payload) + + async def create_async( + self, + service_sid: str, + channel: object, + customer_key: Union[str, object] = values.unset, + media_start_time: Union[datetime, object] = values.unset, + ) -> TranscriptInstance: + """ + Asynchronously create the TranscriptInstance + + :param service_sid: The unique SID identifier of the Service. + :param channel: JSON object describing Media Channel including Source and Participants + :param customer_key: Used to store client provided metadata. Maximum of 64 double-byte UTF8 characters. + :param media_start_time: The date that this Transcript's media was started, given in ISO 8601 format. + + :returns: The created TranscriptInstance + """ + + data = values.of( + { + "ServiceSid": service_sid, + "Channel": serialize.object(channel), + "CustomerKey": customer_key, + "MediaStartTime": serialize.iso8601_datetime(media_start_time), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TranscriptInstance(self._version, payload) + + def stream( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TranscriptInstance]: + """ + Streams TranscriptInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str service_sid: The unique SID identifier of the Service. + :param str before_start_time: Filter by before StartTime. + :param str after_start_time: Filter by after StartTime. + :param str before_date_created: Filter by before DateCreated. + :param str after_date_created: Filter by after DateCreated. + :param str status: Filter by status. + :param str language_code: Filter by Language Code. + :param str source_sid: Filter by SourceSid. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + service_sid=service_sid, + before_start_time=before_start_time, + after_start_time=after_start_time, + before_date_created=before_date_created, + after_date_created=after_date_created, + status=status, + language_code=language_code, + source_sid=source_sid, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TranscriptInstance]: + """ + Asynchronously streams TranscriptInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str service_sid: The unique SID identifier of the Service. + :param str before_start_time: Filter by before StartTime. + :param str after_start_time: Filter by after StartTime. + :param str before_date_created: Filter by before DateCreated. + :param str after_date_created: Filter by after DateCreated. + :param str status: Filter by status. + :param str language_code: Filter by Language Code. + :param str source_sid: Filter by SourceSid. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + service_sid=service_sid, + before_start_time=before_start_time, + after_start_time=after_start_time, + before_date_created=before_date_created, + after_date_created=after_date_created, + status=status, + language_code=language_code, + source_sid=source_sid, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptInstance]: + """ + Lists TranscriptInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str service_sid: The unique SID identifier of the Service. + :param str before_start_time: Filter by before StartTime. + :param str after_start_time: Filter by after StartTime. + :param str before_date_created: Filter by before DateCreated. + :param str after_date_created: Filter by after DateCreated. + :param str status: Filter by status. + :param str language_code: Filter by Language Code. + :param str source_sid: Filter by SourceSid. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + service_sid=service_sid, + before_start_time=before_start_time, + after_start_time=after_start_time, + before_date_created=before_date_created, + after_date_created=after_date_created, + status=status, + language_code=language_code, + source_sid=source_sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TranscriptInstance]: + """ + Asynchronously lists TranscriptInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str service_sid: The unique SID identifier of the Service. + :param str before_start_time: Filter by before StartTime. + :param str after_start_time: Filter by after StartTime. + :param str before_date_created: Filter by before DateCreated. + :param str after_date_created: Filter by after DateCreated. + :param str status: Filter by status. + :param str language_code: Filter by Language Code. + :param str source_sid: Filter by SourceSid. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + service_sid=service_sid, + before_start_time=before_start_time, + after_start_time=after_start_time, + before_date_created=before_date_created, + after_date_created=after_date_created, + status=status, + language_code=language_code, + source_sid=source_sid, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TranscriptPage: + """ + Retrieve a single page of TranscriptInstance records from the API. + Request is executed immediately + + :param service_sid: The unique SID identifier of the Service. + :param before_start_time: Filter by before StartTime. + :param after_start_time: Filter by after StartTime. + :param before_date_created: Filter by before DateCreated. + :param after_date_created: Filter by after DateCreated. + :param status: Filter by status. + :param language_code: Filter by Language Code. + :param source_sid: Filter by SourceSid. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TranscriptInstance + """ + data = values.of( + { + "ServiceSid": service_sid, + "BeforeStartTime": before_start_time, + "AfterStartTime": after_start_time, + "BeforeDateCreated": before_date_created, + "AfterDateCreated": after_date_created, + "Status": status, + "LanguageCode": language_code, + "SourceSid": source_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TranscriptPage(self._version, response) + + async def page_async( + self, + service_sid: Union[str, object] = values.unset, + before_start_time: Union[str, object] = values.unset, + after_start_time: Union[str, object] = values.unset, + before_date_created: Union[str, object] = values.unset, + after_date_created: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + language_code: Union[str, object] = values.unset, + source_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TranscriptPage: + """ + Asynchronously retrieve a single page of TranscriptInstance records from the API. + Request is executed immediately + + :param service_sid: The unique SID identifier of the Service. + :param before_start_time: Filter by before StartTime. + :param after_start_time: Filter by after StartTime. + :param before_date_created: Filter by before DateCreated. + :param after_date_created: Filter by after DateCreated. + :param status: Filter by status. + :param language_code: Filter by Language Code. + :param source_sid: Filter by SourceSid. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TranscriptInstance + """ + data = values.of( + { + "ServiceSid": service_sid, + "BeforeStartTime": before_start_time, + "AfterStartTime": after_start_time, + "BeforeDateCreated": before_date_created, + "AfterDateCreated": after_date_created, + "Status": status, + "LanguageCode": language_code, + "SourceSid": source_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TranscriptPage(self._version, response) + + def get_page(self, target_url: str) -> TranscriptPage: + """ + Retrieve a specific page of TranscriptInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TranscriptInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TranscriptPage(self._version, response) + + async def get_page_async(self, target_url: str) -> TranscriptPage: + """ + Asynchronously retrieve a specific page of TranscriptInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TranscriptInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TranscriptPage(self._version, response) + + def get(self, sid: str) -> TranscriptContext: + """ + Constructs a TranscriptContext + + :param sid: A 34 character string that uniquely identifies this Transcript. + """ + return TranscriptContext(self._version, sid=sid) + + def __call__(self, sid: str) -> TranscriptContext: + """ + Constructs a TranscriptContext + + :param sid: A 34 character string that uniquely identifies this Transcript. + """ + return TranscriptContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence.V2.TranscriptList>" diff --git a/twilio/rest/intelligence/v2/transcript/media.py b/twilio/rest/intelligence/v2/transcript/media.py new file mode 100644 index 0000000000..76bc448e9b --- /dev/null +++ b/twilio/rest/intelligence/v2/transcript/media.py @@ -0,0 +1,221 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class MediaInstance(InstanceResource): + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar media_url: Downloadable URL for media, if stored in Twilio AI. + :ivar service_sid: The unique SID identifier of the Service. + :ivar sid: The unique SID identifier of the Transcript. + :ivar url: The URL of this resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.media_url: Optional[str] = payload.get("media_url") + self.service_sid: Optional[str] = payload.get("service_sid") + self.sid: Optional[str] = payload.get("sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid, + } + self._context: Optional[MediaContext] = None + + @property + def _proxy(self) -> "MediaContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MediaContext for this MediaInstance + """ + if self._context is None: + self._context = MediaContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self, redacted: Union[bool, object] = values.unset) -> "MediaInstance": + """ + Fetch the MediaInstance + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: The fetched MediaInstance + """ + return self._proxy.fetch( + redacted=redacted, + ) + + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> "MediaInstance": + """ + Asynchronous coroutine to fetch the MediaInstance + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: The fetched MediaInstance + """ + return await self._proxy.fetch_async( + redacted=redacted, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.MediaInstance {}>".format(context) + + +class MediaContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the MediaContext + + :param version: Version that contains the resource + :param sid: The unique SID identifier of the Transcript. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Transcripts/{sid}/Media".format(**self._solution) + + def fetch(self, redacted: Union[bool, object] = values.unset) -> MediaInstance: + """ + Fetch the MediaInstance + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: The fetched MediaInstance + """ + + data = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return MediaInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> MediaInstance: + """ + Asynchronous coroutine to fetch the MediaInstance + + :param redacted: Grant access to PII Redacted/Unredacted Media. If redaction is enabled, the default is `true` to access redacted media. + + :returns: The fetched MediaInstance + """ + + data = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return MediaInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.MediaContext {}>".format(context) + + +class MediaList(ListResource): + + def __init__(self, version: Version, sid: str): + """ + Initialize the MediaList + + :param version: Version that contains the resource + :param sid: The unique SID identifier of the Transcript. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + + def get(self) -> MediaContext: + """ + Constructs a MediaContext + + """ + return MediaContext(self._version, sid=self._solution["sid"]) + + def __call__(self) -> MediaContext: + """ + Constructs a MediaContext + + """ + return MediaContext(self._version, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence.V2.MediaList>" diff --git a/twilio/rest/intelligence/v2/transcript/operator_result.py b/twilio/rest/intelligence/v2/transcript/operator_result.py new file mode 100644 index 0000000000..9ba2c57f62 --- /dev/null +++ b/twilio/rest/intelligence/v2/transcript/operator_result.py @@ -0,0 +1,531 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class OperatorResultInstance(InstanceResource): + + class OperatorType(object): + CONVERSATION_CLASSIFY = "conversation_classify" + UTTERANCE_CLASSIFY = "utterance_classify" + EXTRACT = "extract" + EXTRACT_NORMALIZE = "extract_normalize" + PII_EXTRACT = "pii_extract" + TEXT_GENERATION = "text_generation" + JSON = "json" + + """ + :ivar operator_type: + :ivar name: The name of the applied Language Understanding. + :ivar operator_sid: A 34 character string that identifies this Language Understanding operator sid. + :ivar extract_match: Boolean to tell if extract Language Understanding Processing model matches results. + :ivar match_probability: Percentage of 'matching' class needed to consider a sentence matches + :ivar normalized_result: Normalized output of extraction stage which matches Label. + :ivar utterance_results: List of mapped utterance object which matches sentences. + :ivar utterance_match: Boolean to tell if Utterance matches results. + :ivar predicted_label: The 'matching' class. This might be available on conversation classify model outputs. + :ivar predicted_probability: Percentage of 'matching' class needed to consider a sentence matches. + :ivar label_probabilities: The labels probabilities. This might be available on conversation classify model outputs. + :ivar extract_results: List of text extraction results. This might be available on classify-extract model outputs. + :ivar text_generation_results: Output of a text generation operator for example Conversation Sumamary. + :ivar json_results: + :ivar transcript_sid: A 34 character string that uniquely identifies this Transcript. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + transcript_sid: str, + operator_sid: Optional[str] = None, + ): + super().__init__(version) + + self.operator_type: Optional["OperatorResultInstance.OperatorType"] = ( + payload.get("operator_type") + ) + self.name: Optional[str] = payload.get("name") + self.operator_sid: Optional[str] = payload.get("operator_sid") + self.extract_match: Optional[bool] = payload.get("extract_match") + self.match_probability: Optional[float] = deserialize.decimal( + payload.get("match_probability") + ) + self.normalized_result: Optional[str] = payload.get("normalized_result") + self.utterance_results: Optional[List[Dict[str, object]]] = payload.get( + "utterance_results" + ) + self.utterance_match: Optional[bool] = payload.get("utterance_match") + self.predicted_label: Optional[str] = payload.get("predicted_label") + self.predicted_probability: Optional[float] = deserialize.decimal( + payload.get("predicted_probability") + ) + self.label_probabilities: Optional[Dict[str, object]] = payload.get( + "label_probabilities" + ) + self.extract_results: Optional[Dict[str, object]] = payload.get( + "extract_results" + ) + self.text_generation_results: Optional[Dict[str, object]] = payload.get( + "text_generation_results" + ) + self.json_results: Optional[Dict[str, object]] = payload.get("json_results") + self.transcript_sid: Optional[str] = payload.get("transcript_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "transcript_sid": transcript_sid, + "operator_sid": operator_sid or self.operator_sid, + } + self._context: Optional[OperatorResultContext] = None + + @property + def _proxy(self) -> "OperatorResultContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperatorResultContext for this OperatorResultInstance + """ + if self._context is None: + self._context = OperatorResultContext( + self._version, + transcript_sid=self._solution["transcript_sid"], + operator_sid=self._solution["operator_sid"], + ) + return self._context + + def fetch( + self, redacted: Union[bool, object] = values.unset + ) -> "OperatorResultInstance": + """ + Fetch the OperatorResultInstance + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + + :returns: The fetched OperatorResultInstance + """ + return self._proxy.fetch( + redacted=redacted, + ) + + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> "OperatorResultInstance": + """ + Asynchronous coroutine to fetch the OperatorResultInstance + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + + :returns: The fetched OperatorResultInstance + """ + return await self._proxy.fetch_async( + redacted=redacted, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.OperatorResultInstance {}>".format(context) + + +class OperatorResultContext(InstanceContext): + + def __init__(self, version: Version, transcript_sid: str, operator_sid: str): + """ + Initialize the OperatorResultContext + + :param version: Version that contains the resource + :param transcript_sid: A 34 character string that uniquely identifies this Transcript. + :param operator_sid: A 34 character string that identifies this Language Understanding operator sid. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "transcript_sid": transcript_sid, + "operator_sid": operator_sid, + } + self._uri = ( + "/Transcripts/{transcript_sid}/OperatorResults/{operator_sid}".format( + **self._solution + ) + ) + + def fetch( + self, redacted: Union[bool, object] = values.unset + ) -> OperatorResultInstance: + """ + Fetch the OperatorResultInstance + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + + :returns: The fetched OperatorResultInstance + """ + + data = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return OperatorResultInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + operator_sid=self._solution["operator_sid"], + ) + + async def fetch_async( + self, redacted: Union[bool, object] = values.unset + ) -> OperatorResultInstance: + """ + Asynchronous coroutine to fetch the OperatorResultInstance + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + + :returns: The fetched OperatorResultInstance + """ + + data = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return OperatorResultInstance( + self._version, + payload, + transcript_sid=self._solution["transcript_sid"], + operator_sid=self._solution["operator_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.OperatorResultContext {}>".format(context) + + +class OperatorResultPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> OperatorResultInstance: + """ + Build an instance of OperatorResultInstance + + :param payload: Payload response from the API + """ + return OperatorResultInstance( + self._version, payload, transcript_sid=self._solution["transcript_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence.V2.OperatorResultPage>" + + +class OperatorResultList(ListResource): + + def __init__(self, version: Version, transcript_sid: str): + """ + Initialize the OperatorResultList + + :param version: Version that contains the resource + :param transcript_sid: A 34 character string that uniquely identifies this Transcript. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "transcript_sid": transcript_sid, + } + self._uri = "/Transcripts/{transcript_sid}/OperatorResults".format( + **self._solution + ) + + def stream( + self, + redacted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[OperatorResultInstance]: + """ + Streams OperatorResultInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(redacted=redacted, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + redacted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[OperatorResultInstance]: + """ + Asynchronously streams OperatorResultInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(redacted=redacted, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + redacted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OperatorResultInstance]: + """ + Lists OperatorResultInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + redacted=redacted, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + redacted: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OperatorResultInstance]: + """ + Asynchronously lists OperatorResultInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + redacted=redacted, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + redacted: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OperatorResultPage: + """ + Retrieve a single page of OperatorResultInstance records from the API. + Request is executed immediately + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OperatorResultInstance + """ + data = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OperatorResultPage(self._version, response, self._solution) + + async def page_async( + self, + redacted: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OperatorResultPage: + """ + Asynchronously retrieve a single page of OperatorResultInstance records from the API. + Request is executed immediately + + :param redacted: Grant access to PII redacted/unredacted Language Understanding operator. If redaction is enabled, the default is True. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OperatorResultInstance + """ + data = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OperatorResultPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> OperatorResultPage: + """ + Retrieve a specific page of OperatorResultInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OperatorResultInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return OperatorResultPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> OperatorResultPage: + """ + Asynchronously retrieve a specific page of OperatorResultInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OperatorResultInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return OperatorResultPage(self._version, response, self._solution) + + def get(self, operator_sid: str) -> OperatorResultContext: + """ + Constructs a OperatorResultContext + + :param operator_sid: A 34 character string that identifies this Language Understanding operator sid. + """ + return OperatorResultContext( + self._version, + transcript_sid=self._solution["transcript_sid"], + operator_sid=operator_sid, + ) + + def __call__(self, operator_sid: str) -> OperatorResultContext: + """ + Constructs a OperatorResultContext + + :param operator_sid: A 34 character string that identifies this Language Understanding operator sid. + """ + return OperatorResultContext( + self._version, + transcript_sid=self._solution["transcript_sid"], + operator_sid=operator_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence.V2.OperatorResultList>" diff --git a/twilio/rest/intelligence/v2/transcript/sentence.py b/twilio/rest/intelligence/v2/transcript/sentence.py new file mode 100644 index 0000000000..f4fb0b3b92 --- /dev/null +++ b/twilio/rest/intelligence/v2/transcript/sentence.py @@ -0,0 +1,348 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Intelligence + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SentenceInstance(InstanceResource): + """ + :ivar media_channel: The channel number. + :ivar sentence_index: The index of the sentence in the transcript. + :ivar start_time: Offset from the beginning of the transcript when this sentence starts. + :ivar end_time: Offset from the beginning of the transcript when this sentence ends. + :ivar transcript: Transcript text. + :ivar sid: A 34 character string that uniquely identifies this Sentence. + :ivar confidence: + :ivar words: Detailed information for each of the words of the given Sentence. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], transcript_sid: str): + super().__init__(version) + + self.media_channel: Optional[int] = deserialize.integer( + payload.get("media_channel") + ) + self.sentence_index: Optional[int] = deserialize.integer( + payload.get("sentence_index") + ) + self.start_time: Optional[float] = deserialize.decimal( + payload.get("start_time") + ) + self.end_time: Optional[float] = deserialize.decimal(payload.get("end_time")) + self.transcript: Optional[str] = payload.get("transcript") + self.sid: Optional[str] = payload.get("sid") + self.confidence: Optional[float] = deserialize.decimal( + payload.get("confidence") + ) + self.words: Optional[List[Dict[str, object]]] = payload.get("words") + + self._solution = { + "transcript_sid": transcript_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Intelligence.V2.SentenceInstance {}>".format(context) + + +class SentencePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SentenceInstance: + """ + Build an instance of SentenceInstance + + :param payload: Payload response from the API + """ + return SentenceInstance( + self._version, payload, transcript_sid=self._solution["transcript_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence.V2.SentencePage>" + + +class SentenceList(ListResource): + + def __init__(self, version: Version, transcript_sid: str): + """ + Initialize the SentenceList + + :param version: Version that contains the resource + :param transcript_sid: The unique SID identifier of the Transcript. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "transcript_sid": transcript_sid, + } + self._uri = "/Transcripts/{transcript_sid}/Sentences".format(**self._solution) + + def stream( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SentenceInstance]: + """ + Streams SentenceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + :param bool word_timestamps: Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + redacted=redacted, + word_timestamps=word_timestamps, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SentenceInstance]: + """ + Asynchronously streams SentenceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + :param bool word_timestamps: Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + redacted=redacted, + word_timestamps=word_timestamps, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SentenceInstance]: + """ + Lists SentenceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + :param bool word_timestamps: Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + redacted=redacted, + word_timestamps=word_timestamps, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SentenceInstance]: + """ + Asynchronously lists SentenceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + :param bool word_timestamps: Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + redacted=redacted, + word_timestamps=word_timestamps, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SentencePage: + """ + Retrieve a single page of SentenceInstance records from the API. + Request is executed immediately + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + :param word_timestamps: Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SentenceInstance + """ + data = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + "WordTimestamps": serialize.boolean_to_string(word_timestamps), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SentencePage(self._version, response, self._solution) + + async def page_async( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SentencePage: + """ + Asynchronously retrieve a single page of SentenceInstance records from the API. + Request is executed immediately + + :param redacted: Grant access to PII Redacted/Unredacted Sentences. If redaction is enabled, the default is `true` to access redacted sentences. + :param word_timestamps: Returns word level timestamps information, if word_timestamps is enabled. The default is `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SentenceInstance + """ + data = values.of( + { + "Redacted": serialize.boolean_to_string(redacted), + "WordTimestamps": serialize.boolean_to_string(word_timestamps), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SentencePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SentencePage: + """ + Retrieve a specific page of SentenceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SentenceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SentencePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SentencePage: + """ + Asynchronously retrieve a specific page of SentenceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SentenceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SentencePage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Intelligence.V2.SentenceList>" diff --git a/twilio/rest/ip_messaging/IpMessagingBase.py b/twilio/rest/ip_messaging/IpMessagingBase.py new file mode 100644 index 0000000000..752d41adce --- /dev/null +++ b/twilio/rest/ip_messaging/IpMessagingBase.py @@ -0,0 +1,55 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.ip_messaging.v1 import V1 +from twilio.rest.ip_messaging.v2 import V2 + + +class IpMessagingBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the IpMessaging Domain + + :returns: Domain for IpMessaging + """ + super().__init__(twilio, "https://ip-messaging.twilio.com") + self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of IpMessaging + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of IpMessaging + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging>" diff --git a/twilio/rest/ip_messaging/__init__.py b/twilio/rest/ip_messaging/__init__.py new file mode 100644 index 0000000000..61158f8e6a --- /dev/null +++ b/twilio/rest/ip_messaging/__init__.py @@ -0,0 +1,25 @@ +from warnings import warn + +from twilio.rest.ip_messaging.IpMessagingBase import IpMessagingBase +from twilio.rest.ip_messaging.v2.credential import CredentialList +from twilio.rest.ip_messaging.v2.service import ServiceList + + +class IpMessaging(IpMessagingBase): + @property + def credentials(self) -> CredentialList: + warn( + "credentials is deprecated. Use v2.credentials instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.credentials + + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v2.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.services diff --git a/twilio/rest/ip_messaging/v1/__init__.py b/twilio/rest/ip_messaging/v1/__init__.py new file mode 100644 index 0000000000..d1f40c791f --- /dev/null +++ b/twilio/rest/ip_messaging/v1/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.ip_messaging.v1.credential import CredentialList +from twilio.rest.ip_messaging.v1.service import ServiceList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of IpMessaging + + :param domain: The Twilio.ip_messaging domain + """ + super().__init__(domain, "v1") + self._credentials: Optional[CredentialList] = None + self._services: Optional[ServiceList] = None + + @property + def credentials(self) -> CredentialList: + if self._credentials is None: + self._credentials = CredentialList(self) + return self._credentials + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V1>" diff --git a/twilio/rest/ip_messaging/v1/credential.py b/twilio/rest/ip_messaging/v1/credential.py new file mode 100644 index 0000000000..4aa6d3fc63 --- /dev/null +++ b/twilio/rest/ip_messaging/v1/credential.py @@ -0,0 +1,711 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CredentialInstance(InstanceResource): + + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: + :ivar account_sid: + :ivar friendly_name: + :ivar type: + :ivar sandbox: + :ivar date_created: + :ivar date_updated: + :ivar url: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushService"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None + + @property + def _proxy(self) -> "CredentialContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CredentialInstance": + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialInstance": + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Update the CredentialInstance + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V1.CredentialInstance {}>".format(context) + + +class CredentialContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CredentialContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Update the CredentialInstance + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V1.CredentialContext {}>".format(context) + + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance + + :param payload: Payload response from the API + """ + return CredentialInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V1.CredentialPage>" + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Credentials" + + def create( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Create the CredentialInstance + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + async def create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialInstance]: + """ + Streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: + """ + Asynchronously streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Asynchronously lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Asynchronously retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + def get_page(self, target_url: str) -> CredentialPage: + """ + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CredentialPage: + """ + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) + + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: + """ + return CredentialContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: + """ + return CredentialContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V1.CredentialList>" diff --git a/twilio/rest/ip_messaging/v1/service/__init__.py b/twilio/rest/ip_messaging/v1/service/__init__.py new file mode 100644 index 0000000000..3a77cf765e --- /dev/null +++ b/twilio/rest/ip_messaging/v1/service/__init__.py @@ -0,0 +1,1359 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.ip_messaging.v1.service.channel import ChannelList +from twilio.rest.ip_messaging.v1.service.role import RoleList +from twilio.rest.ip_messaging.v1.service.user import UserList + + +class ServiceInstance(InstanceResource): + """ + :ivar sid: + :ivar account_sid: + :ivar friendly_name: + :ivar date_created: + :ivar date_updated: + :ivar default_service_role_sid: + :ivar default_channel_role_sid: + :ivar default_channel_creator_role_sid: + :ivar read_status_enabled: + :ivar reachability_enabled: + :ivar typing_indicator_timeout: + :ivar consumption_report_interval: + :ivar limits: + :ivar webhooks: + :ivar pre_webhook_url: + :ivar post_webhook_url: + :ivar webhook_method: + :ivar webhook_filters: + :ivar notifications: + :ivar url: + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.default_service_role_sid: Optional[str] = payload.get( + "default_service_role_sid" + ) + self.default_channel_role_sid: Optional[str] = payload.get( + "default_channel_role_sid" + ) + self.default_channel_creator_role_sid: Optional[str] = payload.get( + "default_channel_creator_role_sid" + ) + self.read_status_enabled: Optional[bool] = payload.get("read_status_enabled") + self.reachability_enabled: Optional[bool] = payload.get("reachability_enabled") + self.typing_indicator_timeout: Optional[int] = deserialize.integer( + payload.get("typing_indicator_timeout") + ) + self.consumption_report_interval: Optional[int] = deserialize.integer( + payload.get("consumption_report_interval") + ) + self.limits: Optional[Dict[str, object]] = payload.get("limits") + self.webhooks: Optional[Dict[str, object]] = payload.get("webhooks") + self.pre_webhook_url: Optional[str] = payload.get("pre_webhook_url") + self.post_webhook_url: Optional[str] = payload.get("post_webhook_url") + self.webhook_method: Optional[str] = payload.get("webhook_method") + self.webhook_filters: Optional[List[str]] = payload.get("webhook_filters") + self.notifications: Optional[Dict[str, object]] = payload.get("notifications") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param webhooks_on_message_send_url: + :param webhooks_on_message_send_method: + :param webhooks_on_message_update_url: + :param webhooks_on_message_update_method: + :param webhooks_on_message_remove_url: + :param webhooks_on_message_remove_method: + :param webhooks_on_channel_add_url: + :param webhooks_on_channel_add_method: + :param webhooks_on_channel_destroy_url: + :param webhooks_on_channel_destroy_method: + :param webhooks_on_channel_update_url: + :param webhooks_on_channel_update_method: + :param webhooks_on_member_add_url: + :param webhooks_on_member_add_method: + :param webhooks_on_member_remove_url: + :param webhooks_on_member_remove_method: + :param webhooks_on_message_sent_url: + :param webhooks_on_message_sent_method: + :param webhooks_on_message_updated_url: + :param webhooks_on_message_updated_method: + :param webhooks_on_message_removed_url: + :param webhooks_on_message_removed_method: + :param webhooks_on_channel_added_url: + :param webhooks_on_channel_added_method: + :param webhooks_on_channel_destroyed_url: + :param webhooks_on_channel_destroyed_method: + :param webhooks_on_channel_updated_url: + :param webhooks_on_channel_updated_method: + :param webhooks_on_member_added_url: + :param webhooks_on_member_added_method: + :param webhooks_on_member_removed_url: + :param webhooks_on_member_removed_method: + :param limits_channel_members: + :param limits_user_channels: + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param webhooks_on_message_send_url: + :param webhooks_on_message_send_method: + :param webhooks_on_message_update_url: + :param webhooks_on_message_update_method: + :param webhooks_on_message_remove_url: + :param webhooks_on_message_remove_method: + :param webhooks_on_channel_add_url: + :param webhooks_on_channel_add_method: + :param webhooks_on_channel_destroy_url: + :param webhooks_on_channel_destroy_method: + :param webhooks_on_channel_update_url: + :param webhooks_on_channel_update_method: + :param webhooks_on_member_add_url: + :param webhooks_on_member_add_method: + :param webhooks_on_member_remove_url: + :param webhooks_on_member_remove_method: + :param webhooks_on_message_sent_url: + :param webhooks_on_message_sent_method: + :param webhooks_on_message_updated_url: + :param webhooks_on_message_updated_method: + :param webhooks_on_message_removed_url: + :param webhooks_on_message_removed_method: + :param webhooks_on_channel_added_url: + :param webhooks_on_channel_added_method: + :param webhooks_on_channel_destroyed_url: + :param webhooks_on_channel_destroyed_method: + :param webhooks_on_channel_updated_url: + :param webhooks_on_channel_updated_method: + :param webhooks_on_member_added_url: + :param webhooks_on_member_added_method: + :param webhooks_on_member_removed_url: + :param webhooks_on_member_removed_method: + :param limits_channel_members: + :param limits_user_channels: + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + webhooks_on_message_send_url=webhooks_on_message_send_url, + webhooks_on_message_send_method=webhooks_on_message_send_method, + webhooks_on_message_update_url=webhooks_on_message_update_url, + webhooks_on_message_update_method=webhooks_on_message_update_method, + webhooks_on_message_remove_url=webhooks_on_message_remove_url, + webhooks_on_message_remove_method=webhooks_on_message_remove_method, + webhooks_on_channel_add_url=webhooks_on_channel_add_url, + webhooks_on_channel_add_method=webhooks_on_channel_add_method, + webhooks_on_channel_destroy_url=webhooks_on_channel_destroy_url, + webhooks_on_channel_destroy_method=webhooks_on_channel_destroy_method, + webhooks_on_channel_update_url=webhooks_on_channel_update_url, + webhooks_on_channel_update_method=webhooks_on_channel_update_method, + webhooks_on_member_add_url=webhooks_on_member_add_url, + webhooks_on_member_add_method=webhooks_on_member_add_method, + webhooks_on_member_remove_url=webhooks_on_member_remove_url, + webhooks_on_member_remove_method=webhooks_on_member_remove_method, + webhooks_on_message_sent_url=webhooks_on_message_sent_url, + webhooks_on_message_sent_method=webhooks_on_message_sent_method, + webhooks_on_message_updated_url=webhooks_on_message_updated_url, + webhooks_on_message_updated_method=webhooks_on_message_updated_method, + webhooks_on_message_removed_url=webhooks_on_message_removed_url, + webhooks_on_message_removed_method=webhooks_on_message_removed_method, + webhooks_on_channel_added_url=webhooks_on_channel_added_url, + webhooks_on_channel_added_method=webhooks_on_channel_added_method, + webhooks_on_channel_destroyed_url=webhooks_on_channel_destroyed_url, + webhooks_on_channel_destroyed_method=webhooks_on_channel_destroyed_method, + webhooks_on_channel_updated_url=webhooks_on_channel_updated_url, + webhooks_on_channel_updated_method=webhooks_on_channel_updated_method, + webhooks_on_member_added_url=webhooks_on_member_added_url, + webhooks_on_member_added_method=webhooks_on_member_added_method, + webhooks_on_member_removed_url=webhooks_on_member_removed_url, + webhooks_on_member_removed_method=webhooks_on_member_removed_method, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + ) + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + return self._proxy.channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + return self._proxy.users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V1.ServiceInstance {}>".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._channels: Optional[ChannelList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param webhooks_on_message_send_url: + :param webhooks_on_message_send_method: + :param webhooks_on_message_update_url: + :param webhooks_on_message_update_method: + :param webhooks_on_message_remove_url: + :param webhooks_on_message_remove_method: + :param webhooks_on_channel_add_url: + :param webhooks_on_channel_add_method: + :param webhooks_on_channel_destroy_url: + :param webhooks_on_channel_destroy_method: + :param webhooks_on_channel_update_url: + :param webhooks_on_channel_update_method: + :param webhooks_on_member_add_url: + :param webhooks_on_member_add_method: + :param webhooks_on_member_remove_url: + :param webhooks_on_member_remove_method: + :param webhooks_on_message_sent_url: + :param webhooks_on_message_sent_method: + :param webhooks_on_message_updated_url: + :param webhooks_on_message_updated_method: + :param webhooks_on_message_removed_url: + :param webhooks_on_message_removed_method: + :param webhooks_on_channel_added_url: + :param webhooks_on_channel_added_method: + :param webhooks_on_channel_destroyed_url: + :param webhooks_on_channel_destroyed_method: + :param webhooks_on_channel_updated_url: + :param webhooks_on_channel_updated_method: + :param webhooks_on_member_added_url: + :param webhooks_on_member_added_method: + :param webhooks_on_member_removed_url: + :param webhooks_on_member_removed_method: + :param limits_channel_members: + :param limits_user_channels: + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, + "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, + "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, + "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, + "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, + "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, + "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, + "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, + "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, + "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, + "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, + "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, + "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, + "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, + "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, + "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, + "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, + "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, + "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, + "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, + "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, + "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, + "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, + "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, + "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, + "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, + "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, + "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, + "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, + "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, + "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, + "Webhooks.OnMemberRemoved.Method": webhooks_on_member_removed_method, + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + webhooks_on_message_send_url: Union[str, object] = values.unset, + webhooks_on_message_send_method: Union[str, object] = values.unset, + webhooks_on_message_update_url: Union[str, object] = values.unset, + webhooks_on_message_update_method: Union[str, object] = values.unset, + webhooks_on_message_remove_url: Union[str, object] = values.unset, + webhooks_on_message_remove_method: Union[str, object] = values.unset, + webhooks_on_channel_add_url: Union[str, object] = values.unset, + webhooks_on_channel_add_method: Union[str, object] = values.unset, + webhooks_on_channel_destroy_url: Union[str, object] = values.unset, + webhooks_on_channel_destroy_method: Union[str, object] = values.unset, + webhooks_on_channel_update_url: Union[str, object] = values.unset, + webhooks_on_channel_update_method: Union[str, object] = values.unset, + webhooks_on_member_add_url: Union[str, object] = values.unset, + webhooks_on_member_add_method: Union[str, object] = values.unset, + webhooks_on_member_remove_url: Union[str, object] = values.unset, + webhooks_on_member_remove_method: Union[str, object] = values.unset, + webhooks_on_message_sent_url: Union[str, object] = values.unset, + webhooks_on_message_sent_method: Union[str, object] = values.unset, + webhooks_on_message_updated_url: Union[str, object] = values.unset, + webhooks_on_message_updated_method: Union[str, object] = values.unset, + webhooks_on_message_removed_url: Union[str, object] = values.unset, + webhooks_on_message_removed_method: Union[str, object] = values.unset, + webhooks_on_channel_added_url: Union[str, object] = values.unset, + webhooks_on_channel_added_method: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_url: Union[str, object] = values.unset, + webhooks_on_channel_destroyed_method: Union[str, object] = values.unset, + webhooks_on_channel_updated_url: Union[str, object] = values.unset, + webhooks_on_channel_updated_method: Union[str, object] = values.unset, + webhooks_on_member_added_url: Union[str, object] = values.unset, + webhooks_on_member_added_method: Union[str, object] = values.unset, + webhooks_on_member_removed_url: Union[str, object] = values.unset, + webhooks_on_member_removed_method: Union[str, object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param webhooks_on_message_send_url: + :param webhooks_on_message_send_method: + :param webhooks_on_message_update_url: + :param webhooks_on_message_update_method: + :param webhooks_on_message_remove_url: + :param webhooks_on_message_remove_method: + :param webhooks_on_channel_add_url: + :param webhooks_on_channel_add_method: + :param webhooks_on_channel_destroy_url: + :param webhooks_on_channel_destroy_method: + :param webhooks_on_channel_update_url: + :param webhooks_on_channel_update_method: + :param webhooks_on_member_add_url: + :param webhooks_on_member_add_method: + :param webhooks_on_member_remove_url: + :param webhooks_on_member_remove_method: + :param webhooks_on_message_sent_url: + :param webhooks_on_message_sent_method: + :param webhooks_on_message_updated_url: + :param webhooks_on_message_updated_method: + :param webhooks_on_message_removed_url: + :param webhooks_on_message_removed_method: + :param webhooks_on_channel_added_url: + :param webhooks_on_channel_added_method: + :param webhooks_on_channel_destroyed_url: + :param webhooks_on_channel_destroyed_method: + :param webhooks_on_channel_updated_url: + :param webhooks_on_channel_updated_method: + :param webhooks_on_member_added_url: + :param webhooks_on_member_added_method: + :param webhooks_on_member_removed_url: + :param webhooks_on_member_removed_method: + :param limits_channel_members: + :param limits_user_channels: + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Webhooks.OnMessageSend.Url": webhooks_on_message_send_url, + "Webhooks.OnMessageSend.Method": webhooks_on_message_send_method, + "Webhooks.OnMessageUpdate.Url": webhooks_on_message_update_url, + "Webhooks.OnMessageUpdate.Method": webhooks_on_message_update_method, + "Webhooks.OnMessageRemove.Url": webhooks_on_message_remove_url, + "Webhooks.OnMessageRemove.Method": webhooks_on_message_remove_method, + "Webhooks.OnChannelAdd.Url": webhooks_on_channel_add_url, + "Webhooks.OnChannelAdd.Method": webhooks_on_channel_add_method, + "Webhooks.OnChannelDestroy.Url": webhooks_on_channel_destroy_url, + "Webhooks.OnChannelDestroy.Method": webhooks_on_channel_destroy_method, + "Webhooks.OnChannelUpdate.Url": webhooks_on_channel_update_url, + "Webhooks.OnChannelUpdate.Method": webhooks_on_channel_update_method, + "Webhooks.OnMemberAdd.Url": webhooks_on_member_add_url, + "Webhooks.OnMemberAdd.Method": webhooks_on_member_add_method, + "Webhooks.OnMemberRemove.Url": webhooks_on_member_remove_url, + "Webhooks.OnMemberRemove.Method": webhooks_on_member_remove_method, + "Webhooks.OnMessageSent.Url": webhooks_on_message_sent_url, + "Webhooks.OnMessageSent.Method": webhooks_on_message_sent_method, + "Webhooks.OnMessageUpdated.Url": webhooks_on_message_updated_url, + "Webhooks.OnMessageUpdated.Method": webhooks_on_message_updated_method, + "Webhooks.OnMessageRemoved.Url": webhooks_on_message_removed_url, + "Webhooks.OnMessageRemoved.Method": webhooks_on_message_removed_method, + "Webhooks.OnChannelAdded.Url": webhooks_on_channel_added_url, + "Webhooks.OnChannelAdded.Method": webhooks_on_channel_added_method, + "Webhooks.OnChannelDestroyed.Url": webhooks_on_channel_destroyed_url, + "Webhooks.OnChannelDestroyed.Method": webhooks_on_channel_destroyed_method, + "Webhooks.OnChannelUpdated.Url": webhooks_on_channel_updated_url, + "Webhooks.OnChannelUpdated.Method": webhooks_on_channel_updated_method, + "Webhooks.OnMemberAdded.Url": webhooks_on_member_added_url, + "Webhooks.OnMemberAdded.Method": webhooks_on_member_added_method, + "Webhooks.OnMemberRemoved.Url": webhooks_on_member_removed_url, + "Webhooks.OnMemberRemoved.Method": webhooks_on_member_removed_method, + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + if self._channels is None: + self._channels = ChannelList( + self._version, + self._solution["sid"], + ) + return self._channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + if self._roles is None: + self._roles = RoleList( + self._version, + self._solution["sid"], + ) + return self._roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + if self._users is None: + self._users = UserList( + self._version, + self._solution["sid"], + ) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V1.ServiceContext {}>".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V1.ServicePage>" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create(self, friendly_name: str) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async(self, friendly_name: str) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V1.ServiceList>" diff --git a/twilio/rest/ip_messaging/v1/service/channel/__init__.py b/twilio/rest/ip_messaging/v1/service/channel/__init__.py new file mode 100644 index 0000000000..14423c9e38 --- /dev/null +++ b/twilio/rest/ip_messaging/v1/service/channel/__init__.py @@ -0,0 +1,790 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.ip_messaging.v1.service.channel.invite import InviteList +from twilio.rest.ip_messaging.v1.service.channel.member import MemberList +from twilio.rest.ip_messaging.v1.service.channel.message import MessageList + + +class ChannelInstance(InstanceResource): + + class ChannelType(object): + PUBLIC = "public" + PRIVATE = "private" + + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar friendly_name: + :ivar unique_name: + :ivar attributes: + :ivar type: + :ivar date_created: + :ivar date_updated: + :ivar created_by: + :ivar members_count: + :ivar messages_count: + :ivar url: + :ivar links: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.type: Optional["ChannelInstance.ChannelType"] = payload.get("type") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + self.members_count: Optional[int] = deserialize.integer( + payload.get("members_count") + ) + self.messages_count: Optional[int] = deserialize.integer( + payload.get("messages_count") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None + + @property + def _proxy(self) -> "ChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ChannelContext for this ChannelInstance + """ + if self._context is None: + self._context = ChannelContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ChannelInstance": + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ChannelInstance": + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Update the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + + :returns: The updated ChannelInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Asynchronous coroutine to update the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + + :returns: The updated ChannelInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + ) + + @property + def invites(self) -> InviteList: + """ + Access the invites + """ + return self._proxy.invites + + @property + def members(self) -> MemberList: + """ + Access the members + """ + return self._proxy.members + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V1.ChannelInstance {}>".format(context) + + +class ChannelContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the ChannelContext + + :param version: Version that contains the resource + :param service_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Channels/{sid}".format(**self._solution) + + self._invites: Optional[InviteList] = None + self._members: Optional[MemberList] = None + self._messages: Optional[MessageList] = None + + def delete(self) -> bool: + """ + Deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelInstance: + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ChannelInstance: + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Update the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronous coroutine to update the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def invites(self) -> InviteList: + """ + Access the invites + """ + if self._invites is None: + self._invites = InviteList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._invites + + @property + def members(self) -> MemberList: + """ + Access the members + """ + if self._members is None: + self._members = MemberList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._members + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._messages + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V1.ChannelContext {}>".format(context) + + +class ChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: + """ + Build an instance of ChannelInstance + + :param payload: Payload response from the API + """ + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V1.ChannelPage>" + + +class ChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ChannelList + + :param version: Version that contains the resource + :param service_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Channels".format(**self._solution) + + def create( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> ChannelInstance: + """ + Create the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + + :returns: The created ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "Type": type, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronously create the ChannelInstance + + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + + :returns: The created ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "Type": type, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelInstance]: + """ + Streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(type=type, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChannelInstance]: + """ + Asynchronously streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(type=type, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + type=type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Asynchronously lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + type=type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) + + async def page_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Asynchronously retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ChannelPage: + """ + Retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ChannelPage: + """ + Asynchronously retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelPage(self._version, response, self._solution) + + def get(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: + """ + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: + """ + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V1.ChannelList>" diff --git a/twilio/rest/ip_messaging/v1/service/channel/invite.py b/twilio/rest/ip_messaging/v1/service/channel/invite.py new file mode 100644 index 0000000000..d348540346 --- /dev/null +++ b/twilio/rest/ip_messaging/v1/service/channel/invite.py @@ -0,0 +1,598 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InviteInstance(InstanceResource): + """ + :ivar sid: + :ivar account_sid: + :ivar channel_sid: + :ivar service_sid: + :ivar identity: + :ivar date_created: + :ivar date_updated: + :ivar role_sid: + :ivar created_by: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.created_by: Optional[str] = payload.get("created_by") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[InviteContext] = None + + @property + def _proxy(self) -> "InviteContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InviteContext for this InviteInstance + """ + if self._context is None: + self._context = InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "InviteInstance": + """ + Fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InviteInstance": + """ + Asynchronous coroutine to fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V1.InviteInstance {}>".format(context) + + +class InviteContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the InviteContext + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Invites/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> InviteInstance: + """ + Fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InviteInstance: + """ + Asynchronous coroutine to fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V1.InviteContext {}>".format(context) + + +class InvitePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: + """ + Build an instance of InviteInstance + + :param payload: Payload response from the API + """ + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V1.InvitePage>" + + +class InviteList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the InviteList + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Invites".format( + **self._solution + ) + + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Create the InviteInstance + + :param identity: + :param role_sid: + + :returns: The created InviteInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Asynchronously create the InviteInstance + + :param identity: + :param role_sid: + + :returns: The created InviteInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InviteInstance]: + """ + Streams InviteInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InviteInstance]: + """ + Asynchronously streams InviteInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: + """ + Lists InviteInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: + """ + Asynchronously lists InviteInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InvitePage: + """ + Retrieve a single page of InviteInstance records from the API. + Request is executed immediately + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InviteInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InvitePage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InvitePage: + """ + Asynchronously retrieve a single page of InviteInstance records from the API. + Request is executed immediately + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InviteInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InvitePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> InvitePage: + """ + Retrieve a specific page of InviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InviteInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InvitePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> InvitePage: + """ + Asynchronously retrieve a specific page of InviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InviteInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InvitePage(self._version, response, self._solution) + + def get(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V1.InviteList>" diff --git a/twilio/rest/ip_messaging/v1/service/channel/member.py b/twilio/rest/ip_messaging/v1/service/channel/member.py new file mode 100644 index 0000000000..26a68650ef --- /dev/null +++ b/twilio/rest/ip_messaging/v1/service/channel/member.py @@ -0,0 +1,716 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MemberInstance(InstanceResource): + """ + :ivar sid: + :ivar account_sid: + :ivar channel_sid: + :ivar service_sid: + :ivar identity: + :ivar date_created: + :ivar date_updated: + :ivar role_sid: + :ivar last_consumed_message_index: + :ivar last_consumption_timestamp: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.last_consumption_timestamp: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("last_consumption_timestamp")) + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[MemberContext] = None + + @property + def _proxy(self) -> "MemberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MemberContext for this MemberInstance + """ + if self._context is None: + self._context = MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the MemberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "MemberInstance": + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MemberInstance": + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> "MemberInstance": + """ + Update the MemberInstance + + :param role_sid: + :param last_consumed_message_index: + + :returns: The updated MemberInstance + """ + return self._proxy.update( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) + + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> "MemberInstance": + """ + Asynchronous coroutine to update the MemberInstance + + :param role_sid: + :param last_consumed_message_index: + + :returns: The updated MemberInstance + """ + return await self._proxy.update_async( + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V1.MemberInstance {}>".format(context) + + +class MemberContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the MemberContext + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Members/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the MemberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MemberInstance: + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> MemberInstance: + """ + Update the MemberInstance + + :param role_sid: + :param last_consumed_message_index: + + :returns: The updated MemberInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + ) -> MemberInstance: + """ + Asynchronous coroutine to update the MemberInstance + + :param role_sid: + :param last_consumed_message_index: + + :returns: The updated MemberInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V1.MemberContext {}>".format(context) + + +class MemberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: + """ + Build an instance of MemberInstance + + :param payload: Payload response from the API + """ + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V1.MemberPage>" + + +class MemberList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MemberList + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Members".format( + **self._solution + ) + + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> MemberInstance: + """ + Create the MemberInstance + + :param identity: + :param role_sid: + + :returns: The created MemberInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> MemberInstance: + """ + Asynchronously create the MemberInstance + + :param identity: + :param role_sid: + + :returns: The created MemberInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MemberInstance]: + """ + Streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MemberInstance]: + """ + Asynchronously streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Asynchronously lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Asynchronously retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MemberPage: + """ + Retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MemberPage: + """ + Asynchronously retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MemberPage(self._version, response, self._solution) + + def get(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param sid: + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param sid: + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V1.MemberList>" diff --git a/twilio/rest/ip_messaging/v1/service/channel/message.py b/twilio/rest/ip_messaging/v1/service/channel/message.py new file mode 100644 index 0000000000..ad7c05d8a1 --- /dev/null +++ b/twilio/rest/ip_messaging/v1/service/channel/message.py @@ -0,0 +1,731 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MessageInstance(InstanceResource): + + class OrderType(object): + ASC = "asc" + DESC = "desc" + + """ + :ivar sid: + :ivar account_sid: + :ivar attributes: + :ivar service_sid: + :ivar to: + :ivar channel_sid: + :ivar date_created: + :ivar date_updated: + :ivar was_edited: + :ivar _from: + :ivar body: + :ivar index: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.service_sid: Optional[str] = payload.get("service_sid") + self.to: Optional[str] = payload.get("to") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.was_edited: Optional[bool] = payload.get("was_edited") + self._from: Optional[str] = payload.get("from") + self.body: Optional[str] = payload.get("body") + self.index: Optional[int] = deserialize.integer(payload.get("index")) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[MessageContext] = None + + @property + def _proxy(self) -> "MessageContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Update the MessageInstance + + :param body: + :param attributes: + + :returns: The updated MessageInstance + """ + return self._proxy.update( + body=body, + attributes=attributes, + ) + + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Asynchronous coroutine to update the MessageInstance + + :param body: + :param attributes: + + :returns: The updated MessageInstance + """ + return await self._proxy.update_async( + body=body, + attributes=attributes, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V1.MessageInstance {}>".format(context) + + +class MessageContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the MessageContext + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Messages/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Update the MessageInstance + + :param body: + :param attributes: + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param body: + :param attributes: + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V1.MessageContext {}>".format(context) + + +class MessagePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance + + :param payload: Payload response from the API + """ + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V1.MessagePage>" + + +class MessageList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Messages".format( + **self._solution + ) + + def create( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param body: + :param from_: + :param attributes: + + :returns: The created MessageInstance + """ + + data = values.of( + { + "Body": body, + "From": from_, + "Attributes": attributes, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, + body: str, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param body: + :param from_: + :param attributes: + + :returns: The created MessageInstance + """ + + data = values.of( + { + "Body": body, + "From": from_, + "Attributes": attributes, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: + """ + Streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(order=order, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInstance]: + """ + Asynchronously streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(order=order, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + order=order, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Asynchronously lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + order=order, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + async def page_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MessagePage: + """ + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MessagePage: + """ + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) + + def get(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V1.MessageList>" diff --git a/twilio/rest/ip_messaging/v1/service/role.py b/twilio/rest/ip_messaging/v1/service/role.py new file mode 100644 index 0000000000..d5d0628032 --- /dev/null +++ b/twilio/rest/ip_messaging/v1/service/role.py @@ -0,0 +1,645 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RoleInstance(InstanceResource): + + class RoleType(object): + CHANNEL = "channel" + DEPLOYMENT = "deployment" + + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar friendly_name: + :ivar type: + :ivar permissions: + :ivar date_created: + :ivar date_updated: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["RoleInstance.RoleType"] = payload.get("type") + self.permissions: Optional[List[str]] = payload.get("permissions") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[RoleContext] = None + + @property + def _proxy(self) -> "RoleContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoleContext for this RoleInstance + """ + if self._context is None: + self._context = RoleContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RoleInstance": + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RoleInstance": + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return await self._proxy.fetch_async() + + def update(self, permission: List[str]) -> "RoleInstance": + """ + Update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + return self._proxy.update( + permission=permission, + ) + + async def update_async(self, permission: List[str]) -> "RoleInstance": + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + return await self._proxy.update_async( + permission=permission, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V1.RoleInstance {}>".format(context) + + +class RoleContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the RoleContext + + :param version: Version that contains the resource + :param service_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Roles/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update(self, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V1.RoleContext {}>".format(context) + + +class RolePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: + """ + Build an instance of RoleInstance + + :param payload: Payload response from the API + """ + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V1.RolePage>" + + +class RoleList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the RoleList + + :param version: Version that contains the resource + :param service_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Roles".format(**self._solution) + + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoleInstance]: + """ + Streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoleInstance]: + """ + Asynchronously streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Asynchronously lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Asynchronously retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RolePage: + """ + Retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RolePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RolePage: + """ + Asynchronously retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RolePage(self._version, response, self._solution) + + def get(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V1.RoleList>" diff --git a/twilio/rest/ip_messaging/v1/service/user/__init__.py b/twilio/rest/ip_messaging/v1/service/user/__init__.py new file mode 100644 index 0000000000..5f37f2d3aa --- /dev/null +++ b/twilio/rest/ip_messaging/v1/service/user/__init__.py @@ -0,0 +1,723 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.ip_messaging.v1.service.user.user_channel import UserChannelList + + +class UserInstance(InstanceResource): + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar attributes: + :ivar friendly_name: + :ivar role_sid: + :ivar identity: + :ivar is_online: + :ivar is_notifiable: + :ivar date_created: + :ivar date_updated: + :ivar joined_channels_count: + :ivar links: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.role_sid: Optional[str] = payload.get("role_sid") + self.identity: Optional[str] = payload.get("identity") + self.is_online: Optional[bool] = payload.get("is_online") + self.is_notifiable: Optional[bool] = payload.get("is_notifiable") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.joined_channels_count: Optional[int] = deserialize.integer( + payload.get("joined_channels_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserContext] = None + + @property + def _proxy(self) -> "UserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Update the UserInstance + + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + return self._proxy.update( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + return await self._proxy.update_async( + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + @property + def user_channels(self) -> UserChannelList: + """ + Access the user_channels + """ + return self._proxy.user_channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V1.UserInstance {}>".format(context) + + +class UserContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the UserContext + + :param version: Version that contains the resource + :param service_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Users/{sid}".format(**self._solution) + + self._user_channels: Optional[UserChannelList] = None + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Update the UserInstance + + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def user_channels(self) -> UserChannelList: + """ + Access the user_channels + """ + if self._user_channels is None: + self._user_channels = UserChannelList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._user_channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V1.UserContext {}>".format(context) + + +class UserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance + + :param payload: Payload response from the API + """ + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V1.UserPage>" + + +class UserList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the UserList + + :param version: Version that contains the resource + :param service_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Users".format(**self._solution) + + def create( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Create the UserInstance + + :param identity: + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + identity: str, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserInstance]: + """ + Streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserInstance]: + """ + Asynchronously streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Asynchronously lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserPage: + """ + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserPage: + """ + Asynchronously retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserPage(self._version, response, self._solution) + + def get(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: + """ + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: + """ + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V1.UserList>" diff --git a/twilio/rest/ip_messaging/v1/service/user/user_channel.py b/twilio/rest/ip_messaging/v1/service/user/user_channel.py new file mode 100644 index 0000000000..4245449869 --- /dev/null +++ b/twilio/rest/ip_messaging/v1/service/user/user_channel.py @@ -0,0 +1,322 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UserChannelInstance(InstanceResource): + + class ChannelStatus(object): + JOINED = "joined" + INVITED = "invited" + NOT_PARTICIPATING = "not_participating" + + """ + :ivar account_sid: + :ivar service_sid: + :ivar channel_sid: + :ivar member_sid: + :ivar status: + :ivar last_consumed_message_index: + :ivar unread_messages_count: + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], service_sid: str, user_sid: str + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.member_sid: Optional[str] = payload.get("member_sid") + self.status: Optional["UserChannelInstance.ChannelStatus"] = payload.get( + "status" + ) + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.unread_messages_count: Optional[int] = deserialize.integer( + payload.get("unread_messages_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V1.UserChannelInstance {}>".format(context) + + +class UserChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: + """ + Build an instance of UserChannelInstance + + :param payload: Payload response from the API + """ + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V1.UserChannelPage>" + + +class UserChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str, user_sid: str): + """ + Initialize the UserChannelList + + :param version: Version that contains the resource + :param service_sid: + :param user_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Channels".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserChannelInstance]: + """ + Streams UserChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserChannelInstance]: + """ + Asynchronously streams UserChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: + """ + Lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: + """ + Asynchronously lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserChannelPage: + """ + Retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserChannelPage: + """ + Asynchronously retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserChannelPage: + """ + Retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserChannelPage: + """ + Asynchronously retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserChannelPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V1.UserChannelList>" diff --git a/twilio/rest/ip_messaging/v2/__init__.py b/twilio/rest/ip_messaging/v2/__init__.py new file mode 100644 index 0000000000..6003c86b12 --- /dev/null +++ b/twilio/rest/ip_messaging/v2/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.ip_messaging.v2.credential import CredentialList +from twilio.rest.ip_messaging.v2.service import ServiceList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of IpMessaging + + :param domain: The Twilio.ip_messaging domain + """ + super().__init__(domain, "v2") + self._credentials: Optional[CredentialList] = None + self._services: Optional[ServiceList] = None + + @property + def credentials(self) -> CredentialList: + if self._credentials is None: + self._credentials = CredentialList(self) + return self._credentials + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2>" diff --git a/twilio/rest/ip_messaging/v2/credential.py b/twilio/rest/ip_messaging/v2/credential.py new file mode 100644 index 0000000000..065c5048e9 --- /dev/null +++ b/twilio/rest/ip_messaging/v2/credential.py @@ -0,0 +1,711 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CredentialInstance(InstanceResource): + + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: + :ivar account_sid: + :ivar friendly_name: + :ivar type: + :ivar sandbox: + :ivar date_created: + :ivar date_updated: + :ivar url: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushService"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None + + @property + def _proxy(self) -> "CredentialContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CredentialInstance": + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialInstance": + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Update the CredentialInstance + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.CredentialInstance {}>".format(context) + + +class CredentialContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CredentialContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Update the CredentialInstance + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.CredentialContext {}>".format(context) + + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance + + :param payload: Payload response from the API + """ + return CredentialInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.CredentialPage>" + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Credentials" + + def create( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Create the CredentialInstance + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + async def create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: + :param certificate: + :param private_key: + :param sandbox: + :param api_key: + :param secret: + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialInstance]: + """ + Streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: + """ + Asynchronously streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Asynchronously lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Asynchronously retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + def get_page(self, target_url: str) -> CredentialPage: + """ + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CredentialPage: + """ + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) + + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: + """ + return CredentialContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: + """ + return CredentialContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.CredentialList>" diff --git a/twilio/rest/ip_messaging/v2/service/__init__.py b/twilio/rest/ip_messaging/v2/service/__init__.py new file mode 100644 index 0000000000..a303f10f33 --- /dev/null +++ b/twilio/rest/ip_messaging/v2/service/__init__.py @@ -0,0 +1,1128 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.ip_messaging.v2.service.binding import BindingList +from twilio.rest.ip_messaging.v2.service.channel import ChannelList +from twilio.rest.ip_messaging.v2.service.role import RoleList +from twilio.rest.ip_messaging.v2.service.user import UserList + + +class ServiceInstance(InstanceResource): + """ + :ivar sid: + :ivar account_sid: + :ivar friendly_name: + :ivar date_created: + :ivar date_updated: + :ivar default_service_role_sid: + :ivar default_channel_role_sid: + :ivar default_channel_creator_role_sid: + :ivar read_status_enabled: + :ivar reachability_enabled: + :ivar typing_indicator_timeout: + :ivar consumption_report_interval: + :ivar limits: + :ivar pre_webhook_url: + :ivar post_webhook_url: + :ivar webhook_method: + :ivar webhook_filters: + :ivar pre_webhook_retry_count: + :ivar post_webhook_retry_count: + :ivar notifications: + :ivar media: + :ivar url: + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.default_service_role_sid: Optional[str] = payload.get( + "default_service_role_sid" + ) + self.default_channel_role_sid: Optional[str] = payload.get( + "default_channel_role_sid" + ) + self.default_channel_creator_role_sid: Optional[str] = payload.get( + "default_channel_creator_role_sid" + ) + self.read_status_enabled: Optional[bool] = payload.get("read_status_enabled") + self.reachability_enabled: Optional[bool] = payload.get("reachability_enabled") + self.typing_indicator_timeout: Optional[int] = deserialize.integer( + payload.get("typing_indicator_timeout") + ) + self.consumption_report_interval: Optional[int] = deserialize.integer( + payload.get("consumption_report_interval") + ) + self.limits: Optional[Dict[str, object]] = payload.get("limits") + self.pre_webhook_url: Optional[str] = payload.get("pre_webhook_url") + self.post_webhook_url: Optional[str] = payload.get("post_webhook_url") + self.webhook_method: Optional[str] = payload.get("webhook_method") + self.webhook_filters: Optional[List[str]] = payload.get("webhook_filters") + self.pre_webhook_retry_count: Optional[int] = deserialize.integer( + payload.get("pre_webhook_retry_count") + ) + self.post_webhook_retry_count: Optional[int] = deserialize.integer( + payload.get("post_webhook_retry_count") + ) + self.notifications: Optional[Dict[str, object]] = payload.get("notifications") + self.media: Optional[Dict[str, object]] = payload.get("media") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_new_message_sound: + :param notifications_new_message_badge_count_enabled: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_added_to_channel_sound: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_removed_from_channel_sound: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param notifications_invited_to_channel_sound: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param limits_channel_members: + :param limits_user_channels: + :param media_compatibility_message: + :param pre_webhook_retry_count: + :param post_webhook_retry_count: + :param notifications_log_enabled: + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_new_message_sound: + :param notifications_new_message_badge_count_enabled: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_added_to_channel_sound: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_removed_from_channel_sound: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param notifications_invited_to_channel_sound: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param limits_channel_members: + :param limits_user_channels: + :param media_compatibility_message: + :param pre_webhook_retry_count: + :param post_webhook_retry_count: + :param notifications_log_enabled: + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + default_service_role_sid=default_service_role_sid, + default_channel_role_sid=default_channel_role_sid, + default_channel_creator_role_sid=default_channel_creator_role_sid, + read_status_enabled=read_status_enabled, + reachability_enabled=reachability_enabled, + typing_indicator_timeout=typing_indicator_timeout, + consumption_report_interval=consumption_report_interval, + notifications_new_message_enabled=notifications_new_message_enabled, + notifications_new_message_template=notifications_new_message_template, + notifications_new_message_sound=notifications_new_message_sound, + notifications_new_message_badge_count_enabled=notifications_new_message_badge_count_enabled, + notifications_added_to_channel_enabled=notifications_added_to_channel_enabled, + notifications_added_to_channel_template=notifications_added_to_channel_template, + notifications_added_to_channel_sound=notifications_added_to_channel_sound, + notifications_removed_from_channel_enabled=notifications_removed_from_channel_enabled, + notifications_removed_from_channel_template=notifications_removed_from_channel_template, + notifications_removed_from_channel_sound=notifications_removed_from_channel_sound, + notifications_invited_to_channel_enabled=notifications_invited_to_channel_enabled, + notifications_invited_to_channel_template=notifications_invited_to_channel_template, + notifications_invited_to_channel_sound=notifications_invited_to_channel_sound, + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + webhook_method=webhook_method, + webhook_filters=webhook_filters, + limits_channel_members=limits_channel_members, + limits_user_channels=limits_user_channels, + media_compatibility_message=media_compatibility_message, + pre_webhook_retry_count=pre_webhook_retry_count, + post_webhook_retry_count=post_webhook_retry_count, + notifications_log_enabled=notifications_log_enabled, + ) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + return self._proxy.bindings + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + return self._proxy.channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + return self._proxy.roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + return self._proxy.users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.ServiceInstance {}>".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._bindings: Optional[BindingList] = None + self._channels: Optional[ChannelList] = None + self._roles: Optional[RoleList] = None + self._users: Optional[UserList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_new_message_sound: + :param notifications_new_message_badge_count_enabled: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_added_to_channel_sound: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_removed_from_channel_sound: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param notifications_invited_to_channel_sound: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param limits_channel_members: + :param limits_user_channels: + :param media_compatibility_message: + :param pre_webhook_retry_count: + :param post_webhook_retry_count: + :param notifications_log_enabled: + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.NewMessage.Sound": notifications_new_message_sound, + "Notifications.NewMessage.BadgeCountEnabled": serialize.boolean_to_string( + notifications_new_message_badge_count_enabled + ), + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.AddedToChannel.Sound": notifications_added_to_channel_sound, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.RemovedFromChannel.Sound": notifications_removed_from_channel_sound, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "Notifications.InvitedToChannel.Sound": notifications_invited_to_channel_sound, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + "Media.CompatibilityMessage": media_compatibility_message, + "PreWebhookRetryCount": pre_webhook_retry_count, + "PostWebhookRetryCount": post_webhook_retry_count, + "Notifications.LogEnabled": serialize.boolean_to_string( + notifications_log_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + default_service_role_sid: Union[str, object] = values.unset, + default_channel_role_sid: Union[str, object] = values.unset, + default_channel_creator_role_sid: Union[str, object] = values.unset, + read_status_enabled: Union[bool, object] = values.unset, + reachability_enabled: Union[bool, object] = values.unset, + typing_indicator_timeout: Union[int, object] = values.unset, + consumption_report_interval: Union[int, object] = values.unset, + notifications_new_message_enabled: Union[bool, object] = values.unset, + notifications_new_message_template: Union[str, object] = values.unset, + notifications_new_message_sound: Union[str, object] = values.unset, + notifications_new_message_badge_count_enabled: Union[ + bool, object + ] = values.unset, + notifications_added_to_channel_enabled: Union[bool, object] = values.unset, + notifications_added_to_channel_template: Union[str, object] = values.unset, + notifications_added_to_channel_sound: Union[str, object] = values.unset, + notifications_removed_from_channel_enabled: Union[bool, object] = values.unset, + notifications_removed_from_channel_template: Union[str, object] = values.unset, + notifications_removed_from_channel_sound: Union[str, object] = values.unset, + notifications_invited_to_channel_enabled: Union[bool, object] = values.unset, + notifications_invited_to_channel_template: Union[str, object] = values.unset, + notifications_invited_to_channel_sound: Union[str, object] = values.unset, + pre_webhook_url: Union[str, object] = values.unset, + post_webhook_url: Union[str, object] = values.unset, + webhook_method: Union[str, object] = values.unset, + webhook_filters: Union[List[str], object] = values.unset, + limits_channel_members: Union[int, object] = values.unset, + limits_user_channels: Union[int, object] = values.unset, + media_compatibility_message: Union[str, object] = values.unset, + pre_webhook_retry_count: Union[int, object] = values.unset, + post_webhook_retry_count: Union[int, object] = values.unset, + notifications_log_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: + :param default_service_role_sid: + :param default_channel_role_sid: + :param default_channel_creator_role_sid: + :param read_status_enabled: + :param reachability_enabled: + :param typing_indicator_timeout: + :param consumption_report_interval: + :param notifications_new_message_enabled: + :param notifications_new_message_template: + :param notifications_new_message_sound: + :param notifications_new_message_badge_count_enabled: + :param notifications_added_to_channel_enabled: + :param notifications_added_to_channel_template: + :param notifications_added_to_channel_sound: + :param notifications_removed_from_channel_enabled: + :param notifications_removed_from_channel_template: + :param notifications_removed_from_channel_sound: + :param notifications_invited_to_channel_enabled: + :param notifications_invited_to_channel_template: + :param notifications_invited_to_channel_sound: + :param pre_webhook_url: + :param post_webhook_url: + :param webhook_method: + :param webhook_filters: + :param limits_channel_members: + :param limits_user_channels: + :param media_compatibility_message: + :param pre_webhook_retry_count: + :param post_webhook_retry_count: + :param notifications_log_enabled: + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DefaultServiceRoleSid": default_service_role_sid, + "DefaultChannelRoleSid": default_channel_role_sid, + "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, + "ReadStatusEnabled": serialize.boolean_to_string(read_status_enabled), + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), + "TypingIndicatorTimeout": typing_indicator_timeout, + "ConsumptionReportInterval": consumption_report_interval, + "Notifications.NewMessage.Enabled": serialize.boolean_to_string( + notifications_new_message_enabled + ), + "Notifications.NewMessage.Template": notifications_new_message_template, + "Notifications.NewMessage.Sound": notifications_new_message_sound, + "Notifications.NewMessage.BadgeCountEnabled": serialize.boolean_to_string( + notifications_new_message_badge_count_enabled + ), + "Notifications.AddedToChannel.Enabled": serialize.boolean_to_string( + notifications_added_to_channel_enabled + ), + "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, + "Notifications.AddedToChannel.Sound": notifications_added_to_channel_sound, + "Notifications.RemovedFromChannel.Enabled": serialize.boolean_to_string( + notifications_removed_from_channel_enabled + ), + "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, + "Notifications.RemovedFromChannel.Sound": notifications_removed_from_channel_sound, + "Notifications.InvitedToChannel.Enabled": serialize.boolean_to_string( + notifications_invited_to_channel_enabled + ), + "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, + "Notifications.InvitedToChannel.Sound": notifications_invited_to_channel_sound, + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "WebhookMethod": webhook_method, + "WebhookFilters": serialize.map(webhook_filters, lambda e: e), + "Limits.ChannelMembers": limits_channel_members, + "Limits.UserChannels": limits_user_channels, + "Media.CompatibilityMessage": media_compatibility_message, + "PreWebhookRetryCount": pre_webhook_retry_count, + "PostWebhookRetryCount": post_webhook_retry_count, + "Notifications.LogEnabled": serialize.boolean_to_string( + notifications_log_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + if self._bindings is None: + self._bindings = BindingList( + self._version, + self._solution["sid"], + ) + return self._bindings + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + if self._channels is None: + self._channels = ChannelList( + self._version, + self._solution["sid"], + ) + return self._channels + + @property + def roles(self) -> RoleList: + """ + Access the roles + """ + if self._roles is None: + self._roles = RoleList( + self._version, + self._solution["sid"], + ) + return self._roles + + @property + def users(self) -> UserList: + """ + Access the users + """ + if self._users is None: + self._users = UserList( + self._version, + self._solution["sid"], + ) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.ServiceContext {}>".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.ServicePage>" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create(self, friendly_name: str) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async(self, friendly_name: str) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.ServiceList>" diff --git a/twilio/rest/ip_messaging/v2/service/binding.py b/twilio/rest/ip_messaging/v2/service/binding.py new file mode 100644 index 0000000000..af9018af9f --- /dev/null +++ b/twilio/rest/ip_messaging/v2/service/binding.py @@ -0,0 +1,536 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class BindingInstance(InstanceResource): + + class BindingType(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar date_created: + :ivar date_updated: + :ivar endpoint: + :ivar identity: + :ivar credential_sid: + :ivar binding_type: + :ivar message_types: + :ivar url: + :ivar links: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.endpoint: Optional[str] = payload.get("endpoint") + self.identity: Optional[str] = payload.get("identity") + self.credential_sid: Optional[str] = payload.get("credential_sid") + self.binding_type: Optional["BindingInstance.BindingType"] = payload.get( + "binding_type" + ) + self.message_types: Optional[List[str]] = payload.get("message_types") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[BindingContext] = None + + @property + def _proxy(self) -> "BindingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BindingContext for this BindingInstance + """ + if self._context is None: + self._context = BindingContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "BindingInstance": + """ + Fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BindingInstance": + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.BindingInstance {}>".format(context) + + +class BindingContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the BindingContext + + :param version: Version that contains the resource + :param service_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Bindings/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> BindingInstance: + """ + Fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> BindingInstance: + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.BindingContext {}>".format(context) + + +class BindingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: + """ + Build an instance of BindingInstance + + :param payload: Payload response from the API + """ + return BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.BindingPage>" + + +class BindingList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the BindingList + + :param version: Version that contains the resource + :param service_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Bindings".format(**self._solution) + + def stream( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BindingInstance]: + """ + Streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["BindingInstance.BindingType"] binding_type: + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BindingInstance]: + """ + Asynchronously streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["BindingInstance.BindingType"] binding_type: + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + binding_type=binding_type, identity=identity, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BindingInstance]: + """ + Lists BindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["BindingInstance.BindingType"] binding_type: + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BindingInstance]: + """ + Asynchronously lists BindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["BindingInstance.BindingType"] binding_type: + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + binding_type=binding_type, + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BindingPage: + """ + Retrieve a single page of BindingInstance records from the API. + Request is executed immediately + + :param binding_type: + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BindingInstance + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BindingPage(self._version, response, self._solution) + + async def page_async( + self, + binding_type: Union[List["BindingInstance.BindingType"], object] = values.unset, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BindingPage: + """ + Asynchronously retrieve a single page of BindingInstance records from the API. + Request is executed immediately + + :param binding_type: + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BindingInstance + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BindingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> BindingPage: + """ + Retrieve a specific page of BindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BindingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BindingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> BindingPage: + """ + Asynchronously retrieve a specific page of BindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BindingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BindingPage(self._version, response, self._solution) + + def get(self, sid: str) -> BindingContext: + """ + Constructs a BindingContext + + :param sid: + """ + return BindingContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> BindingContext: + """ + Constructs a BindingContext + + :param sid: + """ + return BindingContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.BindingList>" diff --git a/twilio/rest/ip_messaging/v2/service/channel/__init__.py b/twilio/rest/ip_messaging/v2/service/channel/__init__.py new file mode 100644 index 0000000000..8220a4be9c --- /dev/null +++ b/twilio/rest/ip_messaging/v2/service/channel/__init__.py @@ -0,0 +1,962 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.ip_messaging.v2.service.channel.invite import InviteList +from twilio.rest.ip_messaging.v2.service.channel.member import MemberList +from twilio.rest.ip_messaging.v2.service.channel.message import MessageList +from twilio.rest.ip_messaging.v2.service.channel.webhook import WebhookList + + +class ChannelInstance(InstanceResource): + + class ChannelType(object): + PUBLIC = "public" + PRIVATE = "private" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar friendly_name: + :ivar unique_name: + :ivar attributes: + :ivar type: + :ivar date_created: + :ivar date_updated: + :ivar created_by: + :ivar members_count: + :ivar messages_count: + :ivar url: + :ivar links: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.type: Optional["ChannelInstance.ChannelType"] = payload.get("type") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + self.members_count: Optional[int] = deserialize.integer( + payload.get("members_count") + ) + self.messages_count: Optional[int] = deserialize.integer( + payload.get("messages_count") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ChannelContext] = None + + @property + def _proxy(self) -> "ChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ChannelContext for this ChannelInstance + """ + if self._context is None: + self._context = ChannelContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "ChannelInstance": + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ChannelInstance": + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param date_created: + :param date_updated: + :param created_by: + + :returns: The updated ChannelInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> "ChannelInstance": + """ + Asynchronous coroutine to update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param date_created: + :param date_updated: + :param created_by: + + :returns: The updated ChannelInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + created_by=created_by, + ) + + @property + def invites(self) -> InviteList: + """ + Access the invites + """ + return self._proxy.invites + + @property + def members(self) -> MemberList: + """ + Access the members + """ + return self._proxy.members + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + return self._proxy.messages + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + return self._proxy.webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.ChannelInstance {}>".format(context) + + +class ChannelContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the ChannelContext + + :param version: Version that contains the resource + :param service_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Channels/{sid}".format(**self._solution) + + self._invites: Optional[InviteList] = None + self._members: Optional[MemberList] = None + self._messages: Optional[MessageList] = None + self._webhooks: Optional[WebhookList] = None + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelInstance: + """ + Fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ChannelInstance: + """ + Asynchronous coroutine to fetch the ChannelInstance + + + :returns: The fetched ChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param date_created: + :param date_updated: + :param created_by: + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "CreatedBy": created_by, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronous coroutine to update the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param date_created: + :param date_updated: + :param created_by: + + :returns: The updated ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "CreatedBy": created_by, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def invites(self) -> InviteList: + """ + Access the invites + """ + if self._invites is None: + self._invites = InviteList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._invites + + @property + def members(self) -> MemberList: + """ + Access the members + """ + if self._members is None: + self._members = MemberList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._members + + @property + def messages(self) -> MessageList: + """ + Access the messages + """ + if self._messages is None: + self._messages = MessageList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._messages + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + if self._webhooks is None: + self._webhooks = WebhookList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.ChannelContext {}>".format(context) + + +class ChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: + """ + Build an instance of ChannelInstance + + :param payload: Payload response from the API + """ + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.ChannelPage>" + + +class ChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ChannelList + + :param version: Version that contains the resource + :param service_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Channels".format(**self._solution) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Create the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + :param date_created: + :param date_updated: + :param created_by: + + :returns: The created ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "Type": type, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "CreatedBy": created_by, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "ChannelInstance.WebhookEnabledType", object + ] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + type: Union["ChannelInstance.ChannelType", object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + created_by: Union[str, object] = values.unset, + ) -> ChannelInstance: + """ + Asynchronously create the ChannelInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param friendly_name: + :param unique_name: + :param attributes: + :param type: + :param date_created: + :param date_updated: + :param created_by: + + :returns: The created ChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "Type": type, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "CreatedBy": created_by, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelInstance]: + """ + Streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(type=type, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChannelInstance]: + """ + Asynchronously streams ChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(type=type, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + type=type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelInstance]: + """ + Asynchronously lists ChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["ChannelInstance.ChannelType"] type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + type=type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) + + async def page_async( + self, + type: Union[List["ChannelInstance.ChannelType"], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelPage: + """ + Asynchronously retrieve a single page of ChannelInstance records from the API. + Request is executed immediately + + :param type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelInstance + """ + data = values.of( + { + "Type": serialize.map(type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ChannelPage: + """ + Retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ChannelPage: + """ + Asynchronously retrieve a specific page of ChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelPage(self._version, response, self._solution) + + def get(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: + """ + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ChannelContext: + """ + Constructs a ChannelContext + + :param sid: + """ + return ChannelContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.ChannelList>" diff --git a/twilio/rest/ip_messaging/v2/service/channel/invite.py b/twilio/rest/ip_messaging/v2/service/channel/invite.py new file mode 100644 index 0000000000..4fa3c187fc --- /dev/null +++ b/twilio/rest/ip_messaging/v2/service/channel/invite.py @@ -0,0 +1,598 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InviteInstance(InstanceResource): + """ + :ivar sid: + :ivar account_sid: + :ivar channel_sid: + :ivar service_sid: + :ivar identity: + :ivar date_created: + :ivar date_updated: + :ivar role_sid: + :ivar created_by: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.created_by: Optional[str] = payload.get("created_by") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[InviteContext] = None + + @property + def _proxy(self) -> "InviteContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InviteContext for this InviteInstance + """ + if self._context is None: + self._context = InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "InviteInstance": + """ + Fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InviteInstance": + """ + Asynchronous coroutine to fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.InviteInstance {}>".format(context) + + +class InviteContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the InviteContext + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Invites/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InviteInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> InviteInstance: + """ + Fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InviteInstance: + """ + Asynchronous coroutine to fetch the InviteInstance + + + :returns: The fetched InviteInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.InviteContext {}>".format(context) + + +class InvitePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: + """ + Build an instance of InviteInstance + + :param payload: Payload response from the API + """ + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.InvitePage>" + + +class InviteList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the InviteList + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Invites".format( + **self._solution + ) + + def create( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Create the InviteInstance + + :param identity: + :param role_sid: + + :returns: The created InviteInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, identity: str, role_sid: Union[str, object] = values.unset + ) -> InviteInstance: + """ + Asynchronously create the InviteInstance + + :param identity: + :param role_sid: + + :returns: The created InviteInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InviteInstance]: + """ + Streams InviteInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InviteInstance]: + """ + Asynchronously streams InviteInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: + """ + Lists InviteInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InviteInstance]: + """ + Asynchronously lists InviteInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InvitePage: + """ + Retrieve a single page of InviteInstance records from the API. + Request is executed immediately + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InviteInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InvitePage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InvitePage: + """ + Asynchronously retrieve a single page of InviteInstance records from the API. + Request is executed immediately + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InviteInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InvitePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> InvitePage: + """ + Retrieve a specific page of InviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InviteInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InvitePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> InvitePage: + """ + Asynchronously retrieve a specific page of InviteInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InviteInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InvitePage(self._version, response, self._solution) + + def get(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InviteContext: + """ + Constructs a InviteContext + + :param sid: + """ + return InviteContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.InviteList>" diff --git a/twilio/rest/ip_messaging/v2/service/channel/member.py b/twilio/rest/ip_messaging/v2/service/channel/member.py new file mode 100644 index 0000000000..6456d3be20 --- /dev/null +++ b/twilio/rest/ip_messaging/v2/service/channel/member.py @@ -0,0 +1,905 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MemberInstance(InstanceResource): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: + :ivar account_sid: + :ivar channel_sid: + :ivar service_sid: + :ivar identity: + :ivar date_created: + :ivar date_updated: + :ivar role_sid: + :ivar last_consumed_message_index: + :ivar last_consumption_timestamp: + :ivar url: + :ivar attributes: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.role_sid: Optional[str] = payload.get("role_sid") + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.last_consumption_timestamp: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("last_consumption_timestamp")) + ) + self.url: Optional[str] = payload.get("url") + self.attributes: Optional[str] = payload.get("attributes") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[MemberContext] = None + + @property + def _proxy(self) -> "MemberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MemberContext for this MemberInstance + """ + if self._context is None: + self._context = MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "MemberInstance": + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MemberInstance": + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MemberInstance": + """ + Update the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: The updated MemberInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> "MemberInstance": + """ + Asynchronous coroutine to update the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: The updated MemberInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + date_created=date_created, + date_updated=date_updated, + attributes=attributes, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.MemberInstance {}>".format(context) + + +class MemberContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the MemberContext + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Members/{sid}".format( + **self._solution + ) + ) + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MemberInstance: + """ + Fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MemberInstance: + """ + Asynchronous coroutine to fetch the MemberInstance + + + :returns: The fetched MemberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Update the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: The updated MemberInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Asynchronous coroutine to update the MemberInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: The updated MemberInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.MemberContext {}>".format(context) + + +class MemberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: + """ + Build an instance of MemberInstance + + :param payload: Payload response from the API + """ + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.MemberPage>" + + +class MemberList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MemberList + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Members".format( + **self._solution + ) + + def create( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Create the MemberInstance + + :param identity: + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: The created MemberInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "MemberInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> MemberInstance: + """ + Asynchronously create the MemberInstance + + :param identity: + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param last_consumed_message_index: + :param last_consumption_timestamp: + :param date_created: + :param date_updated: + :param attributes: + + :returns: The created MemberInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Attributes": attributes, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MemberInstance]: + """ + Streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MemberInstance]: + """ + Asynchronously streams MemberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(identity=identity, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MemberInstance]: + """ + Asynchronously lists MemberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List[str] identity: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MemberPage: + """ + Asynchronously retrieve a single page of MemberInstance records from the API. + Request is executed immediately + + :param identity: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MemberInstance + """ + data = values.of( + { + "Identity": serialize.map(identity, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MemberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MemberPage: + """ + Retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MemberPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MemberPage: + """ + Asynchronously retrieve a specific page of MemberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MemberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MemberPage(self._version, response, self._solution) + + def get(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param sid: + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MemberContext: + """ + Constructs a MemberContext + + :param sid: + """ + return MemberContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.MemberList>" diff --git a/twilio/rest/ip_messaging/v2/service/channel/message.py b/twilio/rest/ip_messaging/v2/service/channel/message.py new file mode 100644 index 0000000000..838b3c7271 --- /dev/null +++ b/twilio/rest/ip_messaging/v2/service/channel/message.py @@ -0,0 +1,905 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MessageInstance(InstanceResource): + + class OrderType(object): + ASC = "asc" + DESC = "desc" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: + :ivar account_sid: + :ivar attributes: + :ivar service_sid: + :ivar to: + :ivar channel_sid: + :ivar date_created: + :ivar date_updated: + :ivar last_updated_by: + :ivar was_edited: + :ivar _from: + :ivar body: + :ivar index: + :ivar type: + :ivar media: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.service_sid: Optional[str] = payload.get("service_sid") + self.to: Optional[str] = payload.get("to") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.last_updated_by: Optional[str] = payload.get("last_updated_by") + self.was_edited: Optional[bool] = payload.get("was_edited") + self._from: Optional[str] = payload.get("from") + self.body: Optional[str] = payload.get("body") + self.index: Optional[int] = deserialize.integer(payload.get("index")) + self.type: Optional[str] = payload.get("type") + self.media: Optional[Dict[str, object]] = payload.get("media") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[MessageContext] = None + + @property + def _proxy(self) -> "MessageContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MessageContext for this MessageInstance + """ + if self._context is None: + self._context = MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + ) + + def fetch(self) -> "MessageInstance": + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MessageInstance": + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param from_: + + :returns: The updated MessageInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> "MessageInstance": + """ + Asynchronous coroutine to update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param from_: + + :returns: The updated MessageInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + body=body, + attributes=attributes, + date_created=date_created, + date_updated=date_updated, + last_updated_by=last_updated_by, + from_=from_, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.MessageInstance {}>".format(context) + + +class MessageContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the MessageContext + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Messages/{sid}".format( + **self._solution + ) + ) + + def delete( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + ) -> bool: + """ + Asynchronous coroutine that deletes the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessageInstance: + """ + Fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MessageInstance: + """ + Asynchronous coroutine to fetch the MessageInstance + + + :returns: The fetched MessageInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param from_: + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "From": from_, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + body: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronous coroutine to update the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param body: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param from_: + + :returns: The updated MessageInstance + """ + + data = values.of( + { + "Body": body, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "From": from_, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.MessageContext {}>".format(context) + + +class MessagePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInstance: + """ + Build an instance of MessageInstance + + :param payload: Payload response from the API + """ + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.MessagePage>" + + +class MessageList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the MessageList + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Messages".format( + **self._solution + ) + + def create( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param body: + :param media_sid: + + :returns: The created MessageInstance + """ + + data = values.of( + { + "From": from_, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "Body": body, + "MediaSid": media_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, + x_twilio_webhook_enabled: Union[ + "MessageInstance.WebhookEnabledType", object + ] = values.unset, + from_: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + date_created: Union[datetime, object] = values.unset, + date_updated: Union[datetime, object] = values.unset, + last_updated_by: Union[str, object] = values.unset, + body: Union[str, object] = values.unset, + media_sid: Union[str, object] = values.unset, + ) -> MessageInstance: + """ + Asynchronously create the MessageInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param from_: + :param attributes: + :param date_created: + :param date_updated: + :param last_updated_by: + :param body: + :param media_sid: + + :returns: The created MessageInstance + """ + + data = values.of( + { + "From": from_, + "Attributes": attributes, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "LastUpdatedBy": last_updated_by, + "Body": body, + "MediaSid": media_sid, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInstance]: + """ + Streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(order=order, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInstance]: + """ + Asynchronously streams MessageInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(order=order, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + order=order, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInstance]: + """ + Asynchronously lists MessageInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "MessageInstance.OrderType" order: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + order=order, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + async def page_async( + self, + order: Union["MessageInstance.OrderType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagePage: + """ + Asynchronously retrieve a single page of MessageInstance records from the API. + Request is executed immediately + + :param order: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInstance + """ + data = values.of( + { + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MessagePage: + """ + Retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MessagePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MessagePage: + """ + Asynchronously retrieve a specific page of MessageInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagePage(self._version, response, self._solution) + + def get(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MessageContext: + """ + Constructs a MessageContext + + :param sid: + """ + return MessageContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.MessageList>" diff --git a/twilio/rest/ip_messaging/v2/service/channel/webhook.py b/twilio/rest/ip_messaging/v2/service/channel/webhook.py new file mode 100644 index 0000000000..3c7570fd0e --- /dev/null +++ b/twilio/rest/ip_messaging/v2/service/channel/webhook.py @@ -0,0 +1,800 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class WebhookInstance(InstanceResource): + + class Method(object): + GET = "GET" + POST = "POST" + + class Type(object): + WEBHOOK = "webhook" + TRIGGER = "trigger" + STUDIO = "studio" + + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar channel_sid: + :ivar type: + :ivar url: + :ivar configuration: + :ivar date_created: + :ivar date_updated: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + channel_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.type: Optional[str] = payload.get("type") + self.url: Optional[str] = payload.get("url") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid or self.sid, + } + self._context: Optional[WebhookContext] = None + + @property + def _proxy(self) -> "WebhookContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WebhookContext for this WebhookInstance + """ + if self._context is None: + self._context = WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "WebhookInstance": + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WebhookInstance": + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> "WebhookInstance": + """ + Update the WebhookInstance + + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: The updated WebhookInstance + """ + return self._proxy.update( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> "WebhookInstance": + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: The updated WebhookInstance + """ + return await self._proxy.update_async( + configuration_url=configuration_url, + configuration_method=configuration_method, + configuration_filters=configuration_filters, + configuration_triggers=configuration_triggers, + configuration_flow_sid=configuration_flow_sid, + configuration_retry_count=configuration_retry_count, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.WebhookInstance {}>".format(context) + + +class WebhookContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): + """ + Initialize the WebhookContext + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Channels/{channel_sid}/Webhooks/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.RetryCount": configuration_retry_count, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.RetryCount": configuration_retry_count, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.WebhookContext {}>".format(context) + + +class WebhookPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: + """ + Build an instance of WebhookInstance + + :param payload: Payload response from the API + """ + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.WebhookPage>" + + +class WebhookList(ListResource): + + def __init__(self, version: Version, service_sid: str, channel_sid: str): + """ + Initialize the WebhookList + + :param version: Version that contains the resource + :param service_sid: + :param channel_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "channel_sid": channel_sid, + } + self._uri = "/Services/{service_sid}/Channels/{channel_sid}/Webhooks".format( + **self._solution + ) + + def create( + self, + type: "WebhookInstance.Type", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Create the WebhookInstance + + :param type: + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: The created WebhookInstance + """ + + data = values.of( + { + "Type": type, + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.RetryCount": configuration_retry_count, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def create_async( + self, + type: "WebhookInstance.Type", + configuration_url: Union[str, object] = values.unset, + configuration_method: Union["WebhookInstance.Method", object] = values.unset, + configuration_filters: Union[List[str], object] = values.unset, + configuration_triggers: Union[List[str], object] = values.unset, + configuration_flow_sid: Union[str, object] = values.unset, + configuration_retry_count: Union[int, object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronously create the WebhookInstance + + :param type: + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: + + :returns: The created WebhookInstance + """ + + data = values.of( + { + "Type": type, + "Configuration.Url": configuration_url, + "Configuration.Method": configuration_method, + "Configuration.Filters": serialize.map( + configuration_filters, lambda e: e + ), + "Configuration.Triggers": serialize.map( + configuration_triggers, lambda e: e + ), + "Configuration.FlowSid": configuration_flow_sid, + "Configuration.RetryCount": configuration_retry_count, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WebhookInstance]: + """ + Streams WebhookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WebhookInstance]: + """ + Asynchronously streams WebhookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: + """ + Lists WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: + """ + Asynchronously lists WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebhookPage: + """ + Retrieve a single page of WebhookInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebhookInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebhookPage: + """ + Asynchronously retrieve a single page of WebhookInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebhookInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> WebhookPage: + """ + Retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WebhookPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> WebhookPage: + """ + Asynchronously retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WebhookPage(self._version, response, self._solution) + + def get(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: + """ + return WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: + """ + return WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.WebhookList>" diff --git a/twilio/rest/ip_messaging/v2/service/role.py b/twilio/rest/ip_messaging/v2/service/role.py new file mode 100644 index 0000000000..32f70c2272 --- /dev/null +++ b/twilio/rest/ip_messaging/v2/service/role.py @@ -0,0 +1,645 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RoleInstance(InstanceResource): + + class RoleType(object): + CHANNEL = "channel" + DEPLOYMENT = "deployment" + + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar friendly_name: + :ivar type: + :ivar permissions: + :ivar date_created: + :ivar date_updated: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["RoleInstance.RoleType"] = payload.get("type") + self.permissions: Optional[List[str]] = payload.get("permissions") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[RoleContext] = None + + @property + def _proxy(self) -> "RoleContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoleContext for this RoleInstance + """ + if self._context is None: + self._context = RoleContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RoleInstance": + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RoleInstance": + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + return await self._proxy.fetch_async() + + def update(self, permission: List[str]) -> "RoleInstance": + """ + Update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + return self._proxy.update( + permission=permission, + ) + + async def update_async(self, permission: List[str]) -> "RoleInstance": + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + return await self._proxy.update_async( + permission=permission, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.RoleInstance {}>".format(context) + + +class RoleContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the RoleContext + + :param version: Version that contains the resource + :param service_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Roles/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoleInstance: + """ + Fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RoleInstance: + """ + Asynchronous coroutine to fetch the RoleInstance + + + :returns: The fetched RoleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update(self, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, permission: List[str]) -> RoleInstance: + """ + Asynchronous coroutine to update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + + data = values.of( + { + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.RoleContext {}>".format(context) + + +class RolePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: + """ + Build an instance of RoleInstance + + :param payload: Payload response from the API + """ + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.RolePage>" + + +class RoleList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the RoleList + + :param version: Version that contains the resource + :param service_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Roles".format(**self._solution) + + def create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Create the RoleInstance + + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> RoleInstance: + """ + Asynchronously create the RoleInstance + + :param friendly_name: + :param type: + :param permission: + + :returns: The created RoleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoleInstance]: + """ + Streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoleInstance]: + """ + Asynchronously streams RoleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleInstance]: + """ + Asynchronously lists RoleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RolePage: + """ + Asynchronously retrieve a single page of RoleInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RolePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RolePage: + """ + Retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RolePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RolePage: + """ + Asynchronously retrieve a specific page of RoleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RolePage(self._version, response, self._solution) + + def get(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RoleContext: + """ + Constructs a RoleContext + + :param sid: + """ + return RoleContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.RoleList>" diff --git a/twilio/rest/ip_messaging/v2/service/user/__init__.py b/twilio/rest/ip_messaging/v2/service/user/__init__.py new file mode 100644 index 0000000000..f5f1454c72 --- /dev/null +++ b/twilio/rest/ip_messaging/v2/service/user/__init__.py @@ -0,0 +1,804 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.ip_messaging.v2.service.user.user_binding import UserBindingList +from twilio.rest.ip_messaging.v2.service.user.user_channel import UserChannelList + + +class UserInstance(InstanceResource): + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar attributes: + :ivar friendly_name: + :ivar role_sid: + :ivar identity: + :ivar is_online: + :ivar is_notifiable: + :ivar date_created: + :ivar date_updated: + :ivar joined_channels_count: + :ivar links: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.role_sid: Optional[str] = payload.get("role_sid") + self.identity: Optional[str] = payload.get("identity") + self.is_online: Optional[bool] = payload.get("is_online") + self.is_notifiable: Optional[bool] = payload.get("is_notifiable") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.joined_channels_count: Optional[int] = deserialize.integer( + payload.get("joined_channels_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserContext] = None + + @property + def _proxy(self) -> "UserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + return self._proxy.update( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + return await self._proxy.update_async( + x_twilio_webhook_enabled=x_twilio_webhook_enabled, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, + ) + + @property + def user_bindings(self) -> UserBindingList: + """ + Access the user_bindings + """ + return self._proxy.user_bindings + + @property + def user_channels(self) -> UserChannelList: + """ + Access the user_channels + """ + return self._proxy.user_channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.UserInstance {}>".format(context) + + +class UserContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the UserContext + + :param version: Version that contains the resource + :param service_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Users/{sid}".format(**self._solution) + + self._user_bindings: Optional[UserBindingList] = None + self._user_channels: Optional[UserChannelList] = None + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The updated UserInstance + """ + + data = values.of( + { + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + if not ( + x_twilio_webhook_enabled is values.unset + or ( + isinstance(x_twilio_webhook_enabled, str) + and not x_twilio_webhook_enabled + ) + ): + headers["X-Twilio-Webhook-Enabled"] = x_twilio_webhook_enabled + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def user_bindings(self) -> UserBindingList: + """ + Access the user_bindings + """ + if self._user_bindings is None: + self._user_bindings = UserBindingList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._user_bindings + + @property + def user_channels(self) -> UserChannelList: + """ + Access the user_channels + """ + if self._user_channels is None: + self._user_channels = UserChannelList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._user_channels + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.UserContext {}>".format(context) + + +class UserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance + + :param payload: Payload response from the API + """ + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.UserPage>" + + +class UserList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the UserList + + :param version: Version that contains the resource + :param service_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Users".format(**self._solution) + + def create( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Create the UserInstance + + :param identity: + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + identity: str, + x_twilio_webhook_enabled: Union[ + "UserInstance.WebhookEnabledType", object + ] = values.unset, + role_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param identity: + :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header + :param role_sid: + :param attributes: + :param friendly_name: + + :returns: The created UserInstance + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + headers = values.of( + { + "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserInstance]: + """ + Streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserInstance]: + """ + Asynchronously streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Asynchronously lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserPage: + """ + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserPage: + """ + Asynchronously retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserPage(self._version, response, self._solution) + + def get(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: + """ + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> UserContext: + """ + Constructs a UserContext + + :param sid: + """ + return UserContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.UserList>" diff --git a/twilio/rest/ip_messaging/v2/service/user/user_binding.py b/twilio/rest/ip_messaging/v2/service/user/user_binding.py new file mode 100644 index 0000000000..4f1d9f10a7 --- /dev/null +++ b/twilio/rest/ip_messaging/v2/service/user/user_binding.py @@ -0,0 +1,552 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UserBindingInstance(InstanceResource): + + class BindingType(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: + :ivar account_sid: + :ivar service_sid: + :ivar date_created: + :ivar date_updated: + :ivar endpoint: + :ivar identity: + :ivar user_sid: + :ivar credential_sid: + :ivar binding_type: + :ivar message_types: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + user_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.endpoint: Optional[str] = payload.get("endpoint") + self.identity: Optional[str] = payload.get("identity") + self.user_sid: Optional[str] = payload.get("user_sid") + self.credential_sid: Optional[str] = payload.get("credential_sid") + self.binding_type: Optional["UserBindingInstance.BindingType"] = payload.get( + "binding_type" + ) + self.message_types: Optional[List[str]] = payload.get("message_types") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "sid": sid or self.sid, + } + self._context: Optional[UserBindingContext] = None + + @property + def _proxy(self) -> "UserBindingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserBindingContext for this UserBindingInstance + """ + if self._context is None: + self._context = UserBindingContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserBindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserBindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserBindingInstance": + """ + Fetch the UserBindingInstance + + + :returns: The fetched UserBindingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserBindingInstance": + """ + Asynchronous coroutine to fetch the UserBindingInstance + + + :returns: The fetched UserBindingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.UserBindingInstance {}>".format(context) + + +class UserBindingContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, user_sid: str, sid: str): + """ + Initialize the UserBindingContext + + :param version: Version that contains the resource + :param service_sid: + :param user_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Bindings/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the UserBindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserBindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserBindingInstance: + """ + Fetch the UserBindingInstance + + + :returns: The fetched UserBindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UserBindingInstance: + """ + Asynchronous coroutine to fetch the UserBindingInstance + + + :returns: The fetched UserBindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.UserBindingContext {}>".format(context) + + +class UserBindingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserBindingInstance: + """ + Build an instance of UserBindingInstance + + :param payload: Payload response from the API + """ + return UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.UserBindingPage>" + + +class UserBindingList(ListResource): + + def __init__(self, version: Version, service_sid: str, user_sid: str): + """ + Initialize the UserBindingList + + :param version: Version that contains the resource + :param service_sid: + :param user_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Bindings".format( + **self._solution + ) + + def stream( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserBindingInstance]: + """ + Streams UserBindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["UserBindingInstance.BindingType"] binding_type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(binding_type=binding_type, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserBindingInstance]: + """ + Asynchronously streams UserBindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param List["UserBindingInstance.BindingType"] binding_type: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + binding_type=binding_type, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserBindingInstance]: + """ + Lists UserBindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["UserBindingInstance.BindingType"] binding_type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + binding_type=binding_type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserBindingInstance]: + """ + Asynchronously lists UserBindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param List["UserBindingInstance.BindingType"] binding_type: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + binding_type=binding_type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserBindingPage: + """ + Retrieve a single page of UserBindingInstance records from the API. + Request is executed immediately + + :param binding_type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserBindingInstance + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserBindingPage(self._version, response, self._solution) + + async def page_async( + self, + binding_type: Union[ + List["UserBindingInstance.BindingType"], object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserBindingPage: + """ + Asynchronously retrieve a single page of UserBindingInstance records from the API. + Request is executed immediately + + :param binding_type: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserBindingInstance + """ + data = values.of( + { + "BindingType": serialize.map(binding_type, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserBindingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserBindingPage: + """ + Retrieve a specific page of UserBindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserBindingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserBindingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserBindingPage: + """ + Asynchronously retrieve a specific page of UserBindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserBindingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserBindingPage(self._version, response, self._solution) + + def get(self, sid: str) -> UserBindingContext: + """ + Constructs a UserBindingContext + + :param sid: + """ + return UserBindingContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> UserBindingContext: + """ + Constructs a UserBindingContext + + :param sid: + """ + return UserBindingContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.UserBindingList>" diff --git a/twilio/rest/ip_messaging/v2/service/user/user_channel.py b/twilio/rest/ip_messaging/v2/service/user/user_channel.py new file mode 100644 index 0000000000..5cb544fc3f --- /dev/null +++ b/twilio/rest/ip_messaging/v2/service/user/user_channel.py @@ -0,0 +1,666 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Ip_messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UserChannelInstance(InstanceResource): + + class ChannelStatus(object): + JOINED = "joined" + INVITED = "invited" + NOT_PARTICIPATING = "not_participating" + + class NotificationLevel(object): + DEFAULT = "default" + MUTED = "muted" + + """ + :ivar account_sid: + :ivar service_sid: + :ivar channel_sid: + :ivar user_sid: + :ivar member_sid: + :ivar status: + :ivar last_consumed_message_index: + :ivar unread_messages_count: + :ivar links: + :ivar url: + :ivar notification_level: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + user_sid: str, + channel_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.channel_sid: Optional[str] = payload.get("channel_sid") + self.user_sid: Optional[str] = payload.get("user_sid") + self.member_sid: Optional[str] = payload.get("member_sid") + self.status: Optional["UserChannelInstance.ChannelStatus"] = payload.get( + "status" + ) + self.last_consumed_message_index: Optional[int] = deserialize.integer( + payload.get("last_consumed_message_index") + ) + self.unread_messages_count: Optional[int] = deserialize.integer( + payload.get("unread_messages_count") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + self.url: Optional[str] = payload.get("url") + self.notification_level: Optional["UserChannelInstance.NotificationLevel"] = ( + payload.get("notification_level") + ) + + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "channel_sid": channel_sid or self.channel_sid, + } + self._context: Optional[UserChannelContext] = None + + @property + def _proxy(self) -> "UserChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserChannelContext for this UserChannelInstance + """ + if self._context is None: + self._context = UserChannelContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserChannelInstance": + """ + Fetch the UserChannelInstance + + + :returns: The fetched UserChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserChannelInstance": + """ + Asynchronous coroutine to fetch the UserChannelInstance + + + :returns: The fetched UserChannelInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> "UserChannelInstance": + """ + Update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: + + :returns: The updated UserChannelInstance + """ + return self._proxy.update( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + + async def update_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> "UserChannelInstance": + """ + Asynchronous coroutine to update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: + + :returns: The updated UserChannelInstance + """ + return await self._proxy.update_async( + notification_level=notification_level, + last_consumed_message_index=last_consumed_message_index, + last_consumption_timestamp=last_consumption_timestamp, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.UserChannelInstance {}>".format(context) + + +class UserChannelContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, user_sid: str, channel_sid: str + ): + """ + Initialize the UserChannelContext + + :param version: Version that contains the resource + :param service_sid: + :param user_sid: + :param channel_sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + "channel_sid": channel_sid, + } + self._uri = ( + "/Services/{service_sid}/Users/{user_sid}/Channels/{channel_sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the UserChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserChannelInstance: + """ + Fetch the UserChannelInstance + + + :returns: The fetched UserChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def fetch_async(self) -> UserChannelInstance: + """ + Asynchronous coroutine to fetch the UserChannelInstance + + + :returns: The fetched UserChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def update( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> UserChannelInstance: + """ + Update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: + + :returns: The updated UserChannelInstance + """ + + data = values.of( + { + "NotificationLevel": notification_level, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + + async def update_async( + self, + notification_level: Union[ + "UserChannelInstance.NotificationLevel", object + ] = values.unset, + last_consumed_message_index: Union[int, object] = values.unset, + last_consumption_timestamp: Union[datetime, object] = values.unset, + ) -> UserChannelInstance: + """ + Asynchronous coroutine to update the UserChannelInstance + + :param notification_level: + :param last_consumed_message_index: + :param last_consumption_timestamp: + + :returns: The updated UserChannelInstance + """ + + data = values.of( + { + "NotificationLevel": notification_level, + "LastConsumedMessageIndex": last_consumed_message_index, + "LastConsumptionTimestamp": serialize.iso8601_datetime( + last_consumption_timestamp + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.IpMessaging.V2.UserChannelContext {}>".format(context) + + +class UserChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: + """ + Build an instance of UserChannelInstance + + :param payload: Payload response from the API + """ + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.UserChannelPage>" + + +class UserChannelList(ListResource): + + def __init__(self, version: Version, service_sid: str, user_sid: str): + """ + Initialize the UserChannelList + + :param version: Version that contains the resource + :param service_sid: + :param user_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "user_sid": user_sid, + } + self._uri = "/Services/{service_sid}/Users/{user_sid}/Channels".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserChannelInstance]: + """ + Streams UserChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserChannelInstance]: + """ + Asynchronously streams UserChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: + """ + Lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserChannelInstance]: + """ + Asynchronously lists UserChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserChannelPage: + """ + Retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserChannelPage: + """ + Asynchronously retrieve a single page of UserChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserChannelPage: + """ + Retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserChannelPage: + """ + Asynchronously retrieve a specific page of UserChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserChannelPage(self._version, response, self._solution) + + def get(self, channel_sid: str) -> UserChannelContext: + """ + Constructs a UserChannelContext + + :param channel_sid: + """ + return UserChannelContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=channel_sid, + ) + + def __call__(self, channel_sid: str) -> UserChannelContext: + """ + Constructs a UserChannelContext + + :param channel_sid: + """ + return UserChannelContext( + self._version, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=channel_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.IpMessaging.V2.UserChannelList>" diff --git a/twilio/rest/lookups/LookupsBase.py b/twilio/rest/lookups/LookupsBase.py new file mode 100644 index 0000000000..e24f8dc611 --- /dev/null +++ b/twilio/rest/lookups/LookupsBase.py @@ -0,0 +1,55 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.lookups.v1 import V1 +from twilio.rest.lookups.v2 import V2 + + +class LookupsBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Lookups Domain + + :returns: Domain for Lookups + """ + super().__init__(twilio, "https://lookups.twilio.com") + self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Lookups + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Lookups + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Lookups>" diff --git a/twilio/rest/lookups/__init__.py b/twilio/rest/lookups/__init__.py new file mode 100644 index 0000000000..6a984f81ca --- /dev/null +++ b/twilio/rest/lookups/__init__.py @@ -0,0 +1,15 @@ +from warnings import warn + +from twilio.rest.lookups.LookupsBase import LookupsBase +from twilio.rest.lookups.v1.phone_number import PhoneNumberList + + +class Lookups(LookupsBase): + @property + def phone_numbers(self) -> PhoneNumberList: + warn( + "phone_numbers is deprecated. Use v1.phone_numbers instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.phone_numbers diff --git a/twilio/rest/lookups/v1/__init__.py b/twilio/rest/lookups/v1/__init__.py new file mode 100644 index 0000000000..72204da366 --- /dev/null +++ b/twilio/rest/lookups/v1/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Lookups + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.lookups.v1.phone_number import PhoneNumberList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Lookups + + :param domain: The Twilio.lookups domain + """ + super().__init__(domain, "v1") + self._phone_numbers: Optional[PhoneNumberList] = None + + @property + def phone_numbers(self) -> PhoneNumberList: + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList(self) + return self._phone_numbers + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Lookups.V1>" diff --git a/twilio/rest/lookups/v1/phone_number.py b/twilio/rest/lookups/v1/phone_number.py new file mode 100644 index 0000000000..304b89ab15 --- /dev/null +++ b/twilio/rest/lookups/v1/phone_number.py @@ -0,0 +1,272 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Lookups + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PhoneNumberInstance(InstanceResource): + """ + :ivar caller_name: The name of the phone number's owner. If `null`, that information was not available. + :ivar country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) for the phone number. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar national_format: The phone number, in national format. + :ivar carrier: The telecom company that provides the phone number. + :ivar add_ons: A JSON string with the results of the Add-ons you specified in the `add_ons` parameters. For the format of the object, see [Using Add-ons](https://www.twilio.com/docs/add-ons). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + phone_number: Optional[str] = None, + ): + super().__init__(version) + + self.caller_name: Optional[Dict[str, object]] = payload.get("caller_name") + self.country_code: Optional[str] = payload.get("country_code") + self.phone_number: Optional[str] = payload.get("phone_number") + self.national_format: Optional[str] = payload.get("national_format") + self.carrier: Optional[Dict[str, object]] = payload.get("carrier") + self.add_ons: Optional[Dict[str, object]] = payload.get("add_ons") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "phone_number": phone_number or self.phone_number, + } + self._context: Optional[PhoneNumberContext] = None + + @property + def _proxy(self) -> "PhoneNumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PhoneNumberContext for this PhoneNumberInstance + """ + if self._context is None: + self._context = PhoneNumberContext( + self._version, + phone_number=self._solution["phone_number"], + ) + return self._context + + def fetch( + self, + country_code: Union[str, object] = values.unset, + type: Union[List[str], object] = values.unset, + add_ons: Union[List[str], object] = values.unset, + add_ons_data: Union[Dict[str, object], object] = values.unset, + ) -> "PhoneNumberInstance": + """ + Fetch the PhoneNumberInstance + + :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). + :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. + + :returns: The fetched PhoneNumberInstance + """ + return self._proxy.fetch( + country_code=country_code, + type=type, + add_ons=add_ons, + add_ons_data=add_ons_data, + ) + + async def fetch_async( + self, + country_code: Union[str, object] = values.unset, + type: Union[List[str], object] = values.unset, + add_ons: Union[List[str], object] = values.unset, + add_ons_data: Union[Dict[str, object], object] = values.unset, + ) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). + :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. + + :returns: The fetched PhoneNumberInstance + """ + return await self._proxy.fetch_async( + country_code=country_code, + type=type, + add_ons=add_ons, + add_ons_data=add_ons_data, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Lookups.V1.PhoneNumberInstance {}>".format(context) + + +class PhoneNumberContext(InstanceContext): + + def __init__(self, version: Version, phone_number: str): + """ + Initialize the PhoneNumberContext + + :param version: Version that contains the resource + :param phone_number: The phone number to lookup in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "phone_number": phone_number, + } + self._uri = "/PhoneNumbers/{phone_number}".format(**self._solution) + + def fetch( + self, + country_code: Union[str, object] = values.unset, + type: Union[List[str], object] = values.unset, + add_ons: Union[List[str], object] = values.unset, + add_ons_data: Union[Dict[str, object], object] = values.unset, + ) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance + + :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). + :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. + + :returns: The fetched PhoneNumberInstance + """ + + data = values.of( + { + "CountryCode": country_code, + "Type": serialize.map(type, lambda e: e), + "AddOns": serialize.map(add_ons, lambda e: e), + } + ) + + data.update(serialize.prefixed_collapsible_map(add_ons_data, "AddOns")) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + async def fetch_async( + self, + country_code: Union[str, object] = values.unset, + type: Union[List[str], object] = values.unset, + add_ons: Union[List[str], object] = values.unset, + add_ons_data: Union[Dict[str, object], object] = values.unset, + ) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + :param country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the phone number to fetch. This is used to specify the country when the phone number is provided in a national format. + :param type: The type of information to return. Can be: `carrier` or `caller-name`. The default is null. To retrieve both types of information, specify this parameter twice; once with `carrier` and once with `caller-name` as the value. + :param add_ons: The `unique_name` of an Add-on you would like to invoke. Can be the `unique_name` of an Add-on that is installed on your account. You can specify multiple instances of this parameter to invoke multiple Add-ons. For more information about Add-ons, see the [Add-ons documentation](https://www.twilio.com/docs/add-ons). + :param add_ons_data: Data specific to the add-on you would like to invoke. The content and format of this value depends on the add-on. + + :returns: The fetched PhoneNumberInstance + """ + + data = values.of( + { + "CountryCode": country_code, + "Type": serialize.map(type, lambda e: e), + "AddOns": serialize.map(add_ons, lambda e: e), + } + ) + + data.update(serialize.prefixed_collapsible_map(add_ons_data, "AddOns")) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Lookups.V1.PhoneNumberContext {}>".format(context) + + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PhoneNumberList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, phone_number: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param phone_number: The phone number to lookup in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + """ + return PhoneNumberContext(self._version, phone_number=phone_number) + + def __call__(self, phone_number: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param phone_number: The phone number to lookup in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + """ + return PhoneNumberContext(self._version, phone_number=phone_number) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Lookups.V1.PhoneNumberList>" diff --git a/twilio/rest/lookups/v2/__init__.py b/twilio/rest/lookups/v2/__init__.py new file mode 100644 index 0000000000..d795aea168 --- /dev/null +++ b/twilio/rest/lookups/v2/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Lookups + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.lookups.v2.phone_number import PhoneNumberList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Lookups + + :param domain: The Twilio.lookups domain + """ + super().__init__(domain, "v2") + self._phone_numbers: Optional[PhoneNumberList] = None + + @property + def phone_numbers(self) -> PhoneNumberList: + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList(self) + return self._phone_numbers + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Lookups.V2>" diff --git a/twilio/rest/lookups/v2/phone_number.py b/twilio/rest/lookups/v2/phone_number.py new file mode 100644 index 0000000000..fc60eed6d3 --- /dev/null +++ b/twilio/rest/lookups/v2/phone_number.py @@ -0,0 +1,443 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Lookups + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PhoneNumberInstance(InstanceResource): + + class ValidationError(object): + TOO_SHORT = "TOO_SHORT" + TOO_LONG = "TOO_LONG" + INVALID_BUT_POSSIBLE = "INVALID_BUT_POSSIBLE" + INVALID_COUNTRY_CODE = "INVALID_COUNTRY_CODE" + INVALID_LENGTH = "INVALID_LENGTH" + NOT_A_NUMBER = "NOT_A_NUMBER" + + """ + :ivar calling_country_code: International dialing prefix of the phone number defined in the E.164 standard. + :ivar country_code: The phone number's [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar national_format: The phone number in [national format](https://en.wikipedia.org/wiki/National_conventions_for_writing_telephone_numbers). + :ivar valid: Boolean which indicates if the phone number is in a valid range that can be freely assigned by a carrier to a user. + :ivar validation_errors: Contains reasons why a phone number is invalid. Possible values: TOO_SHORT, TOO_LONG, INVALID_BUT_POSSIBLE, INVALID_COUNTRY_CODE, INVALID_LENGTH, NOT_A_NUMBER. + :ivar caller_name: An object that contains caller name information based on [CNAM](https://support.twilio.com/hc/en-us/articles/360051670533-Getting-Started-with-CNAM-Caller-ID). + :ivar sim_swap: An object that contains information on the last date the subscriber identity module (SIM) was changed for a mobile phone number. + :ivar call_forwarding: An object that contains information on the unconditional call forwarding status of mobile phone number. + :ivar line_status: An object that contains line status information for a mobile phone number. + :ivar line_type_intelligence: An object that contains line type information including the carrier name, mobile country code, and mobile network code. + :ivar identity_match: An object that contains identity match information. The result of comparing user-provided information including name, address, date of birth, national ID, against authoritative phone-based data sources + :ivar reassigned_number: An object that contains reassigned number information. Reassigned Numbers will return a phone number's reassignment status given a phone number and date + :ivar sms_pumping_risk: An object that contains information on if a phone number has been currently or previously blocked by Verify Fraud Guard for receiving malicious SMS pumping traffic as well as other signals associated with risky carriers and low conversion rates. + :ivar phone_number_quality_score: An object that contains information of a mobile phone number quality score. Quality score will return a risk score about the phone number. + :ivar pre_fill: An object that contains pre fill information. pre_fill will return PII information associated with the phone number like first name, last name, address line, country code, state and postal code. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + phone_number: Optional[str] = None, + ): + super().__init__(version) + + self.calling_country_code: Optional[str] = payload.get("calling_country_code") + self.country_code: Optional[str] = payload.get("country_code") + self.phone_number: Optional[str] = payload.get("phone_number") + self.national_format: Optional[str] = payload.get("national_format") + self.valid: Optional[bool] = payload.get("valid") + self.validation_errors: Optional[ + List["PhoneNumberInstance.ValidationError"] + ] = payload.get("validation_errors") + self.caller_name: Optional[Dict[str, object]] = payload.get("caller_name") + self.sim_swap: Optional[Dict[str, object]] = payload.get("sim_swap") + self.call_forwarding: Optional[Dict[str, object]] = payload.get( + "call_forwarding" + ) + self.line_status: Optional[Dict[str, object]] = payload.get("line_status") + self.line_type_intelligence: Optional[Dict[str, object]] = payload.get( + "line_type_intelligence" + ) + self.identity_match: Optional[Dict[str, object]] = payload.get("identity_match") + self.reassigned_number: Optional[Dict[str, object]] = payload.get( + "reassigned_number" + ) + self.sms_pumping_risk: Optional[Dict[str, object]] = payload.get( + "sms_pumping_risk" + ) + self.phone_number_quality_score: Optional[Dict[str, object]] = payload.get( + "phone_number_quality_score" + ) + self.pre_fill: Optional[Dict[str, object]] = payload.get("pre_fill") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "phone_number": phone_number or self.phone_number, + } + self._context: Optional[PhoneNumberContext] = None + + @property + def _proxy(self) -> "PhoneNumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PhoneNumberContext for this PhoneNumberInstance + """ + if self._context is None: + self._context = PhoneNumberContext( + self._version, + phone_number=self._solution["phone_number"], + ) + return self._context + + def fetch( + self, + fields: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + address_line1: Union[str, object] = values.unset, + address_line2: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + national_id: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + last_verified_date: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + partner_sub_id: Union[str, object] = values.unset, + ) -> "PhoneNumberInstance": + """ + Fetch the PhoneNumberInstance + + :param fields: A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill. + :param country_code: The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format. + :param first_name: User’s first name. This query parameter is only used (optionally) for identity_match package requests. + :param last_name: User’s last name. This query parameter is only used (optionally) for identity_match package requests. + :param address_line1: User’s first address line. This query parameter is only used (optionally) for identity_match package requests. + :param address_line2: User’s second address line. This query parameter is only used (optionally) for identity_match package requests. + :param city: User’s city. This query parameter is only used (optionally) for identity_match package requests. + :param state: User’s country subdivision, such as state, province, or locality. This query parameter is only used (optionally) for identity_match package requests. + :param postal_code: User’s postal zip code. This query parameter is only used (optionally) for identity_match package requests. + :param address_country_code: User’s country, up to two characters. This query parameter is only used (optionally) for identity_match package requests. + :param national_id: User’s national ID, such as SSN or Passport ID. This query parameter is only used (optionally) for identity_match package requests. + :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. + :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. + :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. + + :returns: The fetched PhoneNumberInstance + """ + return self._proxy.fetch( + fields=fields, + country_code=country_code, + first_name=first_name, + last_name=last_name, + address_line1=address_line1, + address_line2=address_line2, + city=city, + state=state, + postal_code=postal_code, + address_country_code=address_country_code, + national_id=national_id, + date_of_birth=date_of_birth, + last_verified_date=last_verified_date, + verification_sid=verification_sid, + partner_sub_id=partner_sub_id, + ) + + async def fetch_async( + self, + fields: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + address_line1: Union[str, object] = values.unset, + address_line2: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + national_id: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + last_verified_date: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + partner_sub_id: Union[str, object] = values.unset, + ) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + :param fields: A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill. + :param country_code: The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format. + :param first_name: User’s first name. This query parameter is only used (optionally) for identity_match package requests. + :param last_name: User’s last name. This query parameter is only used (optionally) for identity_match package requests. + :param address_line1: User’s first address line. This query parameter is only used (optionally) for identity_match package requests. + :param address_line2: User’s second address line. This query parameter is only used (optionally) for identity_match package requests. + :param city: User’s city. This query parameter is only used (optionally) for identity_match package requests. + :param state: User’s country subdivision, such as state, province, or locality. This query parameter is only used (optionally) for identity_match package requests. + :param postal_code: User’s postal zip code. This query parameter is only used (optionally) for identity_match package requests. + :param address_country_code: User’s country, up to two characters. This query parameter is only used (optionally) for identity_match package requests. + :param national_id: User’s national ID, such as SSN or Passport ID. This query parameter is only used (optionally) for identity_match package requests. + :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. + :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. + :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. + + :returns: The fetched PhoneNumberInstance + """ + return await self._proxy.fetch_async( + fields=fields, + country_code=country_code, + first_name=first_name, + last_name=last_name, + address_line1=address_line1, + address_line2=address_line2, + city=city, + state=state, + postal_code=postal_code, + address_country_code=address_country_code, + national_id=national_id, + date_of_birth=date_of_birth, + last_verified_date=last_verified_date, + verification_sid=verification_sid, + partner_sub_id=partner_sub_id, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Lookups.V2.PhoneNumberInstance {}>".format(context) + + +class PhoneNumberContext(InstanceContext): + + def __init__(self, version: Version, phone_number: str): + """ + Initialize the PhoneNumberContext + + :param version: Version that contains the resource + :param phone_number: The phone number to lookup in E.164 or national format. Default country code is +1 (North America). + """ + super().__init__(version) + + # Path Solution + self._solution = { + "phone_number": phone_number, + } + self._uri = "/PhoneNumbers/{phone_number}".format(**self._solution) + + def fetch( + self, + fields: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + address_line1: Union[str, object] = values.unset, + address_line2: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + national_id: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + last_verified_date: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + partner_sub_id: Union[str, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance + + :param fields: A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill. + :param country_code: The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format. + :param first_name: User’s first name. This query parameter is only used (optionally) for identity_match package requests. + :param last_name: User’s last name. This query parameter is only used (optionally) for identity_match package requests. + :param address_line1: User’s first address line. This query parameter is only used (optionally) for identity_match package requests. + :param address_line2: User’s second address line. This query parameter is only used (optionally) for identity_match package requests. + :param city: User’s city. This query parameter is only used (optionally) for identity_match package requests. + :param state: User’s country subdivision, such as state, province, or locality. This query parameter is only used (optionally) for identity_match package requests. + :param postal_code: User’s postal zip code. This query parameter is only used (optionally) for identity_match package requests. + :param address_country_code: User’s country, up to two characters. This query parameter is only used (optionally) for identity_match package requests. + :param national_id: User’s national ID, such as SSN or Passport ID. This query parameter is only used (optionally) for identity_match package requests. + :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. + :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. + :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. + + :returns: The fetched PhoneNumberInstance + """ + + data = values.of( + { + "Fields": fields, + "CountryCode": country_code, + "FirstName": first_name, + "LastName": last_name, + "AddressLine1": address_line1, + "AddressLine2": address_line2, + "City": city, + "State": state, + "PostalCode": postal_code, + "AddressCountryCode": address_country_code, + "NationalId": national_id, + "DateOfBirth": date_of_birth, + "LastVerifiedDate": last_verified_date, + "VerificationSid": verification_sid, + "PartnerSubId": partner_sub_id, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + async def fetch_async( + self, + fields: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + address_line1: Union[str, object] = values.unset, + address_line2: Union[str, object] = values.unset, + city: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + national_id: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + last_verified_date: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + partner_sub_id: Union[str, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + :param fields: A comma-separated list of fields to return. Possible values are validation, caller_name, sim_swap, call_forwarding, line_status, line_type_intelligence, identity_match, reassigned_number, sms_pumping_risk, phone_number_quality_score, pre_fill. + :param country_code: The [country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) used if the phone number provided is in national format. + :param first_name: User’s first name. This query parameter is only used (optionally) for identity_match package requests. + :param last_name: User’s last name. This query parameter is only used (optionally) for identity_match package requests. + :param address_line1: User’s first address line. This query parameter is only used (optionally) for identity_match package requests. + :param address_line2: User’s second address line. This query parameter is only used (optionally) for identity_match package requests. + :param city: User’s city. This query parameter is only used (optionally) for identity_match package requests. + :param state: User’s country subdivision, such as state, province, or locality. This query parameter is only used (optionally) for identity_match package requests. + :param postal_code: User’s postal zip code. This query parameter is only used (optionally) for identity_match package requests. + :param address_country_code: User’s country, up to two characters. This query parameter is only used (optionally) for identity_match package requests. + :param national_id: User’s national ID, such as SSN or Passport ID. This query parameter is only used (optionally) for identity_match package requests. + :param date_of_birth: User’s date of birth, in YYYYMMDD format. This query parameter is only used (optionally) for identity_match package requests. + :param last_verified_date: The date you obtained consent to call or text the end-user of the phone number or a date on which you are reasonably certain that the end-user could still be reached at that number. This query parameter is only used (optionally) for reassigned_number package requests. + :param verification_sid: The unique identifier associated with a verification process through verify API. This query parameter is only used (optionally) for pre_fill package requests. + :param partner_sub_id: The optional partnerSubId parameter to provide context for your sub-accounts, tenantIDs, sender IDs or other segmentation, enhancing the accuracy of the risk analysis. + + :returns: The fetched PhoneNumberInstance + """ + + data = values.of( + { + "Fields": fields, + "CountryCode": country_code, + "FirstName": first_name, + "LastName": last_name, + "AddressLine1": address_line1, + "AddressLine2": address_line2, + "City": city, + "State": state, + "PostalCode": postal_code, + "AddressCountryCode": address_country_code, + "NationalId": national_id, + "DateOfBirth": date_of_birth, + "LastVerifiedDate": last_verified_date, + "VerificationSid": verification_sid, + "PartnerSubId": partner_sub_id, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Lookups.V2.PhoneNumberContext {}>".format(context) + + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PhoneNumberList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, phone_number: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param phone_number: The phone number to lookup in E.164 or national format. Default country code is +1 (North America). + """ + return PhoneNumberContext(self._version, phone_number=phone_number) + + def __call__(self, phone_number: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param phone_number: The phone number to lookup in E.164 or national format. Default country code is +1 (North America). + """ + return PhoneNumberContext(self._version, phone_number=phone_number) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Lookups.V2.PhoneNumberList>" diff --git a/twilio/rest/marketplace/MarketplaceBase.py b/twilio/rest/marketplace/MarketplaceBase.py new file mode 100644 index 0000000000..9fbe193d99 --- /dev/null +++ b/twilio/rest/marketplace/MarketplaceBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.marketplace.v1 import V1 + + +class MarketplaceBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Marketplace Domain + + :returns: Domain for Marketplace + """ + super().__init__(twilio, "https://marketplace.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Marketplace + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Marketplace>" diff --git a/twilio/rest/marketplace/__init__.py b/twilio/rest/marketplace/__init__.py new file mode 100644 index 0000000000..f0276a8f84 --- /dev/null +++ b/twilio/rest/marketplace/__init__.py @@ -0,0 +1,9 @@ +from twilio.rest.marketplace.MarketplaceBase import MarketplaceBase + + +class Marketplace(MarketplaceBase): + def available_add_ons(self): + return self.v1.available_add_ons + + def installed_add_ons(self): + return self.v1.installed_add_ons diff --git a/twilio/rest/marketplace/v1/__init__.py b/twilio/rest/marketplace/v1/__init__.py new file mode 100644 index 0000000000..6a84b31cd9 --- /dev/null +++ b/twilio/rest/marketplace/v1/__init__.py @@ -0,0 +1,75 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.marketplace.v1.available_add_on import AvailableAddOnList +from twilio.rest.marketplace.v1.installed_add_on import InstalledAddOnList +from twilio.rest.marketplace.v1.module_data import ModuleDataList +from twilio.rest.marketplace.v1.module_data_management import ModuleDataManagementList +from twilio.rest.marketplace.v1.referral_conversion import ReferralConversionList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Marketplace + + :param domain: The Twilio.marketplace domain + """ + super().__init__(domain, "v1") + self._available_add_ons: Optional[AvailableAddOnList] = None + self._installed_add_ons: Optional[InstalledAddOnList] = None + self._module_data: Optional[ModuleDataList] = None + self._module_data_management: Optional[ModuleDataManagementList] = None + self._referral_conversion: Optional[ReferralConversionList] = None + + @property + def available_add_ons(self) -> AvailableAddOnList: + if self._available_add_ons is None: + self._available_add_ons = AvailableAddOnList(self) + return self._available_add_ons + + @property + def installed_add_ons(self) -> InstalledAddOnList: + if self._installed_add_ons is None: + self._installed_add_ons = InstalledAddOnList(self) + return self._installed_add_ons + + @property + def module_data(self) -> ModuleDataList: + if self._module_data is None: + self._module_data = ModuleDataList(self) + return self._module_data + + @property + def module_data_management(self) -> ModuleDataManagementList: + if self._module_data_management is None: + self._module_data_management = ModuleDataManagementList(self) + return self._module_data_management + + @property + def referral_conversion(self) -> ReferralConversionList: + if self._referral_conversion is None: + self._referral_conversion = ReferralConversionList(self) + return self._referral_conversion + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Marketplace.V1>" diff --git a/twilio/rest/marketplace/v1/available_add_on/__init__.py b/twilio/rest/marketplace/v1/available_add_on/__init__.py new file mode 100644 index 0000000000..297d5dd6f3 --- /dev/null +++ b/twilio/rest/marketplace/v1/available_add_on/__init__.py @@ -0,0 +1,438 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.marketplace.v1.available_add_on.available_add_on_extension import ( + AvailableAddOnExtensionList, +) + + +class AvailableAddOnInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the AvailableAddOn resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar description: A short description of the Add-on's functionality. + :ivar pricing_type: How customers are charged for using this Add-on. + :ivar configuration_schema: The JSON object with the configuration that must be provided when installing a given Add-on. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.pricing_type: Optional[str] = payload.get("pricing_type") + self.configuration_schema: Optional[Dict[str, object]] = payload.get( + "configuration_schema" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AvailableAddOnContext] = None + + @property + def _proxy(self) -> "AvailableAddOnContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AvailableAddOnContext for this AvailableAddOnInstance + """ + if self._context is None: + self._context = AvailableAddOnContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AvailableAddOnInstance": + """ + Fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AvailableAddOnInstance": + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + return await self._proxy.fetch_async() + + @property + def extensions(self) -> AvailableAddOnExtensionList: + """ + Access the extensions + """ + return self._proxy.extensions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Marketplace.V1.AvailableAddOnInstance {}>".format(context) + + +class AvailableAddOnContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the AvailableAddOnContext + + :param version: Version that contains the resource + :param sid: The SID of the AvailableAddOn resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/AvailableAddOns/{sid}".format(**self._solution) + + self._extensions: Optional[AvailableAddOnExtensionList] = None + + def fetch(self) -> AvailableAddOnInstance: + """ + Fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AvailableAddOnInstance: + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + @property + def extensions(self) -> AvailableAddOnExtensionList: + """ + Access the extensions + """ + if self._extensions is None: + self._extensions = AvailableAddOnExtensionList( + self._version, + self._solution["sid"], + ) + return self._extensions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Marketplace.V1.AvailableAddOnContext {}>".format(context) + + +class AvailableAddOnPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnInstance: + """ + Build an instance of AvailableAddOnInstance + + :param payload: Payload response from the API + """ + return AvailableAddOnInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Marketplace.V1.AvailableAddOnPage>" + + +class AvailableAddOnList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AvailableAddOnList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/AvailableAddOns" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AvailableAddOnInstance]: + """ + Streams AvailableAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AvailableAddOnInstance]: + """ + Asynchronously streams AvailableAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnInstance]: + """ + Lists AvailableAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnInstance]: + """ + Asynchronously lists AvailableAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailableAddOnPage: + """ + Retrieve a single page of AvailableAddOnInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AvailableAddOnInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailableAddOnPage: + """ + Asynchronously retrieve a single page of AvailableAddOnInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AvailableAddOnInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnPage(self._version, response) + + def get_page(self, target_url: str) -> AvailableAddOnPage: + """ + Retrieve a specific page of AvailableAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AvailableAddOnPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AvailableAddOnPage: + """ + Asynchronously retrieve a specific page of AvailableAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AvailableAddOnPage(self._version, response) + + def get(self, sid: str) -> AvailableAddOnContext: + """ + Constructs a AvailableAddOnContext + + :param sid: The SID of the AvailableAddOn resource to fetch. + """ + return AvailableAddOnContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AvailableAddOnContext: + """ + Constructs a AvailableAddOnContext + + :param sid: The SID of the AvailableAddOn resource to fetch. + """ + return AvailableAddOnContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Marketplace.V1.AvailableAddOnList>" diff --git a/twilio/rest/marketplace/v1/available_add_on/available_add_on_extension.py b/twilio/rest/marketplace/v1/available_add_on/available_add_on_extension.py new file mode 100644 index 0000000000..a8973a08b0 --- /dev/null +++ b/twilio/rest/marketplace/v1/available_add_on/available_add_on_extension.py @@ -0,0 +1,445 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AvailableAddOnExtensionInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the AvailableAddOnExtension resource. + :ivar available_add_on_sid: The SID of the AvailableAddOn resource to which this extension applies. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar product_name: The name of the Product this Extension is used within. + :ivar unique_name: An application-defined string that uniquely identifies the resource. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + available_add_on_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.available_add_on_sid: Optional[str] = payload.get("available_add_on_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.product_name: Optional[str] = payload.get("product_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "available_add_on_sid": available_add_on_sid, + "sid": sid or self.sid, + } + self._context: Optional[AvailableAddOnExtensionContext] = None + + @property + def _proxy(self) -> "AvailableAddOnExtensionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AvailableAddOnExtensionContext for this AvailableAddOnExtensionInstance + """ + if self._context is None: + self._context = AvailableAddOnExtensionContext( + self._version, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AvailableAddOnExtensionInstance": + """ + Fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AvailableAddOnExtensionInstance": + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Marketplace.V1.AvailableAddOnExtensionInstance {}>".format( + context + ) + + +class AvailableAddOnExtensionContext(InstanceContext): + + def __init__(self, version: Version, available_add_on_sid: str, sid: str): + """ + Initialize the AvailableAddOnExtensionContext + + :param version: Version that contains the resource + :param available_add_on_sid: The SID of the AvailableAddOn resource with the extension to fetch. + :param sid: The SID of the AvailableAddOn Extension resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "available_add_on_sid": available_add_on_sid, + "sid": sid, + } + self._uri = "/AvailableAddOns/{available_add_on_sid}/Extensions/{sid}".format( + **self._solution + ) + + def fetch(self) -> AvailableAddOnExtensionInstance: + """ + Fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AvailableAddOnExtensionInstance: + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Marketplace.V1.AvailableAddOnExtensionContext {}>".format( + context + ) + + +class AvailableAddOnExtensionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnExtensionInstance: + """ + Build an instance of AvailableAddOnExtensionInstance + + :param payload: Payload response from the API + """ + return AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Marketplace.V1.AvailableAddOnExtensionPage>" + + +class AvailableAddOnExtensionList(ListResource): + + def __init__(self, version: Version, available_add_on_sid: str): + """ + Initialize the AvailableAddOnExtensionList + + :param version: Version that contains the resource + :param available_add_on_sid: The SID of the AvailableAddOn resource with the extensions to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "available_add_on_sid": available_add_on_sid, + } + self._uri = "/AvailableAddOns/{available_add_on_sid}/Extensions".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AvailableAddOnExtensionInstance]: + """ + Streams AvailableAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AvailableAddOnExtensionInstance]: + """ + Asynchronously streams AvailableAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnExtensionInstance]: + """ + Lists AvailableAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnExtensionInstance]: + """ + Asynchronously lists AvailableAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailableAddOnExtensionPage: + """ + Retrieve a single page of AvailableAddOnExtensionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AvailableAddOnExtensionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnExtensionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailableAddOnExtensionPage: + """ + Asynchronously retrieve a single page of AvailableAddOnExtensionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AvailableAddOnExtensionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnExtensionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AvailableAddOnExtensionPage: + """ + Retrieve a specific page of AvailableAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnExtensionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AvailableAddOnExtensionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AvailableAddOnExtensionPage: + """ + Asynchronously retrieve a specific page of AvailableAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnExtensionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AvailableAddOnExtensionPage(self._version, response, self._solution) + + def get(self, sid: str) -> AvailableAddOnExtensionContext: + """ + Constructs a AvailableAddOnExtensionContext + + :param sid: The SID of the AvailableAddOn Extension resource to fetch. + """ + return AvailableAddOnExtensionContext( + self._version, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AvailableAddOnExtensionContext: + """ + Constructs a AvailableAddOnExtensionContext + + :param sid: The SID of the AvailableAddOn Extension resource to fetch. + """ + return AvailableAddOnExtensionContext( + self._version, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Marketplace.V1.AvailableAddOnExtensionList>" diff --git a/twilio/rest/marketplace/v1/installed_add_on/__init__.py b/twilio/rest/marketplace/v1/installed_add_on/__init__.py new file mode 100644 index 0000000000..8fedfb9b41 --- /dev/null +++ b/twilio/rest/marketplace/v1/installed_add_on/__init__.py @@ -0,0 +1,694 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.marketplace.v1.installed_add_on.installed_add_on_extension import ( + InstalledAddOnExtensionList, +) +from twilio.rest.marketplace.v1.installed_add_on.installed_add_on_usage import ( + InstalledAddOnUsageList, +) + + +class InstalledAddOnInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the InstalledAddOn resource. This Sid can also be found in the Console on that specific Add-ons page as the 'Available Add-on Sid'. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the InstalledAddOn resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar description: A short description of the Add-on's functionality. + :ivar configuration: The JSON object that represents the current configuration of installed Add-on. + :ivar unique_name: An application-defined string that uniquely identifies the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.unique_name: Optional[str] = payload.get("unique_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[InstalledAddOnContext] = None + + @property + def _proxy(self) -> "InstalledAddOnContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InstalledAddOnContext for this InstalledAddOnInstance + """ + if self._context is None: + self._context = InstalledAddOnContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the InstalledAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "InstalledAddOnInstance": + """ + Fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InstalledAddOnInstance": + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> "InstalledAddOnInstance": + """ + Update the InstalledAddOnInstance + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The updated InstalledAddOnInstance + """ + return self._proxy.update( + configuration=configuration, + unique_name=unique_name, + ) + + async def update_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> "InstalledAddOnInstance": + """ + Asynchronous coroutine to update the InstalledAddOnInstance + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The updated InstalledAddOnInstance + """ + return await self._proxy.update_async( + configuration=configuration, + unique_name=unique_name, + ) + + @property + def extensions(self) -> InstalledAddOnExtensionList: + """ + Access the extensions + """ + return self._proxy.extensions + + @property + def usage(self) -> InstalledAddOnUsageList: + """ + Access the usage + """ + return self._proxy.usage + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Marketplace.V1.InstalledAddOnInstance {}>".format(context) + + +class InstalledAddOnContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the InstalledAddOnContext + + :param version: Version that contains the resource + :param sid: The SID of the InstalledAddOn resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/InstalledAddOns/{sid}".format(**self._solution) + + self._extensions: Optional[InstalledAddOnExtensionList] = None + self._usage: Optional[InstalledAddOnUsageList] = None + + def delete(self) -> bool: + """ + Deletes the InstalledAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> InstalledAddOnInstance: + """ + Fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InstalledAddOnInstance: + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: + """ + Update the InstalledAddOnInstance + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The updated InstalledAddOnInstance + """ + + data = values.of( + { + "Configuration": serialize.object(configuration), + "UniqueName": unique_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: + """ + Asynchronous coroutine to update the InstalledAddOnInstance + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The updated InstalledAddOnInstance + """ + + data = values.of( + { + "Configuration": serialize.object(configuration), + "UniqueName": unique_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def extensions(self) -> InstalledAddOnExtensionList: + """ + Access the extensions + """ + if self._extensions is None: + self._extensions = InstalledAddOnExtensionList( + self._version, + self._solution["sid"], + ) + return self._extensions + + @property + def usage(self) -> InstalledAddOnUsageList: + """ + Access the usage + """ + if self._usage is None: + self._usage = InstalledAddOnUsageList( + self._version, + self._solution["sid"], + ) + return self._usage + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Marketplace.V1.InstalledAddOnContext {}>".format(context) + + +class InstalledAddOnPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnInstance: + """ + Build an instance of InstalledAddOnInstance + + :param payload: Payload response from the API + """ + return InstalledAddOnInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Marketplace.V1.InstalledAddOnPage>" + + +class InstalledAddOnList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InstalledAddOnList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/InstalledAddOns" + + def create( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: + """ + Create the InstalledAddOnInstance + + :param available_add_on_sid: The SID of the AvaliableAddOn to install. + :param accept_terms_of_service: Whether the Terms of Service were accepted. + :param configuration: The JSON object that represents the configuration of the new Add-on being installed. + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The created InstalledAddOnInstance + """ + + data = values.of( + { + "AvailableAddOnSid": available_add_on_sid, + "AcceptTermsOfService": serialize.boolean_to_string( + accept_terms_of_service + ), + "Configuration": serialize.object(configuration), + "UniqueName": unique_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnInstance(self._version, payload) + + async def create_async( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: + """ + Asynchronously create the InstalledAddOnInstance + + :param available_add_on_sid: The SID of the AvaliableAddOn to install. + :param accept_terms_of_service: Whether the Terms of Service were accepted. + :param configuration: The JSON object that represents the configuration of the new Add-on being installed. + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The created InstalledAddOnInstance + """ + + data = values.of( + { + "AvailableAddOnSid": available_add_on_sid, + "AcceptTermsOfService": serialize.boolean_to_string( + accept_terms_of_service + ), + "Configuration": serialize.object(configuration), + "UniqueName": unique_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InstalledAddOnInstance]: + """ + Streams InstalledAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InstalledAddOnInstance]: + """ + Asynchronously streams InstalledAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InstalledAddOnInstance]: + """ + Lists InstalledAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InstalledAddOnInstance]: + """ + Asynchronously lists InstalledAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InstalledAddOnPage: + """ + Retrieve a single page of InstalledAddOnInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InstalledAddOnInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InstalledAddOnPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InstalledAddOnPage: + """ + Asynchronously retrieve a single page of InstalledAddOnInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InstalledAddOnInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InstalledAddOnPage(self._version, response) + + def get_page(self, target_url: str) -> InstalledAddOnPage: + """ + Retrieve a specific page of InstalledAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InstalledAddOnPage(self._version, response) + + async def get_page_async(self, target_url: str) -> InstalledAddOnPage: + """ + Asynchronously retrieve a specific page of InstalledAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InstalledAddOnPage(self._version, response) + + def get(self, sid: str) -> InstalledAddOnContext: + """ + Constructs a InstalledAddOnContext + + :param sid: The SID of the InstalledAddOn resource to update. + """ + return InstalledAddOnContext(self._version, sid=sid) + + def __call__(self, sid: str) -> InstalledAddOnContext: + """ + Constructs a InstalledAddOnContext + + :param sid: The SID of the InstalledAddOn resource to update. + """ + return InstalledAddOnContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Marketplace.V1.InstalledAddOnList>" diff --git a/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_extension.py b/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_extension.py new file mode 100644 index 0000000000..88f160ed29 --- /dev/null +++ b/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_extension.py @@ -0,0 +1,533 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InstalledAddOnExtensionInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the InstalledAddOn Extension resource. + :ivar installed_add_on_sid: The SID of the InstalledAddOn resource to which this extension applies. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar product_name: The name of the Product this Extension is used within. + :ivar unique_name: An application-defined string that uniquely identifies the resource. + :ivar enabled: Whether the Extension will be invoked. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + installed_add_on_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.installed_add_on_sid: Optional[str] = payload.get("installed_add_on_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.product_name: Optional[str] = payload.get("product_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.enabled: Optional[bool] = payload.get("enabled") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + "sid": sid or self.sid, + } + self._context: Optional[InstalledAddOnExtensionContext] = None + + @property + def _proxy(self) -> "InstalledAddOnExtensionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InstalledAddOnExtensionContext for this InstalledAddOnExtensionInstance + """ + if self._context is None: + self._context = InstalledAddOnExtensionContext( + self._version, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "InstalledAddOnExtensionInstance": + """ + Fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InstalledAddOnExtensionInstance": + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + return await self._proxy.fetch_async() + + def update(self, enabled: bool) -> "InstalledAddOnExtensionInstance": + """ + Update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + return self._proxy.update( + enabled=enabled, + ) + + async def update_async(self, enabled: bool) -> "InstalledAddOnExtensionInstance": + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + return await self._proxy.update_async( + enabled=enabled, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Marketplace.V1.InstalledAddOnExtensionInstance {}>".format( + context + ) + + +class InstalledAddOnExtensionContext(InstanceContext): + + def __init__(self, version: Version, installed_add_on_sid: str, sid: str): + """ + Initialize the InstalledAddOnExtensionContext + + :param version: Version that contains the resource + :param installed_add_on_sid: The SID of the InstalledAddOn resource with the extension to update. + :param sid: The SID of the InstalledAddOn Extension resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + "sid": sid, + } + self._uri = "/InstalledAddOns/{installed_add_on_sid}/Extensions/{sid}".format( + **self._solution + ) + + def fetch(self) -> InstalledAddOnExtensionInstance: + """ + Fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InstalledAddOnExtensionInstance: + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + def update(self, enabled: bool) -> InstalledAddOnExtensionInstance: + """ + Update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, enabled: bool) -> InstalledAddOnExtensionInstance: + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Marketplace.V1.InstalledAddOnExtensionContext {}>".format( + context + ) + + +class InstalledAddOnExtensionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnExtensionInstance: + """ + Build an instance of InstalledAddOnExtensionInstance + + :param payload: Payload response from the API + """ + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Marketplace.V1.InstalledAddOnExtensionPage>" + + +class InstalledAddOnExtensionList(ListResource): + + def __init__(self, version: Version, installed_add_on_sid: str): + """ + Initialize the InstalledAddOnExtensionList + + :param version: Version that contains the resource + :param installed_add_on_sid: The SID of the InstalledAddOn resource with the extensions to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + } + self._uri = "/InstalledAddOns/{installed_add_on_sid}/Extensions".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InstalledAddOnExtensionInstance]: + """ + Streams InstalledAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InstalledAddOnExtensionInstance]: + """ + Asynchronously streams InstalledAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InstalledAddOnExtensionInstance]: + """ + Lists InstalledAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InstalledAddOnExtensionInstance]: + """ + Asynchronously lists InstalledAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InstalledAddOnExtensionPage: + """ + Retrieve a single page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InstalledAddOnExtensionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InstalledAddOnExtensionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InstalledAddOnExtensionPage: + """ + Asynchronously retrieve a single page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InstalledAddOnExtensionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InstalledAddOnExtensionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> InstalledAddOnExtensionPage: + """ + Retrieve a specific page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnExtensionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InstalledAddOnExtensionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> InstalledAddOnExtensionPage: + """ + Asynchronously retrieve a specific page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnExtensionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InstalledAddOnExtensionPage(self._version, response, self._solution) + + def get(self, sid: str) -> InstalledAddOnExtensionContext: + """ + Constructs a InstalledAddOnExtensionContext + + :param sid: The SID of the InstalledAddOn Extension resource to update. + """ + return InstalledAddOnExtensionContext( + self._version, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InstalledAddOnExtensionContext: + """ + Constructs a InstalledAddOnExtensionContext + + :param sid: The SID of the InstalledAddOn Extension resource to update. + """ + return InstalledAddOnExtensionContext( + self._version, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Marketplace.V1.InstalledAddOnExtensionList>" diff --git a/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_usage.py b/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_usage.py new file mode 100644 index 0000000000..1a54756496 --- /dev/null +++ b/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_usage.py @@ -0,0 +1,234 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class InstalledAddOnUsageInstance(InstanceResource): + + class MarketplaceV1InstalledAddOnInstalledAddOnUsage(object): + """ + :ivar total_submitted: Total amount in local currency that was billed in this request. Aggregates all billable_items that were successfully submitted. + :ivar billable_items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.total_submitted: Optional[float] = deserialize.decimal( + payload.get("total_submitted") + ) + self.billable_items: Optional[ + List[ + InstalledAddOnUsageList.MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems + ] + ] = payload.get("billable_items") + + def to_dict(self): + return { + "total_submitted": self.total_submitted, + "billable_items": ( + [billable_items.to_dict() for billable_items in self.billable_items] + if self.billable_items is not None + else None + ), + } + + class MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems(object): + """ + :ivar quantity: Total amount in local currency that was billed for this Billing Item. Can be any floating number greater than 0. + :ivar sid: BillingSid to use for billing. + :ivar submitted: Whether the billing event was successfully generated for this Billable Item. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.quantity: Optional[float] = payload.get("quantity") + self.sid: Optional[str] = payload.get("sid") + self.submitted: Optional[bool] = payload.get("submitted") + + def to_dict(self): + return { + "quantity": self.quantity, + "sid": self.sid, + "submitted": self.submitted, + } + + """ + :ivar total_submitted: Total amount in local currency that was billed in this request. Aggregates all billable_items that were successfully submitted. + :ivar billable_items: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], installed_add_on_sid: str + ): + super().__init__(version) + + self.total_submitted: Optional[float] = deserialize.decimal( + payload.get("total_submitted") + ) + self.billable_items: Optional[List[InstalledAddOnUsageList.str]] = payload.get( + "billable_items" + ) + + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Marketplace.V1.InstalledAddOnUsageInstance {}>".format(context) + + +class InstalledAddOnUsageList(ListResource): + + class MarketplaceV1InstalledAddOnInstalledAddOnUsage(object): + """ + :ivar total_submitted: Total amount in local currency that was billed in this request. Aggregates all billable_items that were successfully submitted. + :ivar billable_items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.total_submitted: Optional[float] = deserialize.decimal( + payload.get("total_submitted") + ) + self.billable_items: Optional[ + List[ + InstalledAddOnUsageList.MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems + ] + ] = payload.get("billable_items") + + def to_dict(self): + return { + "total_submitted": self.total_submitted, + "billable_items": ( + [billable_items.to_dict() for billable_items in self.billable_items] + if self.billable_items is not None + else None + ), + } + + class MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems(object): + """ + :ivar quantity: Total amount in local currency that was billed for this Billing Item. Can be any floating number greater than 0. + :ivar sid: BillingSid to use for billing. + :ivar submitted: Whether the billing event was successfully generated for this Billable Item. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.quantity: Optional[float] = payload.get("quantity") + self.sid: Optional[str] = payload.get("sid") + self.submitted: Optional[bool] = payload.get("submitted") + + def to_dict(self): + return { + "quantity": self.quantity, + "sid": self.sid, + "submitted": self.submitted, + } + + def __init__(self, version: Version, installed_add_on_sid: str): + """ + Initialize the InstalledAddOnUsageList + + :param version: Version that contains the resource + :param installed_add_on_sid: Customer Installation SID to report usage on. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + } + self._uri = "/InstalledAddOns/{installed_add_on_sid}/Usage".format( + **self._solution + ) + + def create( + self, + marketplace_v1_installed_add_on_installed_add_on_usage: MarketplaceV1InstalledAddOnInstalledAddOnUsage, + ) -> InstalledAddOnUsageInstance: + """ + Create the InstalledAddOnUsageInstance + + :param marketplace_v1_installed_add_on_installed_add_on_usage: + + :returns: The created InstalledAddOnUsageInstance + """ + data = marketplace_v1_installed_add_on_installed_add_on_usage.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnUsageInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + ) + + async def create_async( + self, + marketplace_v1_installed_add_on_installed_add_on_usage: MarketplaceV1InstalledAddOnInstalledAddOnUsage, + ) -> InstalledAddOnUsageInstance: + """ + Asynchronously create the InstalledAddOnUsageInstance + + :param marketplace_v1_installed_add_on_installed_add_on_usage: + + :returns: The created InstalledAddOnUsageInstance + """ + data = marketplace_v1_installed_add_on_installed_add_on_usage.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnUsageInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Marketplace.V1.InstalledAddOnUsageList>" diff --git a/twilio/rest/marketplace/v1/module_data.py b/twilio/rest/marketplace/v1/module_data.py new file mode 100644 index 0000000000..1308c17a91 --- /dev/null +++ b/twilio/rest/marketplace/v1/module_data.py @@ -0,0 +1,176 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ModuleDataInstance(InstanceResource): + """ + :ivar url: URL to query the subresource. + :ivar sid: ModuleSid that identifies this Listing. + :ivar description: A JSON object describing the module and is displayed under the Description tab of the Module detail page. You can define the main body of the description, highlight key features or aspects of the module and if applicable, provide code samples for developers + :ivar support: A JSON object containing information on how customers can obtain support for the module. Use this parameter to provide details such as contact information and support description. + :ivar policies: A JSON object describing the module's privacy and legal policies and is displayed under the Policies tab of the Module detail page. The maximum file size for Policies is 5MB + :ivar module_info: A JSON object containing essential attributes that define a module. This information is presented on the Module detail page in the Twilio Marketplace Catalog. You can pass the following attributes in the JSON object + :ivar documentation: A JSON object for providing comprehensive information, instructions, and resources related to the module + :ivar configuration: A JSON object for providing listing specific configuration. Contains button setup, notification url, among others. + :ivar pricing: A JSON object for providing Listing specific pricing information. + :ivar listings: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.url: Optional[str] = payload.get("url") + self.sid: Optional[str] = payload.get("sid") + self.description: Optional[Dict[str, object]] = payload.get("description") + self.support: Optional[Dict[str, object]] = payload.get("support") + self.policies: Optional[Dict[str, object]] = payload.get("policies") + self.module_info: Optional[Dict[str, object]] = payload.get("module_info") + self.documentation: Optional[Dict[str, object]] = payload.get("documentation") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.pricing: Optional[Dict[str, object]] = payload.get("pricing") + self.listings: Optional[List[Dict[str, object]]] = payload.get("listings") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Marketplace.V1.ModuleDataInstance>" + + +class ModuleDataList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ModuleDataList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Listings" + + def create( + self, + module_info: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + ) -> ModuleDataInstance: + """ + Create the ModuleDataInstance + + :param module_info: A JSON object containing essential attributes that define a Listing. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + + :returns: The created ModuleDataInstance + """ + + data = values.of( + { + "ModuleInfo": module_info, + "Configuration": configuration, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ModuleDataInstance(self._version, payload) + + async def create_async( + self, + module_info: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + ) -> ModuleDataInstance: + """ + Asynchronously create the ModuleDataInstance + + :param module_info: A JSON object containing essential attributes that define a Listing. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + + :returns: The created ModuleDataInstance + """ + + data = values.of( + { + "ModuleInfo": module_info, + "Configuration": configuration, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ModuleDataInstance(self._version, payload) + + def fetch(self) -> ModuleDataInstance: + """ + Asynchronously fetch the ModuleDataInstance + + + :returns: The fetched ModuleDataInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ModuleDataInstance(self._version, payload) + + async def fetch_async(self) -> ModuleDataInstance: + """ + Asynchronously fetch the ModuleDataInstance + + + :returns: The fetched ModuleDataInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ModuleDataInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Marketplace.V1.ModuleDataList>" diff --git a/twilio/rest/marketplace/v1/module_data_management.py b/twilio/rest/marketplace/v1/module_data_management.py new file mode 100644 index 0000000000..6ed82d846d --- /dev/null +++ b/twilio/rest/marketplace/v1/module_data_management.py @@ -0,0 +1,367 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ModuleDataManagementInstance(InstanceResource): + """ + :ivar url: URL to query the subresource. + :ivar sid: ModuleSid that identifies this Listing. + :ivar description: A JSON object describing the module and is displayed under the Description tab of the Module detail page. You can define the main body of the description, highlight key features or aspects of the module and if applicable, provide code samples for developers + :ivar support: A JSON object containing information on how customers can obtain support for the module. Use this parameter to provide details such as contact information and support description. + :ivar policies: A JSON object describing the module's privacy and legal policies and is displayed under the Policies tab of the Module detail page. The maximum file size for Policies is 5MB + :ivar module_info: A JSON object containing essential attributes that define a module. This information is presented on the Module detail page in the Twilio Marketplace Catalog. You can pass the following attributes in the JSON object + :ivar documentation: A JSON object for providing comprehensive information, instructions, and resources related to the module + :ivar configuration: A JSON object for providing listing specific configuration. Contains button setup, notification url, among others. + :ivar pricing: A JSON object for providing Listing specific pricing information. + :ivar listings: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.url: Optional[str] = payload.get("url") + self.sid: Optional[str] = payload.get("sid") + self.description: Optional[Dict[str, object]] = payload.get("description") + self.support: Optional[Dict[str, object]] = payload.get("support") + self.policies: Optional[Dict[str, object]] = payload.get("policies") + self.module_info: Optional[Dict[str, object]] = payload.get("module_info") + self.documentation: Optional[Dict[str, object]] = payload.get("documentation") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.pricing: Optional[Dict[str, object]] = payload.get("pricing") + self.listings: Optional[List[Dict[str, object]]] = payload.get("listings") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ModuleDataManagementContext] = None + + @property + def _proxy(self) -> "ModuleDataManagementContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ModuleDataManagementContext for this ModuleDataManagementInstance + """ + if self._context is None: + self._context = ModuleDataManagementContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ModuleDataManagementInstance": + """ + Fetch the ModuleDataManagementInstance + + + :returns: The fetched ModuleDataManagementInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ModuleDataManagementInstance": + """ + Asynchronous coroutine to fetch the ModuleDataManagementInstance + + + :returns: The fetched ModuleDataManagementInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + module_info: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + documentation: Union[str, object] = values.unset, + policies: Union[str, object] = values.unset, + support: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + pricing: Union[str, object] = values.unset, + ) -> "ModuleDataManagementInstance": + """ + Update the ModuleDataManagementInstance + + :param module_info: A JSON object containing essential attributes that define a Listing. + :param description: A JSON object describing the Listing. You can define the main body of the description, highlight key features or aspects of the Listing, and provide code samples for developers if applicable. + :param documentation: A JSON object for providing comprehensive information, instructions, and resources related to the Listing. + :param policies: A JSON object describing the Listing's privacy and legal policies. The maximum file size for Policies is 5MB. + :param support: A JSON object containing information on how Marketplace users can obtain support for the Listing. Use this parameter to provide details such as contact information and support description. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + :param pricing: A JSON object for providing Listing's purchase options. + + :returns: The updated ModuleDataManagementInstance + """ + return self._proxy.update( + module_info=module_info, + description=description, + documentation=documentation, + policies=policies, + support=support, + configuration=configuration, + pricing=pricing, + ) + + async def update_async( + self, + module_info: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + documentation: Union[str, object] = values.unset, + policies: Union[str, object] = values.unset, + support: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + pricing: Union[str, object] = values.unset, + ) -> "ModuleDataManagementInstance": + """ + Asynchronous coroutine to update the ModuleDataManagementInstance + + :param module_info: A JSON object containing essential attributes that define a Listing. + :param description: A JSON object describing the Listing. You can define the main body of the description, highlight key features or aspects of the Listing, and provide code samples for developers if applicable. + :param documentation: A JSON object for providing comprehensive information, instructions, and resources related to the Listing. + :param policies: A JSON object describing the Listing's privacy and legal policies. The maximum file size for Policies is 5MB. + :param support: A JSON object containing information on how Marketplace users can obtain support for the Listing. Use this parameter to provide details such as contact information and support description. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + :param pricing: A JSON object for providing Listing's purchase options. + + :returns: The updated ModuleDataManagementInstance + """ + return await self._proxy.update_async( + module_info=module_info, + description=description, + documentation=documentation, + policies=policies, + support=support, + configuration=configuration, + pricing=pricing, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Marketplace.V1.ModuleDataManagementInstance {}>".format(context) + + +class ModuleDataManagementContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ModuleDataManagementContext + + :param version: Version that contains the resource + :param sid: SID that uniquely identifies the Listing. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Listing/{sid}".format(**self._solution) + + def fetch(self) -> ModuleDataManagementInstance: + """ + Fetch the ModuleDataManagementInstance + + + :returns: The fetched ModuleDataManagementInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ModuleDataManagementInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ModuleDataManagementInstance: + """ + Asynchronous coroutine to fetch the ModuleDataManagementInstance + + + :returns: The fetched ModuleDataManagementInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ModuleDataManagementInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + module_info: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + documentation: Union[str, object] = values.unset, + policies: Union[str, object] = values.unset, + support: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + pricing: Union[str, object] = values.unset, + ) -> ModuleDataManagementInstance: + """ + Update the ModuleDataManagementInstance + + :param module_info: A JSON object containing essential attributes that define a Listing. + :param description: A JSON object describing the Listing. You can define the main body of the description, highlight key features or aspects of the Listing, and provide code samples for developers if applicable. + :param documentation: A JSON object for providing comprehensive information, instructions, and resources related to the Listing. + :param policies: A JSON object describing the Listing's privacy and legal policies. The maximum file size for Policies is 5MB. + :param support: A JSON object containing information on how Marketplace users can obtain support for the Listing. Use this parameter to provide details such as contact information and support description. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + :param pricing: A JSON object for providing Listing's purchase options. + + :returns: The updated ModuleDataManagementInstance + """ + + data = values.of( + { + "ModuleInfo": module_info, + "Description": description, + "Documentation": documentation, + "Policies": policies, + "Support": support, + "Configuration": configuration, + "Pricing": pricing, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ModuleDataManagementInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, + module_info: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + documentation: Union[str, object] = values.unset, + policies: Union[str, object] = values.unset, + support: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + pricing: Union[str, object] = values.unset, + ) -> ModuleDataManagementInstance: + """ + Asynchronous coroutine to update the ModuleDataManagementInstance + + :param module_info: A JSON object containing essential attributes that define a Listing. + :param description: A JSON object describing the Listing. You can define the main body of the description, highlight key features or aspects of the Listing, and provide code samples for developers if applicable. + :param documentation: A JSON object for providing comprehensive information, instructions, and resources related to the Listing. + :param policies: A JSON object describing the Listing's privacy and legal policies. The maximum file size for Policies is 5MB. + :param support: A JSON object containing information on how Marketplace users can obtain support for the Listing. Use this parameter to provide details such as contact information and support description. + :param configuration: A JSON object for providing Listing-specific configuration. Contains button setup, notification URL, and more. + :param pricing: A JSON object for providing Listing's purchase options. + + :returns: The updated ModuleDataManagementInstance + """ + + data = values.of( + { + "ModuleInfo": module_info, + "Description": description, + "Documentation": documentation, + "Policies": policies, + "Support": support, + "Configuration": configuration, + "Pricing": pricing, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ModuleDataManagementInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Marketplace.V1.ModuleDataManagementContext {}>".format(context) + + +class ModuleDataManagementList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ModuleDataManagementList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sid: str) -> ModuleDataManagementContext: + """ + Constructs a ModuleDataManagementContext + + :param sid: SID that uniquely identifies the Listing. + """ + return ModuleDataManagementContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ModuleDataManagementContext: + """ + Constructs a ModuleDataManagementContext + + :param sid: SID that uniquely identifies the Listing. + """ + return ModuleDataManagementContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Marketplace.V1.ModuleDataManagementList>" diff --git a/twilio/rest/marketplace/v1/referral_conversion.py b/twilio/rest/marketplace/v1/referral_conversion.py new file mode 100644 index 0000000000..9d9f3c2fa9 --- /dev/null +++ b/twilio/rest/marketplace/v1/referral_conversion.py @@ -0,0 +1,143 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ReferralConversionInstance(InstanceResource): + + class CreateReferralConversionRequest(object): + """ + :ivar referral_account_sid: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.referral_account_sid: Optional[str] = payload.get( + "referral_account_sid" + ) + + def to_dict(self): + return { + "referral_account_sid": self.referral_account_sid, + } + + """ + :ivar converted_account_sid: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.converted_account_sid: Optional[str] = payload.get("converted_account_sid") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Marketplace.V1.ReferralConversionInstance>" + + +class ReferralConversionList(ListResource): + + class CreateReferralConversionRequest(object): + """ + :ivar referral_account_sid: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.referral_account_sid: Optional[str] = payload.get( + "referral_account_sid" + ) + + def to_dict(self): + return { + "referral_account_sid": self.referral_account_sid, + } + + def __init__(self, version: Version): + """ + Initialize the ReferralConversionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ReferralConversion" + + def create( + self, create_referral_conversion_request: CreateReferralConversionRequest + ) -> ReferralConversionInstance: + """ + Create the ReferralConversionInstance + + :param create_referral_conversion_request: + + :returns: The created ReferralConversionInstance + """ + data = create_referral_conversion_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ReferralConversionInstance(self._version, payload) + + async def create_async( + self, create_referral_conversion_request: CreateReferralConversionRequest + ) -> ReferralConversionInstance: + """ + Asynchronously create the ReferralConversionInstance + + :param create_referral_conversion_request: + + :returns: The created ReferralConversionInstance + """ + data = create_referral_conversion_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ReferralConversionInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Marketplace.V1.ReferralConversionList>" diff --git a/twilio/rest/messaging/MessagingBase.py b/twilio/rest/messaging/MessagingBase.py new file mode 100644 index 0000000000..e45ed56fcd --- /dev/null +++ b/twilio/rest/messaging/MessagingBase.py @@ -0,0 +1,55 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.messaging.v1 import V1 +from twilio.rest.messaging.v2 import V2 + + +class MessagingBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Messaging Domain + + :returns: Domain for Messaging + """ + super().__init__(twilio, "https://messaging.twilio.com") + self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Messaging + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Messaging + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Messaging>" diff --git a/twilio/rest/messaging/__init__.py b/twilio/rest/messaging/__init__.py new file mode 100644 index 0000000000..4e62832592 --- /dev/null +++ b/twilio/rest/messaging/__init__.py @@ -0,0 +1,99 @@ +from warnings import warn + +from twilio.rest.messaging.MessagingBase import MessagingBase +from twilio.rest.messaging.v1.brand_registration import BrandRegistrationList +from twilio.rest.messaging.v1.deactivations import DeactivationsList +from twilio.rest.messaging.v1.domain_certs import DomainCertsList +from twilio.rest.messaging.v1.domain_config import DomainConfigList +from twilio.rest.messaging.v1.domain_config_messaging_service import ( + DomainConfigMessagingServiceList, +) +from twilio.rest.messaging.v1.external_campaign import ExternalCampaignList +from twilio.rest.messaging.v1.linkshortening_messaging_service import ( + LinkshorteningMessagingServiceList, +) +from twilio.rest.messaging.v1.service import ServiceList +from twilio.rest.messaging.v1.usecase import UsecaseList + + +class Messaging(MessagingBase): + @property + def brand_registrations(self) -> BrandRegistrationList: + warn( + "brand_registrations is deprecated. Use v1.brand_registrations instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.brand_registrations + + @property + def deactivations(self) -> DeactivationsList: + warn( + "deactivations is deprecated. Use v1.deactivations instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.deactivations + + @property + def domain_certs(self) -> DomainCertsList: + warn( + "domain_certs is deprecated. Use v1.domain_certs instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.domain_certs + + @property + def domain_config(self) -> DomainConfigList: + warn( + "domain_config is deprecated. Use v1.domain_config instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.domain_config + + @property + def domain_config_messaging_service(self) -> DomainConfigMessagingServiceList: + warn( + "domain_config_messaging_service is deprecated. Use v1.domain_config_messaging_service instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.domain_config_messaging_service + + @property + def external_campaign(self) -> ExternalCampaignList: + warn( + "external_campaign is deprecated. Use v1.external_campaign instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.external_campaign + + @property + def linkshortening_messaging_service(self) -> LinkshorteningMessagingServiceList: + warn( + "linkshortening_messaging_service is deprecated. Use v1.linkshortening_messaging_service instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.linkshortening_messaging_service + + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v1.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.services + + @property + def usecases(self) -> UsecaseList: + warn( + "usecases is deprecated. Use v1.usecases instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.usecases diff --git a/twilio/rest/messaging/v1/__init__.py b/twilio/rest/messaging/v1/__init__.py new file mode 100644 index 0000000000..6bd630fbd8 --- /dev/null +++ b/twilio/rest/messaging/v1/__init__.py @@ -0,0 +1,151 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.messaging.v1.brand_registration import BrandRegistrationList +from twilio.rest.messaging.v1.deactivations import DeactivationsList +from twilio.rest.messaging.v1.domain_certs import DomainCertsList +from twilio.rest.messaging.v1.domain_config import DomainConfigList +from twilio.rest.messaging.v1.domain_config_messaging_service import ( + DomainConfigMessagingServiceList, +) +from twilio.rest.messaging.v1.external_campaign import ExternalCampaignList +from twilio.rest.messaging.v1.linkshortening_messaging_service import ( + LinkshorteningMessagingServiceList, +) +from twilio.rest.messaging.v1.linkshortening_messaging_service_domain_association import ( + LinkshorteningMessagingServiceDomainAssociationList, +) +from twilio.rest.messaging.v1.request_managed_cert import RequestManagedCertList +from twilio.rest.messaging.v1.service import ServiceList +from twilio.rest.messaging.v1.tollfree_verification import TollfreeVerificationList +from twilio.rest.messaging.v1.usecase import UsecaseList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Messaging + + :param domain: The Twilio.messaging domain + """ + super().__init__(domain, "v1") + self._brand_registrations: Optional[BrandRegistrationList] = None + self._deactivations: Optional[DeactivationsList] = None + self._domain_certs: Optional[DomainCertsList] = None + self._domain_config: Optional[DomainConfigList] = None + self._domain_config_messaging_service: Optional[ + DomainConfigMessagingServiceList + ] = None + self._external_campaign: Optional[ExternalCampaignList] = None + self._linkshortening_messaging_service: Optional[ + LinkshorteningMessagingServiceList + ] = None + self._linkshortening_messaging_service_domain_association: Optional[ + LinkshorteningMessagingServiceDomainAssociationList + ] = None + self._request_managed_cert: Optional[RequestManagedCertList] = None + self._services: Optional[ServiceList] = None + self._tollfree_verifications: Optional[TollfreeVerificationList] = None + self._usecases: Optional[UsecaseList] = None + + @property + def brand_registrations(self) -> BrandRegistrationList: + if self._brand_registrations is None: + self._brand_registrations = BrandRegistrationList(self) + return self._brand_registrations + + @property + def deactivations(self) -> DeactivationsList: + if self._deactivations is None: + self._deactivations = DeactivationsList(self) + return self._deactivations + + @property + def domain_certs(self) -> DomainCertsList: + if self._domain_certs is None: + self._domain_certs = DomainCertsList(self) + return self._domain_certs + + @property + def domain_config(self) -> DomainConfigList: + if self._domain_config is None: + self._domain_config = DomainConfigList(self) + return self._domain_config + + @property + def domain_config_messaging_service(self) -> DomainConfigMessagingServiceList: + if self._domain_config_messaging_service is None: + self._domain_config_messaging_service = DomainConfigMessagingServiceList( + self + ) + return self._domain_config_messaging_service + + @property + def external_campaign(self) -> ExternalCampaignList: + if self._external_campaign is None: + self._external_campaign = ExternalCampaignList(self) + return self._external_campaign + + @property + def linkshortening_messaging_service(self) -> LinkshorteningMessagingServiceList: + if self._linkshortening_messaging_service is None: + self._linkshortening_messaging_service = LinkshorteningMessagingServiceList( + self + ) + return self._linkshortening_messaging_service + + @property + def linkshortening_messaging_service_domain_association( + self, + ) -> LinkshorteningMessagingServiceDomainAssociationList: + if self._linkshortening_messaging_service_domain_association is None: + self._linkshortening_messaging_service_domain_association = ( + LinkshorteningMessagingServiceDomainAssociationList(self) + ) + return self._linkshortening_messaging_service_domain_association + + @property + def request_managed_cert(self) -> RequestManagedCertList: + if self._request_managed_cert is None: + self._request_managed_cert = RequestManagedCertList(self) + return self._request_managed_cert + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + @property + def tollfree_verifications(self) -> TollfreeVerificationList: + if self._tollfree_verifications is None: + self._tollfree_verifications = TollfreeVerificationList(self) + return self._tollfree_verifications + + @property + def usecases(self) -> UsecaseList: + if self._usecases is None: + self._usecases = UsecaseList(self) + return self._usecases + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1>" diff --git a/twilio/rest/messaging/v1/brand_registration/__init__.py b/twilio/rest/messaging/v1/brand_registration/__init__.py new file mode 100644 index 0000000000..939cba604c --- /dev/null +++ b/twilio/rest/messaging/v1/brand_registration/__init__.py @@ -0,0 +1,673 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.messaging.v1.brand_registration.brand_registration_otp import ( + BrandRegistrationOtpList, +) +from twilio.rest.messaging.v1.brand_registration.brand_vetting import BrandVettingList + + +class BrandRegistrationInstance(InstanceResource): + + class BrandFeedback(object): + TAX_ID = "TAX_ID" + STOCK_SYMBOL = "STOCK_SYMBOL" + NONPROFIT = "NONPROFIT" + GOVERNMENT_ENTITY = "GOVERNMENT_ENTITY" + OTHERS = "OTHERS" + + class IdentityStatus(object): + SELF_DECLARED = "SELF_DECLARED" + UNVERIFIED = "UNVERIFIED" + VERIFIED = "VERIFIED" + VETTED_VERIFIED = "VETTED_VERIFIED" + + class Status(object): + PENDING = "PENDING" + APPROVED = "APPROVED" + FAILED = "FAILED" + IN_REVIEW = "IN_REVIEW" + DELETION_PENDING = "DELETION_PENDING" + DELETION_FAILED = "DELETION_FAILED" + SUSPENDED = "SUSPENDED" + + """ + :ivar sid: The unique string to identify Brand Registration. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Brand Registration resource. + :ivar customer_profile_bundle_sid: A2P Messaging Profile Bundle BundleSid. + :ivar a2p_profile_bundle_sid: A2P Messaging Profile Bundle BundleSid. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar brand_type: Type of brand. One of: \"STANDARD\", \"SOLE_PROPRIETOR\". SOLE_PROPRIETOR is for the low volume, SOLE_PROPRIETOR campaign use case. There can only be one SOLE_PROPRIETOR campaign created per SOLE_PROPRIETOR brand. STANDARD is for all other campaign use cases. Multiple campaign use cases can be created per STANDARD brand. + :ivar status: + :ivar tcr_id: Campaign Registry (TCR) Brand ID. Assigned only after successful brand registration. + :ivar failure_reason: DEPRECATED. A reason why brand registration has failed. Only applicable when status is FAILED. + :ivar errors: A list of errors that occurred during the brand registration process. + :ivar url: The absolute URL of the Brand Registration resource. + :ivar brand_score: The secondary vetting score if it was done. Otherwise, it will be the brand score if it's returned from TCR. It may be null if no score is available. + :ivar brand_feedback: DEPRECATED. Feedback on how to improve brand score + :ivar identity_status: + :ivar russell_3000: Publicly traded company identified in the Russell 3000 Index + :ivar government_entity: Identified as a government entity + :ivar tax_exempt_status: Nonprofit organization tax-exempt status per section 501 of the U.S. tax code. + :ivar skip_automatic_sec_vet: A flag to disable automatic secondary vetting for brands which it would otherwise be done. + :ivar mock: A boolean that specifies whether brand should be a mock or not. If true, brand will be registered as a mock brand. Defaults to false if no value is provided. + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.customer_profile_bundle_sid: Optional[str] = payload.get( + "customer_profile_bundle_sid" + ) + self.a2p_profile_bundle_sid: Optional[str] = payload.get( + "a2p_profile_bundle_sid" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.brand_type: Optional[str] = payload.get("brand_type") + self.status: Optional["BrandRegistrationInstance.Status"] = payload.get( + "status" + ) + self.tcr_id: Optional[str] = payload.get("tcr_id") + self.failure_reason: Optional[str] = payload.get("failure_reason") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") + self.url: Optional[str] = payload.get("url") + self.brand_score: Optional[int] = deserialize.integer( + payload.get("brand_score") + ) + self.brand_feedback: Optional[ + List["BrandRegistrationInstance.BrandFeedback"] + ] = payload.get("brand_feedback") + self.identity_status: Optional["BrandRegistrationInstance.IdentityStatus"] = ( + payload.get("identity_status") + ) + self.russell_3000: Optional[bool] = payload.get("russell_3000") + self.government_entity: Optional[bool] = payload.get("government_entity") + self.tax_exempt_status: Optional[str] = payload.get("tax_exempt_status") + self.skip_automatic_sec_vet: Optional[bool] = payload.get( + "skip_automatic_sec_vet" + ) + self.mock: Optional[bool] = payload.get("mock") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[BrandRegistrationContext] = None + + @property + def _proxy(self) -> "BrandRegistrationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BrandRegistrationContext for this BrandRegistrationInstance + """ + if self._context is None: + self._context = BrandRegistrationContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "BrandRegistrationInstance": + """ + Fetch the BrandRegistrationInstance + + + :returns: The fetched BrandRegistrationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BrandRegistrationInstance": + """ + Asynchronous coroutine to fetch the BrandRegistrationInstance + + + :returns: The fetched BrandRegistrationInstance + """ + return await self._proxy.fetch_async() + + def update(self) -> "BrandRegistrationInstance": + """ + Update the BrandRegistrationInstance + + + :returns: The updated BrandRegistrationInstance + """ + return self._proxy.update() + + async def update_async(self) -> "BrandRegistrationInstance": + """ + Asynchronous coroutine to update the BrandRegistrationInstance + + + :returns: The updated BrandRegistrationInstance + """ + return await self._proxy.update_async() + + @property + def brand_registration_otps(self) -> BrandRegistrationOtpList: + """ + Access the brand_registration_otps + """ + return self._proxy.brand_registration_otps + + @property + def brand_vettings(self) -> BrandVettingList: + """ + Access the brand_vettings + """ + return self._proxy.brand_vettings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.BrandRegistrationInstance {}>".format(context) + + +class BrandRegistrationContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the BrandRegistrationContext + + :param version: Version that contains the resource + :param sid: The SID of the Brand Registration resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/a2p/BrandRegistrations/{sid}".format(**self._solution) + + self._brand_registration_otps: Optional[BrandRegistrationOtpList] = None + self._brand_vettings: Optional[BrandVettingList] = None + + def fetch(self) -> BrandRegistrationInstance: + """ + Fetch the BrandRegistrationInstance + + + :returns: The fetched BrandRegistrationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return BrandRegistrationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> BrandRegistrationInstance: + """ + Asynchronous coroutine to fetch the BrandRegistrationInstance + + + :returns: The fetched BrandRegistrationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return BrandRegistrationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update(self) -> BrandRegistrationInstance: + """ + Update the BrandRegistrationInstance + + + :returns: The updated BrandRegistrationInstance + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BrandRegistrationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async(self) -> BrandRegistrationInstance: + """ + Asynchronous coroutine to update the BrandRegistrationInstance + + + :returns: The updated BrandRegistrationInstance + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BrandRegistrationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + @property + def brand_registration_otps(self) -> BrandRegistrationOtpList: + """ + Access the brand_registration_otps + """ + if self._brand_registration_otps is None: + self._brand_registration_otps = BrandRegistrationOtpList( + self._version, + self._solution["sid"], + ) + return self._brand_registration_otps + + @property + def brand_vettings(self) -> BrandVettingList: + """ + Access the brand_vettings + """ + if self._brand_vettings is None: + self._brand_vettings = BrandVettingList( + self._version, + self._solution["sid"], + ) + return self._brand_vettings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.BrandRegistrationContext {}>".format(context) + + +class BrandRegistrationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BrandRegistrationInstance: + """ + Build an instance of BrandRegistrationInstance + + :param payload: Payload response from the API + """ + return BrandRegistrationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.BrandRegistrationPage>" + + +class BrandRegistrationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BrandRegistrationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/a2p/BrandRegistrations" + + def create( + self, + customer_profile_bundle_sid: str, + a2p_profile_bundle_sid: str, + brand_type: Union[str, object] = values.unset, + mock: Union[bool, object] = values.unset, + skip_automatic_sec_vet: Union[bool, object] = values.unset, + ) -> BrandRegistrationInstance: + """ + Create the BrandRegistrationInstance + + :param customer_profile_bundle_sid: Customer Profile Bundle Sid. + :param a2p_profile_bundle_sid: A2P Messaging Profile Bundle Sid. + :param brand_type: Type of brand being created. One of: \\\"STANDARD\\\", \\\"SOLE_PROPRIETOR\\\". SOLE_PROPRIETOR is for low volume, SOLE_PROPRIETOR use cases. STANDARD is for all other use cases. + :param mock: A boolean that specifies whether brand should be a mock or not. If true, brand will be registered as a mock brand. Defaults to false if no value is provided. + :param skip_automatic_sec_vet: A flag to disable automatic secondary vetting for brands which it would otherwise be done. + + :returns: The created BrandRegistrationInstance + """ + + data = values.of( + { + "CustomerProfileBundleSid": customer_profile_bundle_sid, + "A2PProfileBundleSid": a2p_profile_bundle_sid, + "BrandType": brand_type, + "Mock": serialize.boolean_to_string(mock), + "SkipAutomaticSecVet": serialize.boolean_to_string( + skip_automatic_sec_vet + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BrandRegistrationInstance(self._version, payload) + + async def create_async( + self, + customer_profile_bundle_sid: str, + a2p_profile_bundle_sid: str, + brand_type: Union[str, object] = values.unset, + mock: Union[bool, object] = values.unset, + skip_automatic_sec_vet: Union[bool, object] = values.unset, + ) -> BrandRegistrationInstance: + """ + Asynchronously create the BrandRegistrationInstance + + :param customer_profile_bundle_sid: Customer Profile Bundle Sid. + :param a2p_profile_bundle_sid: A2P Messaging Profile Bundle Sid. + :param brand_type: Type of brand being created. One of: \\\"STANDARD\\\", \\\"SOLE_PROPRIETOR\\\". SOLE_PROPRIETOR is for low volume, SOLE_PROPRIETOR use cases. STANDARD is for all other use cases. + :param mock: A boolean that specifies whether brand should be a mock or not. If true, brand will be registered as a mock brand. Defaults to false if no value is provided. + :param skip_automatic_sec_vet: A flag to disable automatic secondary vetting for brands which it would otherwise be done. + + :returns: The created BrandRegistrationInstance + """ + + data = values.of( + { + "CustomerProfileBundleSid": customer_profile_bundle_sid, + "A2PProfileBundleSid": a2p_profile_bundle_sid, + "BrandType": brand_type, + "Mock": serialize.boolean_to_string(mock), + "SkipAutomaticSecVet": serialize.boolean_to_string( + skip_automatic_sec_vet + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BrandRegistrationInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BrandRegistrationInstance]: + """ + Streams BrandRegistrationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BrandRegistrationInstance]: + """ + Asynchronously streams BrandRegistrationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BrandRegistrationInstance]: + """ + Lists BrandRegistrationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BrandRegistrationInstance]: + """ + Asynchronously lists BrandRegistrationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BrandRegistrationPage: + """ + Retrieve a single page of BrandRegistrationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BrandRegistrationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BrandRegistrationPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BrandRegistrationPage: + """ + Asynchronously retrieve a single page of BrandRegistrationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BrandRegistrationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BrandRegistrationPage(self._version, response) + + def get_page(self, target_url: str) -> BrandRegistrationPage: + """ + Retrieve a specific page of BrandRegistrationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BrandRegistrationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BrandRegistrationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> BrandRegistrationPage: + """ + Asynchronously retrieve a specific page of BrandRegistrationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BrandRegistrationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BrandRegistrationPage(self._version, response) + + def get(self, sid: str) -> BrandRegistrationContext: + """ + Constructs a BrandRegistrationContext + + :param sid: The SID of the Brand Registration resource to update. + """ + return BrandRegistrationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> BrandRegistrationContext: + """ + Constructs a BrandRegistrationContext + + :param sid: The SID of the Brand Registration resource to update. + """ + return BrandRegistrationContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.BrandRegistrationList>" diff --git a/twilio/rest/messaging/v1/brand_registration/brand_registration_otp.py b/twilio/rest/messaging/v1/brand_registration/brand_registration_otp.py new file mode 100644 index 0000000000..415dec9589 --- /dev/null +++ b/twilio/rest/messaging/v1/brand_registration/brand_registration_otp.py @@ -0,0 +1,121 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class BrandRegistrationOtpInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Brand Registration resource. + :ivar brand_registration_sid: The unique string to identify Brand Registration of Sole Proprietor Brand + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], brand_registration_sid: str + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.brand_registration_sid: Optional[str] = payload.get( + "brand_registration_sid" + ) + + self._solution = { + "brand_registration_sid": brand_registration_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.BrandRegistrationOtpInstance {}>".format(context) + + +class BrandRegistrationOtpList(ListResource): + + def __init__(self, version: Version, brand_registration_sid: str): + """ + Initialize the BrandRegistrationOtpList + + :param version: Version that contains the resource + :param brand_registration_sid: Brand Registration Sid of Sole Proprietor Brand. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "brand_registration_sid": brand_registration_sid, + } + self._uri = "/a2p/BrandRegistrations/{brand_registration_sid}/SmsOtp".format( + **self._solution + ) + + def create(self) -> BrandRegistrationOtpInstance: + """ + Create the BrandRegistrationOtpInstance + + + :returns: The created BrandRegistrationOtpInstance + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = self._version.create(method="POST", uri=self._uri, headers=headers) + + return BrandRegistrationOtpInstance( + self._version, + payload, + brand_registration_sid=self._solution["brand_registration_sid"], + ) + + async def create_async(self) -> BrandRegistrationOtpInstance: + """ + Asynchronously create the BrandRegistrationOtpInstance + + + :returns: The created BrandRegistrationOtpInstance + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, headers=headers + ) + + return BrandRegistrationOtpInstance( + self._version, + payload, + brand_registration_sid=self._solution["brand_registration_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.BrandRegistrationOtpList>" diff --git a/twilio/rest/messaging/v1/brand_registration/brand_vetting.py b/twilio/rest/messaging/v1/brand_registration/brand_vetting.py new file mode 100644 index 0000000000..b633144a71 --- /dev/null +++ b/twilio/rest/messaging/v1/brand_registration/brand_vetting.py @@ -0,0 +1,561 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class BrandVettingInstance(InstanceResource): + + class VettingProvider(object): + CAMPAIGN_VERIFY = "campaign-verify" + AEGIS = "aegis" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the vetting record. + :ivar brand_sid: The unique string to identify Brand Registration. + :ivar brand_vetting_sid: The Twilio SID of the third-party vetting record. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar vetting_id: The unique identifier of the vetting from the third-party provider. + :ivar vetting_class: The type of vetting that has been conducted. One of “STANDARD” (Aegis) or “POLITICAL” (Campaign Verify). + :ivar vetting_status: The status of the import vetting attempt. One of “PENDING,” “SUCCESS,” or “FAILED”. + :ivar vetting_provider: + :ivar url: The absolute URL of the Brand Vetting resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + brand_sid: str, + brand_vetting_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.brand_sid: Optional[str] = payload.get("brand_sid") + self.brand_vetting_sid: Optional[str] = payload.get("brand_vetting_sid") + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.vetting_id: Optional[str] = payload.get("vetting_id") + self.vetting_class: Optional[str] = payload.get("vetting_class") + self.vetting_status: Optional[str] = payload.get("vetting_status") + self.vetting_provider: Optional["BrandVettingInstance.VettingProvider"] = ( + payload.get("vetting_provider") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "brand_sid": brand_sid, + "brand_vetting_sid": brand_vetting_sid or self.brand_vetting_sid, + } + self._context: Optional[BrandVettingContext] = None + + @property + def _proxy(self) -> "BrandVettingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BrandVettingContext for this BrandVettingInstance + """ + if self._context is None: + self._context = BrandVettingContext( + self._version, + brand_sid=self._solution["brand_sid"], + brand_vetting_sid=self._solution["brand_vetting_sid"], + ) + return self._context + + def fetch(self) -> "BrandVettingInstance": + """ + Fetch the BrandVettingInstance + + + :returns: The fetched BrandVettingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BrandVettingInstance": + """ + Asynchronous coroutine to fetch the BrandVettingInstance + + + :returns: The fetched BrandVettingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.BrandVettingInstance {}>".format(context) + + +class BrandVettingContext(InstanceContext): + + def __init__(self, version: Version, brand_sid: str, brand_vetting_sid: str): + """ + Initialize the BrandVettingContext + + :param version: Version that contains the resource + :param brand_sid: The SID of the Brand Registration resource of the vettings to read . + :param brand_vetting_sid: The Twilio SID of the third-party vetting record. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "brand_sid": brand_sid, + "brand_vetting_sid": brand_vetting_sid, + } + self._uri = ( + "/a2p/BrandRegistrations/{brand_sid}/Vettings/{brand_vetting_sid}".format( + **self._solution + ) + ) + + def fetch(self) -> BrandVettingInstance: + """ + Fetch the BrandVettingInstance + + + :returns: The fetched BrandVettingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return BrandVettingInstance( + self._version, + payload, + brand_sid=self._solution["brand_sid"], + brand_vetting_sid=self._solution["brand_vetting_sid"], + ) + + async def fetch_async(self) -> BrandVettingInstance: + """ + Asynchronous coroutine to fetch the BrandVettingInstance + + + :returns: The fetched BrandVettingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return BrandVettingInstance( + self._version, + payload, + brand_sid=self._solution["brand_sid"], + brand_vetting_sid=self._solution["brand_vetting_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.BrandVettingContext {}>".format(context) + + +class BrandVettingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BrandVettingInstance: + """ + Build an instance of BrandVettingInstance + + :param payload: Payload response from the API + """ + return BrandVettingInstance( + self._version, payload, brand_sid=self._solution["brand_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.BrandVettingPage>" + + +class BrandVettingList(ListResource): + + def __init__(self, version: Version, brand_sid: str): + """ + Initialize the BrandVettingList + + :param version: Version that contains the resource + :param brand_sid: The SID of the Brand Registration resource of the vettings to read . + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "brand_sid": brand_sid, + } + self._uri = "/a2p/BrandRegistrations/{brand_sid}/Vettings".format( + **self._solution + ) + + def create( + self, + vetting_provider: "BrandVettingInstance.VettingProvider", + vetting_id: Union[str, object] = values.unset, + ) -> BrandVettingInstance: + """ + Create the BrandVettingInstance + + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: The created BrandVettingInstance + """ + + data = values.of( + { + "VettingProvider": vetting_provider, + "VettingId": vetting_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BrandVettingInstance( + self._version, payload, brand_sid=self._solution["brand_sid"] + ) + + async def create_async( + self, + vetting_provider: "BrandVettingInstance.VettingProvider", + vetting_id: Union[str, object] = values.unset, + ) -> BrandVettingInstance: + """ + Asynchronously create the BrandVettingInstance + + :param vetting_provider: + :param vetting_id: The unique ID of the vetting + + :returns: The created BrandVettingInstance + """ + + data = values.of( + { + "VettingProvider": vetting_provider, + "VettingId": vetting_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BrandVettingInstance( + self._version, payload, brand_sid=self._solution["brand_sid"] + ) + + def stream( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BrandVettingInstance]: + """ + Streams BrandVettingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "BrandVettingInstance.VettingProvider" vetting_provider: The third-party provider of the vettings to read + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + vetting_provider=vetting_provider, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BrandVettingInstance]: + """ + Asynchronously streams BrandVettingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "BrandVettingInstance.VettingProvider" vetting_provider: The third-party provider of the vettings to read + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + vetting_provider=vetting_provider, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BrandVettingInstance]: + """ + Lists BrandVettingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "BrandVettingInstance.VettingProvider" vetting_provider: The third-party provider of the vettings to read + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + vetting_provider=vetting_provider, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BrandVettingInstance]: + """ + Asynchronously lists BrandVettingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "BrandVettingInstance.VettingProvider" vetting_provider: The third-party provider of the vettings to read + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + vetting_provider=vetting_provider, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BrandVettingPage: + """ + Retrieve a single page of BrandVettingInstance records from the API. + Request is executed immediately + + :param vetting_provider: The third-party provider of the vettings to read + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BrandVettingInstance + """ + data = values.of( + { + "VettingProvider": vetting_provider, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BrandVettingPage(self._version, response, self._solution) + + async def page_async( + self, + vetting_provider: Union[ + "BrandVettingInstance.VettingProvider", object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BrandVettingPage: + """ + Asynchronously retrieve a single page of BrandVettingInstance records from the API. + Request is executed immediately + + :param vetting_provider: The third-party provider of the vettings to read + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BrandVettingInstance + """ + data = values.of( + { + "VettingProvider": vetting_provider, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BrandVettingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> BrandVettingPage: + """ + Retrieve a specific page of BrandVettingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BrandVettingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BrandVettingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> BrandVettingPage: + """ + Asynchronously retrieve a specific page of BrandVettingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BrandVettingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BrandVettingPage(self._version, response, self._solution) + + def get(self, brand_vetting_sid: str) -> BrandVettingContext: + """ + Constructs a BrandVettingContext + + :param brand_vetting_sid: The Twilio SID of the third-party vetting record. + """ + return BrandVettingContext( + self._version, + brand_sid=self._solution["brand_sid"], + brand_vetting_sid=brand_vetting_sid, + ) + + def __call__(self, brand_vetting_sid: str) -> BrandVettingContext: + """ + Constructs a BrandVettingContext + + :param brand_vetting_sid: The Twilio SID of the third-party vetting record. + """ + return BrandVettingContext( + self._version, + brand_sid=self._solution["brand_sid"], + brand_vetting_sid=brand_vetting_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.BrandVettingList>" diff --git a/twilio/rest/messaging/v1/deactivations.py b/twilio/rest/messaging/v1/deactivations.py new file mode 100644 index 0000000000..e2cbf17a94 --- /dev/null +++ b/twilio/rest/messaging/v1/deactivations.py @@ -0,0 +1,199 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class DeactivationsInstance(InstanceResource): + """ + :ivar redirect_to: Returns an authenticated url that redirects to a file containing the deactivated numbers for the requested day. This url is valid for up to two minutes. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.redirect_to: Optional[str] = payload.get("redirect_to") + + self._context: Optional[DeactivationsContext] = None + + @property + def _proxy(self) -> "DeactivationsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DeactivationsContext for this DeactivationsInstance + """ + if self._context is None: + self._context = DeactivationsContext( + self._version, + ) + return self._context + + def fetch( + self, date: Union[date, object] = values.unset + ) -> "DeactivationsInstance": + """ + Fetch the DeactivationsInstance + + :param date: The request will return a list of all United States Phone Numbers that were deactivated on the day specified by this parameter. This date should be specified in YYYY-MM-DD format. + + :returns: The fetched DeactivationsInstance + """ + return self._proxy.fetch( + date=date, + ) + + async def fetch_async( + self, date: Union[date, object] = values.unset + ) -> "DeactivationsInstance": + """ + Asynchronous coroutine to fetch the DeactivationsInstance + + :param date: The request will return a list of all United States Phone Numbers that were deactivated on the day specified by this parameter. This date should be specified in YYYY-MM-DD format. + + :returns: The fetched DeactivationsInstance + """ + return await self._proxy.fetch_async( + date=date, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Messaging.V1.DeactivationsInstance>" + + +class DeactivationsContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the DeactivationsContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/Deactivations" + + def fetch(self, date: Union[date, object] = values.unset) -> DeactivationsInstance: + """ + Fetch the DeactivationsInstance + + :param date: The request will return a list of all United States Phone Numbers that were deactivated on the day specified by this parameter. This date should be specified in YYYY-MM-DD format. + + :returns: The fetched DeactivationsInstance + """ + + data = values.of( + { + "Date": serialize.iso8601_date(date), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return DeactivationsInstance( + self._version, + payload, + ) + + async def fetch_async( + self, date: Union[date, object] = values.unset + ) -> DeactivationsInstance: + """ + Asynchronous coroutine to fetch the DeactivationsInstance + + :param date: The request will return a list of all United States Phone Numbers that were deactivated on the day specified by this parameter. This date should be specified in YYYY-MM-DD format. + + :returns: The fetched DeactivationsInstance + """ + + data = values.of( + { + "Date": serialize.iso8601_date(date), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return DeactivationsInstance( + self._version, + payload, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Messaging.V1.DeactivationsContext>" + + +class DeactivationsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the DeactivationsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> DeactivationsContext: + """ + Constructs a DeactivationsContext + + """ + return DeactivationsContext(self._version) + + def __call__(self) -> DeactivationsContext: + """ + Constructs a DeactivationsContext + + """ + return DeactivationsContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.DeactivationsList>" diff --git a/twilio/rest/messaging/v1/domain_certs.py b/twilio/rest/messaging/v1/domain_certs.py new file mode 100644 index 0000000000..6da256cdb0 --- /dev/null +++ b/twilio/rest/messaging/v1/domain_certs.py @@ -0,0 +1,337 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class DomainCertsInstance(InstanceResource): + """ + :ivar domain_sid: The unique string that we created to identify the Domain resource. + :ivar date_updated: Date that this Domain was last updated. + :ivar date_expires: Date that the private certificate associated with this domain expires. You will need to update the certificate before that date to ensure your shortened links will continue to work. + :ivar date_created: Date that this Domain was registered to the Twilio platform to create a new Domain object. + :ivar domain_name: Full url path for this domain. + :ivar certificate_sid: The unique string that we created to identify this Certificate resource. + :ivar url: + :ivar cert_in_validation: Optional JSON field describing the status and upload date of a new certificate in the process of validation + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + domain_sid: Optional[str] = None, + ): + super().__init__(version) + + self.domain_sid: Optional[str] = payload.get("domain_sid") + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.date_expires: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expires") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.domain_name: Optional[str] = payload.get("domain_name") + self.certificate_sid: Optional[str] = payload.get("certificate_sid") + self.url: Optional[str] = payload.get("url") + self.cert_in_validation: Optional[Dict[str, object]] = payload.get( + "cert_in_validation" + ) + + self._solution = { + "domain_sid": domain_sid or self.domain_sid, + } + self._context: Optional[DomainCertsContext] = None + + @property + def _proxy(self) -> "DomainCertsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DomainCertsContext for this DomainCertsInstance + """ + if self._context is None: + self._context = DomainCertsContext( + self._version, + domain_sid=self._solution["domain_sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the DomainCertsInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DomainCertsInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "DomainCertsInstance": + """ + Fetch the DomainCertsInstance + + + :returns: The fetched DomainCertsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DomainCertsInstance": + """ + Asynchronous coroutine to fetch the DomainCertsInstance + + + :returns: The fetched DomainCertsInstance + """ + return await self._proxy.fetch_async() + + def update(self, tls_cert: str) -> "DomainCertsInstance": + """ + Update the DomainCertsInstance + + :param tls_cert: Contains the full TLS certificate and private for this domain in PEM format: https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail. Twilio uses this information to process HTTPS traffic sent to your domain. + + :returns: The updated DomainCertsInstance + """ + return self._proxy.update( + tls_cert=tls_cert, + ) + + async def update_async(self, tls_cert: str) -> "DomainCertsInstance": + """ + Asynchronous coroutine to update the DomainCertsInstance + + :param tls_cert: Contains the full TLS certificate and private for this domain in PEM format: https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail. Twilio uses this information to process HTTPS traffic sent to your domain. + + :returns: The updated DomainCertsInstance + """ + return await self._proxy.update_async( + tls_cert=tls_cert, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.DomainCertsInstance {}>".format(context) + + +class DomainCertsContext(InstanceContext): + + def __init__(self, version: Version, domain_sid: str): + """ + Initialize the DomainCertsContext + + :param version: Version that contains the resource + :param domain_sid: Unique string used to identify the domain that this certificate should be associated with. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "domain_sid": domain_sid, + } + self._uri = "/LinkShortening/Domains/{domain_sid}/Certificate".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the DomainCertsInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DomainCertsInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> DomainCertsInstance: + """ + Fetch the DomainCertsInstance + + + :returns: The fetched DomainCertsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DomainCertsInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + + async def fetch_async(self) -> DomainCertsInstance: + """ + Asynchronous coroutine to fetch the DomainCertsInstance + + + :returns: The fetched DomainCertsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DomainCertsInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + + def update(self, tls_cert: str) -> DomainCertsInstance: + """ + Update the DomainCertsInstance + + :param tls_cert: Contains the full TLS certificate and private for this domain in PEM format: https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail. Twilio uses this information to process HTTPS traffic sent to your domain. + + :returns: The updated DomainCertsInstance + """ + + data = values.of( + { + "TlsCert": tls_cert, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DomainCertsInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + + async def update_async(self, tls_cert: str) -> DomainCertsInstance: + """ + Asynchronous coroutine to update the DomainCertsInstance + + :param tls_cert: Contains the full TLS certificate and private for this domain in PEM format: https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail. Twilio uses this information to process HTTPS traffic sent to your domain. + + :returns: The updated DomainCertsInstance + """ + + data = values.of( + { + "TlsCert": tls_cert, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DomainCertsInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.DomainCertsContext {}>".format(context) + + +class DomainCertsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the DomainCertsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, domain_sid: str) -> DomainCertsContext: + """ + Constructs a DomainCertsContext + + :param domain_sid: Unique string used to identify the domain that this certificate should be associated with. + """ + return DomainCertsContext(self._version, domain_sid=domain_sid) + + def __call__(self, domain_sid: str) -> DomainCertsContext: + """ + Constructs a DomainCertsContext + + :param domain_sid: Unique string used to identify the domain that this certificate should be associated with. + """ + return DomainCertsContext(self._version, domain_sid=domain_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.DomainCertsList>" diff --git a/twilio/rest/messaging/v1/domain_config.py b/twilio/rest/messaging/v1/domain_config.py new file mode 100644 index 0000000000..ed70351077 --- /dev/null +++ b/twilio/rest/messaging/v1/domain_config.py @@ -0,0 +1,339 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class DomainConfigInstance(InstanceResource): + """ + :ivar domain_sid: The unique string that we created to identify the Domain resource. + :ivar config_sid: The unique string that we created to identify the Domain config (prefix ZK). + :ivar fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + :ivar callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links. + :ivar continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service + :ivar date_created: Date this Domain Config was created. + :ivar date_updated: Date that this Domain Config was last updated. + :ivar url: + :ivar disable_https: Customer's choice to send links with/without \"https://\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + domain_sid: Optional[str] = None, + ): + super().__init__(version) + + self.domain_sid: Optional[str] = payload.get("domain_sid") + self.config_sid: Optional[str] = payload.get("config_sid") + self.fallback_url: Optional[str] = payload.get("fallback_url") + self.callback_url: Optional[str] = payload.get("callback_url") + self.continue_on_failure: Optional[bool] = payload.get("continue_on_failure") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.disable_https: Optional[bool] = payload.get("disable_https") + + self._solution = { + "domain_sid": domain_sid or self.domain_sid, + } + self._context: Optional[DomainConfigContext] = None + + @property + def _proxy(self) -> "DomainConfigContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DomainConfigContext for this DomainConfigInstance + """ + if self._context is None: + self._context = DomainConfigContext( + self._version, + domain_sid=self._solution["domain_sid"], + ) + return self._context + + def fetch(self) -> "DomainConfigInstance": + """ + Fetch the DomainConfigInstance + + + :returns: The fetched DomainConfigInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DomainConfigInstance": + """ + Asynchronous coroutine to fetch the DomainConfigInstance + + + :returns: The fetched DomainConfigInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + fallback_url: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + continue_on_failure: Union[bool, object] = values.unset, + disable_https: Union[bool, object] = values.unset, + ) -> "DomainConfigInstance": + """ + Update the DomainConfigInstance + + :param fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + :param callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links + :param continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service + :param disable_https: Customer's choice to send links with/without \\\"https://\\\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. + + :returns: The updated DomainConfigInstance + """ + return self._proxy.update( + fallback_url=fallback_url, + callback_url=callback_url, + continue_on_failure=continue_on_failure, + disable_https=disable_https, + ) + + async def update_async( + self, + fallback_url: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + continue_on_failure: Union[bool, object] = values.unset, + disable_https: Union[bool, object] = values.unset, + ) -> "DomainConfigInstance": + """ + Asynchronous coroutine to update the DomainConfigInstance + + :param fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + :param callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links + :param continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service + :param disable_https: Customer's choice to send links with/without \\\"https://\\\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. + + :returns: The updated DomainConfigInstance + """ + return await self._proxy.update_async( + fallback_url=fallback_url, + callback_url=callback_url, + continue_on_failure=continue_on_failure, + disable_https=disable_https, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.DomainConfigInstance {}>".format(context) + + +class DomainConfigContext(InstanceContext): + + def __init__(self, version: Version, domain_sid: str): + """ + Initialize the DomainConfigContext + + :param version: Version that contains the resource + :param domain_sid: Unique string used to identify the domain that this config should be associated with. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "domain_sid": domain_sid, + } + self._uri = "/LinkShortening/Domains/{domain_sid}/Config".format( + **self._solution + ) + + def fetch(self) -> DomainConfigInstance: + """ + Fetch the DomainConfigInstance + + + :returns: The fetched DomainConfigInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DomainConfigInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + + async def fetch_async(self) -> DomainConfigInstance: + """ + Asynchronous coroutine to fetch the DomainConfigInstance + + + :returns: The fetched DomainConfigInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DomainConfigInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + ) + + def update( + self, + fallback_url: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + continue_on_failure: Union[bool, object] = values.unset, + disable_https: Union[bool, object] = values.unset, + ) -> DomainConfigInstance: + """ + Update the DomainConfigInstance + + :param fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + :param callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links + :param continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service + :param disable_https: Customer's choice to send links with/without \\\"https://\\\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. + + :returns: The updated DomainConfigInstance + """ + + data = values.of( + { + "FallbackUrl": fallback_url, + "CallbackUrl": callback_url, + "ContinueOnFailure": serialize.boolean_to_string(continue_on_failure), + "DisableHttps": serialize.boolean_to_string(disable_https), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DomainConfigInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + + async def update_async( + self, + fallback_url: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + continue_on_failure: Union[bool, object] = values.unset, + disable_https: Union[bool, object] = values.unset, + ) -> DomainConfigInstance: + """ + Asynchronous coroutine to update the DomainConfigInstance + + :param fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + :param callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links + :param continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service + :param disable_https: Customer's choice to send links with/without \\\"https://\\\" attached to shortened url. If true, messages will not be sent with https:// at the beginning of the url. If false, messages will be sent with https:// at the beginning of the url. False is the default behavior if it is not specified. + + :returns: The updated DomainConfigInstance + """ + + data = values.of( + { + "FallbackUrl": fallback_url, + "CallbackUrl": callback_url, + "ContinueOnFailure": serialize.boolean_to_string(continue_on_failure), + "DisableHttps": serialize.boolean_to_string(disable_https), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DomainConfigInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.DomainConfigContext {}>".format(context) + + +class DomainConfigList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the DomainConfigList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, domain_sid: str) -> DomainConfigContext: + """ + Constructs a DomainConfigContext + + :param domain_sid: Unique string used to identify the domain that this config should be associated with. + """ + return DomainConfigContext(self._version, domain_sid=domain_sid) + + def __call__(self, domain_sid: str) -> DomainConfigContext: + """ + Constructs a DomainConfigContext + + :param domain_sid: Unique string used to identify the domain that this config should be associated with. + """ + return DomainConfigContext(self._version, domain_sid=domain_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.DomainConfigList>" diff --git a/twilio/rest/messaging/v1/domain_config_messaging_service.py b/twilio/rest/messaging/v1/domain_config_messaging_service.py new file mode 100644 index 0000000000..2bcd4aa88c --- /dev/null +++ b/twilio/rest/messaging/v1/domain_config_messaging_service.py @@ -0,0 +1,222 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class DomainConfigMessagingServiceInstance(InstanceResource): + """ + :ivar domain_sid: The unique string that we created to identify the Domain resource. + :ivar config_sid: The unique string that we created to identify the Domain config (prefix ZK). + :ivar messaging_service_sid: The unique string that identifies the messaging service + :ivar fallback_url: Any requests we receive to this domain that do not match an existing shortened message will be redirected to the fallback url. These will likely be either expired messages, random misdirected traffic, or intentional scraping. + :ivar callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links. + :ivar continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service + :ivar date_created: Date this Domain Config was created. + :ivar date_updated: Date that this Domain Config was last updated. + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + messaging_service_sid: Optional[str] = None, + ): + super().__init__(version) + + self.domain_sid: Optional[str] = payload.get("domain_sid") + self.config_sid: Optional[str] = payload.get("config_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.fallback_url: Optional[str] = payload.get("fallback_url") + self.callback_url: Optional[str] = payload.get("callback_url") + self.continue_on_failure: Optional[bool] = payload.get("continue_on_failure") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "messaging_service_sid": messaging_service_sid + or self.messaging_service_sid, + } + self._context: Optional[DomainConfigMessagingServiceContext] = None + + @property + def _proxy(self) -> "DomainConfigMessagingServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DomainConfigMessagingServiceContext for this DomainConfigMessagingServiceInstance + """ + if self._context is None: + self._context = DomainConfigMessagingServiceContext( + self._version, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return self._context + + def fetch(self) -> "DomainConfigMessagingServiceInstance": + """ + Fetch the DomainConfigMessagingServiceInstance + + + :returns: The fetched DomainConfigMessagingServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DomainConfigMessagingServiceInstance": + """ + Asynchronous coroutine to fetch the DomainConfigMessagingServiceInstance + + + :returns: The fetched DomainConfigMessagingServiceInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.DomainConfigMessagingServiceInstance {}>".format( + context + ) + + +class DomainConfigMessagingServiceContext(InstanceContext): + + def __init__(self, version: Version, messaging_service_sid: str): + """ + Initialize the DomainConfigMessagingServiceContext + + :param version: Version that contains the resource + :param messaging_service_sid: Unique string used to identify the Messaging service that this domain should be associated with. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "messaging_service_sid": messaging_service_sid, + } + self._uri = "/LinkShortening/MessagingService/{messaging_service_sid}/DomainConfig".format( + **self._solution + ) + + def fetch(self) -> DomainConfigMessagingServiceInstance: + """ + Fetch the DomainConfigMessagingServiceInstance + + + :returns: The fetched DomainConfigMessagingServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DomainConfigMessagingServiceInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + async def fetch_async(self) -> DomainConfigMessagingServiceInstance: + """ + Asynchronous coroutine to fetch the DomainConfigMessagingServiceInstance + + + :returns: The fetched DomainConfigMessagingServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DomainConfigMessagingServiceInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.DomainConfigMessagingServiceContext {}>".format( + context + ) + + +class DomainConfigMessagingServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the DomainConfigMessagingServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, messaging_service_sid: str) -> DomainConfigMessagingServiceContext: + """ + Constructs a DomainConfigMessagingServiceContext + + :param messaging_service_sid: Unique string used to identify the Messaging service that this domain should be associated with. + """ + return DomainConfigMessagingServiceContext( + self._version, messaging_service_sid=messaging_service_sid + ) + + def __call__( + self, messaging_service_sid: str + ) -> DomainConfigMessagingServiceContext: + """ + Constructs a DomainConfigMessagingServiceContext + + :param messaging_service_sid: Unique string used to identify the Messaging service that this domain should be associated with. + """ + return DomainConfigMessagingServiceContext( + self._version, messaging_service_sid=messaging_service_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.DomainConfigMessagingServiceList>" diff --git a/twilio/rest/messaging/v1/external_campaign.py b/twilio/rest/messaging/v1/external_campaign.py new file mode 100644 index 0000000000..eed039a6cc --- /dev/null +++ b/twilio/rest/messaging/v1/external_campaign.py @@ -0,0 +1,143 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ExternalCampaignInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies a US A2P Compliance resource `QE2c6890da8086d771620e9b13fadeba0b`. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the Campaign belongs to. + :ivar campaign_id: ID of the preregistered campaign. + :ivar messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.campaign_id: Optional[str] = payload.get("campaign_id") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Messaging.V1.ExternalCampaignInstance>" + + +class ExternalCampaignList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ExternalCampaignList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services/PreregisteredUsa2p" + + def create( + self, + campaign_id: str, + messaging_service_sid: str, + cnp_migration: Union[bool, object] = values.unset, + ) -> ExternalCampaignInstance: + """ + Create the ExternalCampaignInstance + + :param campaign_id: ID of the preregistered campaign. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. + :param cnp_migration: Customers should use this flag during the ERC registration process to indicate to Twilio that the campaign being registered is undergoing CNP migration. It is important for the user to first trigger the CNP migration process for said campaign in their CSP portal and have Twilio accept the sharing request, before making this api call. + + :returns: The created ExternalCampaignInstance + """ + + data = values.of( + { + "CampaignId": campaign_id, + "MessagingServiceSid": messaging_service_sid, + "CnpMigration": serialize.boolean_to_string(cnp_migration), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExternalCampaignInstance(self._version, payload) + + async def create_async( + self, + campaign_id: str, + messaging_service_sid: str, + cnp_migration: Union[bool, object] = values.unset, + ) -> ExternalCampaignInstance: + """ + Asynchronously create the ExternalCampaignInstance + + :param campaign_id: ID of the preregistered campaign. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. + :param cnp_migration: Customers should use this flag during the ERC registration process to indicate to Twilio that the campaign being registered is undergoing CNP migration. It is important for the user to first trigger the CNP migration process for said campaign in their CSP portal and have Twilio accept the sharing request, before making this api call. + + :returns: The created ExternalCampaignInstance + """ + + data = values.of( + { + "CampaignId": campaign_id, + "MessagingServiceSid": messaging_service_sid, + "CnpMigration": serialize.boolean_to_string(cnp_migration), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExternalCampaignInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.ExternalCampaignList>" diff --git a/twilio/rest/messaging/v1/linkshortening_messaging_service.py b/twilio/rest/messaging/v1/linkshortening_messaging_service.py new file mode 100644 index 0000000000..ac69842a0c --- /dev/null +++ b/twilio/rest/messaging/v1/linkshortening_messaging_service.py @@ -0,0 +1,258 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class LinkshorteningMessagingServiceInstance(InstanceResource): + """ + :ivar domain_sid: The unique string identifies the domain resource + :ivar messaging_service_sid: The unique string that identifies the messaging service + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + domain_sid: Optional[str] = None, + messaging_service_sid: Optional[str] = None, + ): + super().__init__(version) + + self.domain_sid: Optional[str] = payload.get("domain_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "domain_sid": domain_sid or self.domain_sid, + "messaging_service_sid": messaging_service_sid + or self.messaging_service_sid, + } + self._context: Optional[LinkshorteningMessagingServiceContext] = None + + @property + def _proxy(self) -> "LinkshorteningMessagingServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: LinkshorteningMessagingServiceContext for this LinkshorteningMessagingServiceInstance + """ + if self._context is None: + self._context = LinkshorteningMessagingServiceContext( + self._version, + domain_sid=self._solution["domain_sid"], + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return self._context + + def create(self) -> "LinkshorteningMessagingServiceInstance": + """ + Create the LinkshorteningMessagingServiceInstance + + + :returns: The created LinkshorteningMessagingServiceInstance + """ + return self._proxy.create() + + async def create_async(self) -> "LinkshorteningMessagingServiceInstance": + """ + Asynchronous coroutine to create the LinkshorteningMessagingServiceInstance + + + :returns: The created LinkshorteningMessagingServiceInstance + """ + return await self._proxy.create_async() + + def delete(self) -> bool: + """ + Deletes the LinkshorteningMessagingServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the LinkshorteningMessagingServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.LinkshorteningMessagingServiceInstance {}>".format( + context + ) + + +class LinkshorteningMessagingServiceContext(InstanceContext): + + def __init__(self, version: Version, domain_sid: str, messaging_service_sid: str): + """ + Initialize the LinkshorteningMessagingServiceContext + + :param version: Version that contains the resource + :param domain_sid: The domain SID to dissociate from a messaging service. With URL shortening enabled, links in messages sent with the associated messaging service will be shortened to the provided domain + :param messaging_service_sid: A messaging service SID to dissociate from a domain. With URL shortening enabled, links in messages sent with the provided messaging service will be shortened to the associated domain + """ + super().__init__(version) + + # Path Solution + self._solution = { + "domain_sid": domain_sid, + "messaging_service_sid": messaging_service_sid, + } + self._uri = "/LinkShortening/Domains/{domain_sid}/MessagingServices/{messaging_service_sid}".format( + **self._solution + ) + + def create(self) -> LinkshorteningMessagingServiceInstance: + """ + Create the LinkshorteningMessagingServiceInstance + + + :returns: The created LinkshorteningMessagingServiceInstance + """ + data = values.of({}) + + payload = self._version.create(method="POST", uri=self._uri, data=data) + + return LinkshorteningMessagingServiceInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + async def create_async(self) -> LinkshorteningMessagingServiceInstance: + """ + Asynchronous coroutine to create the LinkshorteningMessagingServiceInstance + + + :returns: The created LinkshorteningMessagingServiceInstance + """ + data = values.of({}) + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data + ) + + return LinkshorteningMessagingServiceInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def delete(self) -> bool: + """ + Deletes the LinkshorteningMessagingServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the LinkshorteningMessagingServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.LinkshorteningMessagingServiceContext {}>".format( + context + ) + + +class LinkshorteningMessagingServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the LinkshorteningMessagingServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get( + self, domain_sid: str, messaging_service_sid: str + ) -> LinkshorteningMessagingServiceContext: + """ + Constructs a LinkshorteningMessagingServiceContext + + :param domain_sid: The domain SID to dissociate from a messaging service. With URL shortening enabled, links in messages sent with the associated messaging service will be shortened to the provided domain + :param messaging_service_sid: A messaging service SID to dissociate from a domain. With URL shortening enabled, links in messages sent with the provided messaging service will be shortened to the associated domain + """ + return LinkshorteningMessagingServiceContext( + self._version, + domain_sid=domain_sid, + messaging_service_sid=messaging_service_sid, + ) + + def __call__( + self, domain_sid: str, messaging_service_sid: str + ) -> LinkshorteningMessagingServiceContext: + """ + Constructs a LinkshorteningMessagingServiceContext + + :param domain_sid: The domain SID to dissociate from a messaging service. With URL shortening enabled, links in messages sent with the associated messaging service will be shortened to the provided domain + :param messaging_service_sid: A messaging service SID to dissociate from a domain. With URL shortening enabled, links in messages sent with the provided messaging service will be shortened to the associated domain + """ + return LinkshorteningMessagingServiceContext( + self._version, + domain_sid=domain_sid, + messaging_service_sid=messaging_service_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.LinkshorteningMessagingServiceList>" diff --git a/twilio/rest/messaging/v1/linkshortening_messaging_service_domain_association.py b/twilio/rest/messaging/v1/linkshortening_messaging_service_domain_association.py new file mode 100644 index 0000000000..4c0b52bddf --- /dev/null +++ b/twilio/rest/messaging/v1/linkshortening_messaging_service_domain_association.py @@ -0,0 +1,217 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class LinkshorteningMessagingServiceDomainAssociationInstance(InstanceResource): + """ + :ivar domain_sid: The unique string that we created to identify the Domain resource. + :ivar messaging_service_sid: The unique string that identifies the messaging service + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + messaging_service_sid: Optional[str] = None, + ): + super().__init__(version) + + self.domain_sid: Optional[str] = payload.get("domain_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "messaging_service_sid": messaging_service_sid + or self.messaging_service_sid, + } + self._context: Optional[ + LinkshorteningMessagingServiceDomainAssociationContext + ] = None + + @property + def _proxy(self) -> "LinkshorteningMessagingServiceDomainAssociationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: LinkshorteningMessagingServiceDomainAssociationContext for this LinkshorteningMessagingServiceDomainAssociationInstance + """ + if self._context is None: + self._context = LinkshorteningMessagingServiceDomainAssociationContext( + self._version, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return self._context + + def fetch(self) -> "LinkshorteningMessagingServiceDomainAssociationInstance": + """ + Fetch the LinkshorteningMessagingServiceDomainAssociationInstance + + + :returns: The fetched LinkshorteningMessagingServiceDomainAssociationInstance + """ + return self._proxy.fetch() + + async def fetch_async( + self, + ) -> "LinkshorteningMessagingServiceDomainAssociationInstance": + """ + Asynchronous coroutine to fetch the LinkshorteningMessagingServiceDomainAssociationInstance + + + :returns: The fetched LinkshorteningMessagingServiceDomainAssociationInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.LinkshorteningMessagingServiceDomainAssociationInstance {}>".format( + context + ) + + +class LinkshorteningMessagingServiceDomainAssociationContext(InstanceContext): + + def __init__(self, version: Version, messaging_service_sid: str): + """ + Initialize the LinkshorteningMessagingServiceDomainAssociationContext + + :param version: Version that contains the resource + :param messaging_service_sid: Unique string used to identify the Messaging service that this domain should be associated with. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "messaging_service_sid": messaging_service_sid, + } + self._uri = ( + "/LinkShortening/MessagingServices/{messaging_service_sid}/Domain".format( + **self._solution + ) + ) + + def fetch(self) -> LinkshorteningMessagingServiceDomainAssociationInstance: + """ + Fetch the LinkshorteningMessagingServiceDomainAssociationInstance + + + :returns: The fetched LinkshorteningMessagingServiceDomainAssociationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return LinkshorteningMessagingServiceDomainAssociationInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + async def fetch_async( + self, + ) -> LinkshorteningMessagingServiceDomainAssociationInstance: + """ + Asynchronous coroutine to fetch the LinkshorteningMessagingServiceDomainAssociationInstance + + + :returns: The fetched LinkshorteningMessagingServiceDomainAssociationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return LinkshorteningMessagingServiceDomainAssociationInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.LinkshorteningMessagingServiceDomainAssociationContext {}>".format( + context + ) + + +class LinkshorteningMessagingServiceDomainAssociationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the LinkshorteningMessagingServiceDomainAssociationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get( + self, messaging_service_sid: str + ) -> LinkshorteningMessagingServiceDomainAssociationContext: + """ + Constructs a LinkshorteningMessagingServiceDomainAssociationContext + + :param messaging_service_sid: Unique string used to identify the Messaging service that this domain should be associated with. + """ + return LinkshorteningMessagingServiceDomainAssociationContext( + self._version, messaging_service_sid=messaging_service_sid + ) + + def __call__( + self, messaging_service_sid: str + ) -> LinkshorteningMessagingServiceDomainAssociationContext: + """ + Constructs a LinkshorteningMessagingServiceDomainAssociationContext + + :param messaging_service_sid: Unique string used to identify the Messaging service that this domain should be associated with. + """ + return LinkshorteningMessagingServiceDomainAssociationContext( + self._version, messaging_service_sid=messaging_service_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return ( + "<Twilio.Messaging.V1.LinkshorteningMessagingServiceDomainAssociationList>" + ) diff --git a/twilio/rest/messaging/v1/request_managed_cert.py b/twilio/rest/messaging/v1/request_managed_cert.py new file mode 100644 index 0000000000..81ccf9486c --- /dev/null +++ b/twilio/rest/messaging/v1/request_managed_cert.py @@ -0,0 +1,213 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class RequestManagedCertInstance(InstanceResource): + """ + :ivar domain_sid: The unique string that we created to identify the Domain resource. + :ivar date_updated: Date that this Domain was last updated. + :ivar date_created: Date that this Domain was registered to the Twilio platform to create a new Domain object. + :ivar date_expires: Date that the private certificate associated with this domain expires. This is the expiration date of your existing cert. + :ivar domain_name: Full url path for this domain. + :ivar certificate_sid: The unique string that we created to identify this Certificate resource. + :ivar url: + :ivar managed: A boolean flag indicating if the certificate is managed by Twilio. + :ivar requesting: A boolean flag indicating if a managed certificate needs to be fulfilled by Twilio. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + domain_sid: Optional[str] = None, + ): + super().__init__(version) + + self.domain_sid: Optional[str] = payload.get("domain_sid") + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_expires: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expires") + ) + self.domain_name: Optional[str] = payload.get("domain_name") + self.certificate_sid: Optional[str] = payload.get("certificate_sid") + self.url: Optional[str] = payload.get("url") + self.managed: Optional[bool] = payload.get("managed") + self.requesting: Optional[bool] = payload.get("requesting") + + self._solution = { + "domain_sid": domain_sid or self.domain_sid, + } + self._context: Optional[RequestManagedCertContext] = None + + @property + def _proxy(self) -> "RequestManagedCertContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RequestManagedCertContext for this RequestManagedCertInstance + """ + if self._context is None: + self._context = RequestManagedCertContext( + self._version, + domain_sid=self._solution["domain_sid"], + ) + return self._context + + def update(self) -> "RequestManagedCertInstance": + """ + Update the RequestManagedCertInstance + + + :returns: The updated RequestManagedCertInstance + """ + return self._proxy.update() + + async def update_async(self) -> "RequestManagedCertInstance": + """ + Asynchronous coroutine to update the RequestManagedCertInstance + + + :returns: The updated RequestManagedCertInstance + """ + return await self._proxy.update_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.RequestManagedCertInstance {}>".format(context) + + +class RequestManagedCertContext(InstanceContext): + + def __init__(self, version: Version, domain_sid: str): + """ + Initialize the RequestManagedCertContext + + :param version: Version that contains the resource + :param domain_sid: Unique string used to identify the domain that this certificate should be associated with. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "domain_sid": domain_sid, + } + self._uri = "/LinkShortening/Domains/{domain_sid}/RequestManagedCert".format( + **self._solution + ) + + def update(self) -> RequestManagedCertInstance: + """ + Update the RequestManagedCertInstance + + + :returns: The updated RequestManagedCertInstance + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RequestManagedCertInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + + async def update_async(self) -> RequestManagedCertInstance: + """ + Asynchronous coroutine to update the RequestManagedCertInstance + + + :returns: The updated RequestManagedCertInstance + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RequestManagedCertInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.RequestManagedCertContext {}>".format(context) + + +class RequestManagedCertList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RequestManagedCertList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, domain_sid: str) -> RequestManagedCertContext: + """ + Constructs a RequestManagedCertContext + + :param domain_sid: Unique string used to identify the domain that this certificate should be associated with. + """ + return RequestManagedCertContext(self._version, domain_sid=domain_sid) + + def __call__(self, domain_sid: str) -> RequestManagedCertContext: + """ + Constructs a RequestManagedCertContext + + :param domain_sid: Unique string used to identify the domain that this certificate should be associated with. + """ + return RequestManagedCertContext(self._version, domain_sid=domain_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.RequestManagedCertList>" diff --git a/twilio/rest/messaging/v1/service/__init__.py b/twilio/rest/messaging/v1/service/__init__.py new file mode 100644 index 0000000000..06a53c9a20 --- /dev/null +++ b/twilio/rest/messaging/v1/service/__init__.py @@ -0,0 +1,1115 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.messaging.v1.service.alpha_sender import AlphaSenderList +from twilio.rest.messaging.v1.service.channel_sender import ChannelSenderList +from twilio.rest.messaging.v1.service.destination_alpha_sender import ( + DestinationAlphaSenderList, +) +from twilio.rest.messaging.v1.service.phone_number import PhoneNumberList +from twilio.rest.messaging.v1.service.short_code import ShortCodeList +from twilio.rest.messaging.v1.service.us_app_to_person import UsAppToPersonList +from twilio.rest.messaging.v1.service.us_app_to_person_usecase import ( + UsAppToPersonUsecaseList, +) + + +class ServiceInstance(InstanceResource): + + class ScanMessageContent(object): + INHERIT = "inherit" + ENABLE = "enable" + DISABLE = "disable" + + """ + :ivar sid: The unique string that we created to identify the Service resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :ivar inbound_method: The HTTP method we use to call `inbound_request_url`. Can be `GET` or `POST`. + :ivar fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :ivar fallback_method: The HTTP method we use to call `fallback_url`. Can be: `GET` or `POST`. + :ivar status_callback: The URL we call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :ivar sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :ivar mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :ivar smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :ivar scan_message_content: + :ivar fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :ivar area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :ivar synchronous_validation: Reserved. + :ivar validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. + :ivar url: The absolute URL of the Service resource. + :ivar links: The absolute URLs of related resources. + :ivar usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :ivar us_app_to_person_registered: Whether US A2P campaign is registered for this Service. + :ivar use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.inbound_request_url: Optional[str] = payload.get("inbound_request_url") + self.inbound_method: Optional[str] = payload.get("inbound_method") + self.fallback_url: Optional[str] = payload.get("fallback_url") + self.fallback_method: Optional[str] = payload.get("fallback_method") + self.status_callback: Optional[str] = payload.get("status_callback") + self.sticky_sender: Optional[bool] = payload.get("sticky_sender") + self.mms_converter: Optional[bool] = payload.get("mms_converter") + self.smart_encoding: Optional[bool] = payload.get("smart_encoding") + self.scan_message_content: Optional["ServiceInstance.ScanMessageContent"] = ( + payload.get("scan_message_content") + ) + self.fallback_to_long_code: Optional[bool] = payload.get( + "fallback_to_long_code" + ) + self.area_code_geomatch: Optional[bool] = payload.get("area_code_geomatch") + self.synchronous_validation: Optional[bool] = payload.get( + "synchronous_validation" + ) + self.validity_period: Optional[int] = deserialize.integer( + payload.get("validity_period") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.usecase: Optional[str] = payload.get("usecase") + self.us_app_to_person_registered: Optional[bool] = payload.get( + "us_app_to_person_registered" + ) + self.use_inbound_webhook_on_number: Optional[bool] = payload.get( + "use_inbound_webhook_on_number" + ) + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + inbound_request_url=inbound_request_url, + inbound_method=inbound_method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + sticky_sender=sticky_sender, + mms_converter=mms_converter, + smart_encoding=smart_encoding, + scan_message_content=scan_message_content, + fallback_to_long_code=fallback_to_long_code, + area_code_geomatch=area_code_geomatch, + validity_period=validity_period, + synchronous_validation=synchronous_validation, + usecase=usecase, + use_inbound_webhook_on_number=use_inbound_webhook_on_number, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + inbound_request_url=inbound_request_url, + inbound_method=inbound_method, + fallback_url=fallback_url, + fallback_method=fallback_method, + status_callback=status_callback, + sticky_sender=sticky_sender, + mms_converter=mms_converter, + smart_encoding=smart_encoding, + scan_message_content=scan_message_content, + fallback_to_long_code=fallback_to_long_code, + area_code_geomatch=area_code_geomatch, + validity_period=validity_period, + synchronous_validation=synchronous_validation, + usecase=usecase, + use_inbound_webhook_on_number=use_inbound_webhook_on_number, + ) + + @property + def alpha_senders(self) -> AlphaSenderList: + """ + Access the alpha_senders + """ + return self._proxy.alpha_senders + + @property + def channel_senders(self) -> ChannelSenderList: + """ + Access the channel_senders + """ + return self._proxy.channel_senders + + @property + def destination_alpha_senders(self) -> DestinationAlphaSenderList: + """ + Access the destination_alpha_senders + """ + return self._proxy.destination_alpha_senders + + @property + def phone_numbers(self) -> PhoneNumberList: + """ + Access the phone_numbers + """ + return self._proxy.phone_numbers + + @property + def short_codes(self) -> ShortCodeList: + """ + Access the short_codes + """ + return self._proxy.short_codes + + @property + def us_app_to_person(self) -> UsAppToPersonList: + """ + Access the us_app_to_person + """ + return self._proxy.us_app_to_person + + @property + def us_app_to_person_usecases(self) -> UsAppToPersonUsecaseList: + """ + Access the us_app_to_person_usecases + """ + return self._proxy.us_app_to_person_usecases + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.ServiceInstance {}>".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The SID of the Service resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._alpha_senders: Optional[AlphaSenderList] = None + self._channel_senders: Optional[ChannelSenderList] = None + self._destination_alpha_senders: Optional[DestinationAlphaSenderList] = None + self._phone_numbers: Optional[PhoneNumberList] = None + self._short_codes: Optional[ShortCodeList] = None + self._us_app_to_person: Optional[UsAppToPersonList] = None + self._us_app_to_person_usecases: Optional[UsAppToPersonUsecaseList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "InboundRequestUrl": inbound_request_url, + "InboundMethod": inbound_method, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StickySender": serialize.boolean_to_string(sticky_sender), + "MmsConverter": serialize.boolean_to_string(mms_converter), + "SmartEncoding": serialize.boolean_to_string(smart_encoding), + "ScanMessageContent": scan_message_content, + "FallbackToLongCode": serialize.boolean_to_string( + fallback_to_long_code + ), + "AreaCodeGeomatch": serialize.boolean_to_string(area_code_geomatch), + "ValidityPeriod": validity_period, + "SynchronousValidation": serialize.boolean_to_string( + synchronous_validation + ), + "Usecase": usecase, + "UseInboundWebhookOnNumber": serialize.boolean_to_string( + use_inbound_webhook_on_number + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "InboundRequestUrl": inbound_request_url, + "InboundMethod": inbound_method, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StickySender": serialize.boolean_to_string(sticky_sender), + "MmsConverter": serialize.boolean_to_string(mms_converter), + "SmartEncoding": serialize.boolean_to_string(smart_encoding), + "ScanMessageContent": scan_message_content, + "FallbackToLongCode": serialize.boolean_to_string( + fallback_to_long_code + ), + "AreaCodeGeomatch": serialize.boolean_to_string(area_code_geomatch), + "ValidityPeriod": validity_period, + "SynchronousValidation": serialize.boolean_to_string( + synchronous_validation + ), + "Usecase": usecase, + "UseInboundWebhookOnNumber": serialize.boolean_to_string( + use_inbound_webhook_on_number + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def alpha_senders(self) -> AlphaSenderList: + """ + Access the alpha_senders + """ + if self._alpha_senders is None: + self._alpha_senders = AlphaSenderList( + self._version, + self._solution["sid"], + ) + return self._alpha_senders + + @property + def channel_senders(self) -> ChannelSenderList: + """ + Access the channel_senders + """ + if self._channel_senders is None: + self._channel_senders = ChannelSenderList( + self._version, + self._solution["sid"], + ) + return self._channel_senders + + @property + def destination_alpha_senders(self) -> DestinationAlphaSenderList: + """ + Access the destination_alpha_senders + """ + if self._destination_alpha_senders is None: + self._destination_alpha_senders = DestinationAlphaSenderList( + self._version, + self._solution["sid"], + ) + return self._destination_alpha_senders + + @property + def phone_numbers(self) -> PhoneNumberList: + """ + Access the phone_numbers + """ + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList( + self._version, + self._solution["sid"], + ) + return self._phone_numbers + + @property + def short_codes(self) -> ShortCodeList: + """ + Access the short_codes + """ + if self._short_codes is None: + self._short_codes = ShortCodeList( + self._version, + self._solution["sid"], + ) + return self._short_codes + + @property + def us_app_to_person(self) -> UsAppToPersonList: + """ + Access the us_app_to_person + """ + if self._us_app_to_person is None: + self._us_app_to_person = UsAppToPersonList( + self._version, + self._solution["sid"], + ) + return self._us_app_to_person + + @property + def us_app_to_person_usecases(self) -> UsAppToPersonUsecaseList: + """ + Access the us_app_to_person_usecases + """ + if self._us_app_to_person_usecases is None: + self._us_app_to_person_usecases = UsAppToPersonUsecaseList( + self._version, + self._solution["sid"], + ) + return self._us_app_to_person_usecases + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.ServiceContext {}>".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.ServicePage>" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create( + self, + friendly_name: str, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "InboundRequestUrl": inbound_request_url, + "InboundMethod": inbound_method, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StickySender": serialize.boolean_to_string(sticky_sender), + "MmsConverter": serialize.boolean_to_string(mms_converter), + "SmartEncoding": serialize.boolean_to_string(smart_encoding), + "ScanMessageContent": scan_message_content, + "FallbackToLongCode": serialize.boolean_to_string( + fallback_to_long_code + ), + "AreaCodeGeomatch": serialize.boolean_to_string(area_code_geomatch), + "ValidityPeriod": validity_period, + "SynchronousValidation": serialize.boolean_to_string( + synchronous_validation + ), + "Usecase": usecase, + "UseInboundWebhookOnNumber": serialize.boolean_to_string( + use_inbound_webhook_on_number + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + inbound_request_url: Union[str, object] = values.unset, + inbound_method: Union[str, object] = values.unset, + fallback_url: Union[str, object] = values.unset, + fallback_method: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + sticky_sender: Union[bool, object] = values.unset, + mms_converter: Union[bool, object] = values.unset, + smart_encoding: Union[bool, object] = values.unset, + scan_message_content: Union[ + "ServiceInstance.ScanMessageContent", object + ] = values.unset, + fallback_to_long_code: Union[bool, object] = values.unset, + area_code_geomatch: Union[bool, object] = values.unset, + validity_period: Union[int, object] = values.unset, + synchronous_validation: Union[bool, object] = values.unset, + usecase: Union[str, object] = values.unset, + use_inbound_webhook_on_number: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param inbound_request_url: The URL we call using `inbound_method` when a message is received by any phone number or short code in the Service. When this property is `null`, receiving inbound messages is disabled. All messages sent to the Twilio phone number or short code will not be logged and received on the Account. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `inbound_request_url` defined for the Messaging Service. + :param inbound_method: The HTTP method we should use to call `inbound_request_url`. Can be `GET` or `POST` and the default is `POST`. + :param fallback_url: The URL that we call using `fallback_method` if an error occurs while retrieving or executing the TwiML from the Inbound Request URL. If the `use_inbound_webhook_on_number` field is enabled then the webhook url defined on the phone number will override the `fallback_url` defined for the Messaging Service. + :param fallback_method: The HTTP method we should use to call `fallback_url`. Can be: `GET` or `POST`. + :param status_callback: The URL we should call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. + :param sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. + :param scan_message_content: + :param fallback_to_long_code: [OBSOLETE] Former feature used to fallback to long code sender after certain short code message failures. + :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/messaging/services#area-code-geomatch) on the Service Instance. + :param validity_period: How long, in seconds, messages sent from the Service are valid. Can be an integer from `1` to `14,400`. Default value is `14,400`. + :param synchronous_validation: Reserved. + :param usecase: A string that describes the scenario in which the Messaging Service will be used. Possible values are `notifications`, `marketing`, `verification`, `discussion`, `poll`, `undeclared`. + :param use_inbound_webhook_on_number: A boolean value that indicates either the webhook url configured on the phone number will be used or `inbound_request_url`/`fallback_url` url will be called when a message is received from the phone number. If this field is enabled then the webhook url defined on the phone number will override the `inbound_request_url`/`fallback_url` defined for the Messaging Service. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "InboundRequestUrl": inbound_request_url, + "InboundMethod": inbound_method, + "FallbackUrl": fallback_url, + "FallbackMethod": fallback_method, + "StatusCallback": status_callback, + "StickySender": serialize.boolean_to_string(sticky_sender), + "MmsConverter": serialize.boolean_to_string(mms_converter), + "SmartEncoding": serialize.boolean_to_string(smart_encoding), + "ScanMessageContent": scan_message_content, + "FallbackToLongCode": serialize.boolean_to_string( + fallback_to_long_code + ), + "AreaCodeGeomatch": serialize.boolean_to_string(area_code_geomatch), + "ValidityPeriod": validity_period, + "SynchronousValidation": serialize.boolean_to_string( + synchronous_validation + ), + "Usecase": usecase, + "UseInboundWebhookOnNumber": serialize.boolean_to_string( + use_inbound_webhook_on_number + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The SID of the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The SID of the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.ServiceList>" diff --git a/twilio/rest/messaging/v1/service/alpha_sender.py b/twilio/rest/messaging/v1/service/alpha_sender.py new file mode 100644 index 0000000000..2ba4c2a45c --- /dev/null +++ b/twilio/rest/messaging/v1/service/alpha_sender.py @@ -0,0 +1,542 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AlphaSenderInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the AlphaSender resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AlphaSender resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the resource is associated with. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar alpha_sender: The Alphanumeric Sender ID string. + :ivar capabilities: An array of values that describe whether the number can receive calls or messages. Can be: `SMS`. + :ivar url: The absolute URL of the AlphaSender resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.alpha_sender: Optional[str] = payload.get("alpha_sender") + self.capabilities: Optional[List[str]] = payload.get("capabilities") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[AlphaSenderContext] = None + + @property + def _proxy(self) -> "AlphaSenderContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AlphaSenderContext for this AlphaSenderInstance + """ + if self._context is None: + self._context = AlphaSenderContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AlphaSenderInstance": + """ + Fetch the AlphaSenderInstance + + + :returns: The fetched AlphaSenderInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AlphaSenderInstance": + """ + Asynchronous coroutine to fetch the AlphaSenderInstance + + + :returns: The fetched AlphaSenderInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.AlphaSenderInstance {}>".format(context) + + +class AlphaSenderContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the AlphaSenderContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the resource from. + :param sid: The SID of the AlphaSender resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/AlphaSenders/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the AlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AlphaSenderInstance: + """ + Fetch the AlphaSenderInstance + + + :returns: The fetched AlphaSenderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AlphaSenderInstance: + """ + Asynchronous coroutine to fetch the AlphaSenderInstance + + + :returns: The fetched AlphaSenderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.AlphaSenderContext {}>".format(context) + + +class AlphaSenderPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AlphaSenderInstance: + """ + Build an instance of AlphaSenderInstance + + :param payload: Payload response from the API + """ + return AlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.AlphaSenderPage>" + + +class AlphaSenderList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the AlphaSenderList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/AlphaSenders".format(**self._solution) + + def create(self, alpha_sender: str) -> AlphaSenderInstance: + """ + Create the AlphaSenderInstance + + :param alpha_sender: The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. + + :returns: The created AlphaSenderInstance + """ + + data = values.of( + { + "AlphaSender": alpha_sender, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async(self, alpha_sender: str) -> AlphaSenderInstance: + """ + Asynchronously create the AlphaSenderInstance + + :param alpha_sender: The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. + + :returns: The created AlphaSenderInstance + """ + + data = values.of( + { + "AlphaSender": alpha_sender, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AlphaSenderInstance]: + """ + Streams AlphaSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AlphaSenderInstance]: + """ + Asynchronously streams AlphaSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AlphaSenderInstance]: + """ + Lists AlphaSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AlphaSenderInstance]: + """ + Asynchronously lists AlphaSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AlphaSenderPage: + """ + Retrieve a single page of AlphaSenderInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AlphaSenderInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AlphaSenderPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AlphaSenderPage: + """ + Asynchronously retrieve a single page of AlphaSenderInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AlphaSenderInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AlphaSenderPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AlphaSenderPage: + """ + Retrieve a specific page of AlphaSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AlphaSenderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AlphaSenderPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AlphaSenderPage: + """ + Asynchronously retrieve a specific page of AlphaSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AlphaSenderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AlphaSenderPage(self._version, response, self._solution) + + def get(self, sid: str) -> AlphaSenderContext: + """ + Constructs a AlphaSenderContext + + :param sid: The SID of the AlphaSender resource to fetch. + """ + return AlphaSenderContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> AlphaSenderContext: + """ + Constructs a AlphaSenderContext + + :param sid: The SID of the AlphaSender resource to fetch. + """ + return AlphaSenderContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.AlphaSenderList>" diff --git a/twilio/rest/messaging/v1/service/channel_sender.py b/twilio/rest/messaging/v1/service/channel_sender.py new file mode 100644 index 0000000000..9d708a2fba --- /dev/null +++ b/twilio/rest/messaging/v1/service/channel_sender.py @@ -0,0 +1,556 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ChannelSenderInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ChannelSender resource. + :ivar messaging_service_sid: The SID of the [Service](https://www.twilio.com/docs/messaging/services) the resource is associated with. + :ivar sid: The unique string that we created to identify the ChannelSender resource. + :ivar sender: The unique string that identifies the sender e.g whatsapp:+123456XXXX. + :ivar sender_type: A string value that identifies the sender type e.g WhatsApp, Messenger. + :ivar country_code: The 2-character [ISO Country Code](https://www.iso.org/iso-3166-country-codes.html) of the number. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the ChannelSender resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + messaging_service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.sid: Optional[str] = payload.get("sid") + self.sender: Optional[str] = payload.get("sender") + self.sender_type: Optional[str] = payload.get("sender_type") + self.country_code: Optional[str] = payload.get("country_code") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "messaging_service_sid": messaging_service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ChannelSenderContext] = None + + @property + def _proxy(self) -> "ChannelSenderContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ChannelSenderContext for this ChannelSenderInstance + """ + if self._context is None: + self._context = ChannelSenderContext( + self._version, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ChannelSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ChannelSenderInstance": + """ + Fetch the ChannelSenderInstance + + + :returns: The fetched ChannelSenderInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ChannelSenderInstance": + """ + Asynchronous coroutine to fetch the ChannelSenderInstance + + + :returns: The fetched ChannelSenderInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.ChannelSenderInstance {}>".format(context) + + +class ChannelSenderContext(InstanceContext): + + def __init__(self, version: Version, messaging_service_sid: str, sid: str): + """ + Initialize the ChannelSenderContext + + :param version: Version that contains the resource + :param messaging_service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the resource from. + :param sid: The SID of the ChannelSender resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "messaging_service_sid": messaging_service_sid, + "sid": sid, + } + self._uri = "/Services/{messaging_service_sid}/ChannelSenders/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the ChannelSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelSenderInstance: + """ + Fetch the ChannelSenderInstance + + + :returns: The fetched ChannelSenderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ChannelSenderInstance: + """ + Asynchronous coroutine to fetch the ChannelSenderInstance + + + :returns: The fetched ChannelSenderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.ChannelSenderContext {}>".format(context) + + +class ChannelSenderPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChannelSenderInstance: + """ + Build an instance of ChannelSenderInstance + + :param payload: Payload response from the API + """ + return ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.ChannelSenderPage>" + + +class ChannelSenderList(ListResource): + + def __init__(self, version: Version, messaging_service_sid: str): + """ + Initialize the ChannelSenderList + + :param version: Version that contains the resource + :param messaging_service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "messaging_service_sid": messaging_service_sid, + } + self._uri = "/Services/{messaging_service_sid}/ChannelSenders".format( + **self._solution + ) + + def create(self, sid: str) -> ChannelSenderInstance: + """ + Create the ChannelSenderInstance + + :param sid: The SID of the Channel Sender being added to the Service. + + :returns: The created ChannelSenderInstance + """ + + data = values.of( + { + "Sid": sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + async def create_async(self, sid: str) -> ChannelSenderInstance: + """ + Asynchronously create the ChannelSenderInstance + + :param sid: The SID of the Channel Sender being added to the Service. + + :returns: The created ChannelSenderInstance + """ + + data = values.of( + { + "Sid": sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelSenderInstance]: + """ + Streams ChannelSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChannelSenderInstance]: + """ + Asynchronously streams ChannelSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelSenderInstance]: + """ + Lists ChannelSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelSenderInstance]: + """ + Asynchronously lists ChannelSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelSenderPage: + """ + Retrieve a single page of ChannelSenderInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelSenderInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelSenderPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelSenderPage: + """ + Asynchronously retrieve a single page of ChannelSenderInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelSenderInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelSenderPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ChannelSenderPage: + """ + Retrieve a specific page of ChannelSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelSenderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChannelSenderPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ChannelSenderPage: + """ + Asynchronously retrieve a specific page of ChannelSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelSenderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelSenderPage(self._version, response, self._solution) + + def get(self, sid: str) -> ChannelSenderContext: + """ + Constructs a ChannelSenderContext + + :param sid: The SID of the ChannelSender resource to fetch. + """ + return ChannelSenderContext( + self._version, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ChannelSenderContext: + """ + Constructs a ChannelSenderContext + + :param sid: The SID of the ChannelSender resource to fetch. + """ + return ChannelSenderContext( + self._version, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.ChannelSenderList>" diff --git a/twilio/rest/messaging/v1/service/destination_alpha_sender.py b/twilio/rest/messaging/v1/service/destination_alpha_sender.py new file mode 100644 index 0000000000..244d906cae --- /dev/null +++ b/twilio/rest/messaging/v1/service/destination_alpha_sender.py @@ -0,0 +1,574 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DestinationAlphaSenderInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the AlphaSender resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AlphaSender resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the resource is associated with. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar alpha_sender: The Alphanumeric Sender ID string. + :ivar capabilities: An array of values that describe whether the number can receive calls or messages. Can be: `SMS`. + :ivar url: The absolute URL of the AlphaSender resource. + :ivar iso_country_code: The Two Character ISO Country Code the Alphanumeric Sender ID will be used for. For Default Alpha Senders that work across countries, this value will be an empty string + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.alpha_sender: Optional[str] = payload.get("alpha_sender") + self.capabilities: Optional[List[str]] = payload.get("capabilities") + self.url: Optional[str] = payload.get("url") + self.iso_country_code: Optional[str] = payload.get("iso_country_code") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[DestinationAlphaSenderContext] = None + + @property + def _proxy(self) -> "DestinationAlphaSenderContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DestinationAlphaSenderContext for this DestinationAlphaSenderInstance + """ + if self._context is None: + self._context = DestinationAlphaSenderContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the DestinationAlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DestinationAlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "DestinationAlphaSenderInstance": + """ + Fetch the DestinationAlphaSenderInstance + + + :returns: The fetched DestinationAlphaSenderInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DestinationAlphaSenderInstance": + """ + Asynchronous coroutine to fetch the DestinationAlphaSenderInstance + + + :returns: The fetched DestinationAlphaSenderInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.DestinationAlphaSenderInstance {}>".format(context) + + +class DestinationAlphaSenderContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the DestinationAlphaSenderContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the resource from. + :param sid: The SID of the AlphaSender resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/DestinationAlphaSenders/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the DestinationAlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DestinationAlphaSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> DestinationAlphaSenderInstance: + """ + Fetch the DestinationAlphaSenderInstance + + + :returns: The fetched DestinationAlphaSenderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DestinationAlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> DestinationAlphaSenderInstance: + """ + Asynchronous coroutine to fetch the DestinationAlphaSenderInstance + + + :returns: The fetched DestinationAlphaSenderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DestinationAlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.DestinationAlphaSenderContext {}>".format(context) + + +class DestinationAlphaSenderPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DestinationAlphaSenderInstance: + """ + Build an instance of DestinationAlphaSenderInstance + + :param payload: Payload response from the API + """ + return DestinationAlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.DestinationAlphaSenderPage>" + + +class DestinationAlphaSenderList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the DestinationAlphaSenderList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/DestinationAlphaSenders".format( + **self._solution + ) + + def create( + self, alpha_sender: str, iso_country_code: Union[str, object] = values.unset + ) -> DestinationAlphaSenderInstance: + """ + Create the DestinationAlphaSenderInstance + + :param alpha_sender: The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. + :param iso_country_code: The Optional Two Character ISO Country Code the Alphanumeric Sender ID will be used for. If the IsoCountryCode is not provided, a default Alpha Sender will be created that can be used across all countries. + + :returns: The created DestinationAlphaSenderInstance + """ + + data = values.of( + { + "AlphaSender": alpha_sender, + "IsoCountryCode": iso_country_code, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DestinationAlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, alpha_sender: str, iso_country_code: Union[str, object] = values.unset + ) -> DestinationAlphaSenderInstance: + """ + Asynchronously create the DestinationAlphaSenderInstance + + :param alpha_sender: The Alphanumeric Sender ID string. Can be up to 11 characters long. Valid characters are A-Z, a-z, 0-9, space, hyphen `-`, plus `+`, underscore `_` and ampersand `&`. This value cannot contain only numbers. + :param iso_country_code: The Optional Two Character ISO Country Code the Alphanumeric Sender ID will be used for. If the IsoCountryCode is not provided, a default Alpha Sender will be created that can be used across all countries. + + :returns: The created DestinationAlphaSenderInstance + """ + + data = values.of( + { + "AlphaSender": alpha_sender, + "IsoCountryCode": iso_country_code, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DestinationAlphaSenderInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + iso_country_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DestinationAlphaSenderInstance]: + """ + Streams DestinationAlphaSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + iso_country_code=iso_country_code, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + iso_country_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DestinationAlphaSenderInstance]: + """ + Asynchronously streams DestinationAlphaSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + iso_country_code=iso_country_code, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + iso_country_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DestinationAlphaSenderInstance]: + """ + Lists DestinationAlphaSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + iso_country_code=iso_country_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + iso_country_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DestinationAlphaSenderInstance]: + """ + Asynchronously lists DestinationAlphaSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + iso_country_code=iso_country_code, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + iso_country_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DestinationAlphaSenderPage: + """ + Retrieve a single page of DestinationAlphaSenderInstance records from the API. + Request is executed immediately + + :param iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DestinationAlphaSenderInstance + """ + data = values.of( + { + "IsoCountryCode": iso_country_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DestinationAlphaSenderPage(self._version, response, self._solution) + + async def page_async( + self, + iso_country_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DestinationAlphaSenderPage: + """ + Asynchronously retrieve a single page of DestinationAlphaSenderInstance records from the API. + Request is executed immediately + + :param iso_country_code: Optional filter to return only alphanumeric sender IDs associated with the specified two-character ISO country code. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DestinationAlphaSenderInstance + """ + data = values.of( + { + "IsoCountryCode": iso_country_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DestinationAlphaSenderPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DestinationAlphaSenderPage: + """ + Retrieve a specific page of DestinationAlphaSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DestinationAlphaSenderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DestinationAlphaSenderPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DestinationAlphaSenderPage: + """ + Asynchronously retrieve a specific page of DestinationAlphaSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DestinationAlphaSenderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DestinationAlphaSenderPage(self._version, response, self._solution) + + def get(self, sid: str) -> DestinationAlphaSenderContext: + """ + Constructs a DestinationAlphaSenderContext + + :param sid: The SID of the AlphaSender resource to fetch. + """ + return DestinationAlphaSenderContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> DestinationAlphaSenderContext: + """ + Constructs a DestinationAlphaSenderContext + + :param sid: The SID of the AlphaSender resource to fetch. + """ + return DestinationAlphaSenderContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.DestinationAlphaSenderList>" diff --git a/twilio/rest/messaging/v1/service/phone_number.py b/twilio/rest/messaging/v1/service/phone_number.py new file mode 100644 index 0000000000..11b806583e --- /dev/null +++ b/twilio/rest/messaging/v1/service/phone_number.py @@ -0,0 +1,544 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PhoneNumberInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the PhoneNumber resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the PhoneNumber resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the resource is associated with. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar country_code: The 2-character [ISO Country Code](https://www.iso.org/iso-3166-country-codes.html) of the number. + :ivar capabilities: An array of values that describe whether the number can receive calls or messages. Can be: `Voice`, `SMS`, and `MMS`. + :ivar url: The absolute URL of the PhoneNumber resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.phone_number: Optional[str] = payload.get("phone_number") + self.country_code: Optional[str] = payload.get("country_code") + self.capabilities: Optional[List[str]] = payload.get("capabilities") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[PhoneNumberContext] = None + + @property + def _proxy(self) -> "PhoneNumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PhoneNumberContext for this PhoneNumberInstance + """ + if self._context is None: + self._context = PhoneNumberContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "PhoneNumberInstance": + """ + Fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.PhoneNumberInstance {}>".format(context) + + +class PhoneNumberContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the PhoneNumberContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the resource from. + :param sid: The SID of the PhoneNumber resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/PhoneNumbers/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.PhoneNumberContext {}>".format(context) + + +class PhoneNumberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: + """ + Build an instance of PhoneNumberInstance + + :param payload: Payload response from the API + """ + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.PhoneNumberPage>" + + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the PhoneNumberList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/PhoneNumbers".format(**self._solution) + + def create(self, phone_number_sid: str) -> PhoneNumberInstance: + """ + Create the PhoneNumberInstance + + :param phone_number_sid: The SID of the Phone Number being added to the Service. + + :returns: The created PhoneNumberInstance + """ + + data = values.of( + { + "PhoneNumberSid": phone_number_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async(self, phone_number_sid: str) -> PhoneNumberInstance: + """ + Asynchronously create the PhoneNumberInstance + + :param phone_number_sid: The SID of the Phone Number being added to the Service. + + :returns: The created PhoneNumberInstance + """ + + data = values.of( + { + "PhoneNumberSid": phone_number_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PhoneNumberInstance]: + """ + Streams PhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PhoneNumberInstance]: + """ + Asynchronously streams PhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PhoneNumberInstance]: + """ + Lists PhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PhoneNumberInstance]: + """ + Asynchronously lists PhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PhoneNumberPage: + """ + Retrieve a single page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PhoneNumberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PhoneNumberPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PhoneNumberPage: + """ + Asynchronously retrieve a single page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PhoneNumberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PhoneNumberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> PhoneNumberPage: + """ + Retrieve a specific page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PhoneNumberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PhoneNumberPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> PhoneNumberPage: + """ + Asynchronously retrieve a specific page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PhoneNumberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PhoneNumberPage(self._version, response, self._solution) + + def get(self, sid: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param sid: The SID of the PhoneNumber resource to fetch. + """ + return PhoneNumberContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param sid: The SID of the PhoneNumber resource to fetch. + """ + return PhoneNumberContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.PhoneNumberList>" diff --git a/twilio/rest/messaging/v1/service/short_code.py b/twilio/rest/messaging/v1/service/short_code.py new file mode 100644 index 0000000000..172c78dbb9 --- /dev/null +++ b/twilio/rest/messaging/v1/service/short_code.py @@ -0,0 +1,542 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ShortCodeInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the ShortCode resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ShortCode resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) the resource is associated with. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar short_code: The [E.164](https://www.twilio.com/docs/glossary/what-e164) format of the short code. + :ivar country_code: The 2-character [ISO Country Code](https://www.iso.org/iso-3166-country-codes.html) of the number. + :ivar capabilities: An array of values that describe whether the number can receive calls or messages. Can be: `SMS` and `MMS`. + :ivar url: The absolute URL of the ShortCode resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.short_code: Optional[str] = payload.get("short_code") + self.country_code: Optional[str] = payload.get("country_code") + self.capabilities: Optional[List[str]] = payload.get("capabilities") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ShortCodeContext] = None + + @property + def _proxy(self) -> "ShortCodeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ShortCodeContext for this ShortCodeInstance + """ + if self._context is None: + self._context = ShortCodeContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ShortCodeInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ShortCodeInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ShortCodeInstance": + """ + Fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ShortCodeInstance": + """ + Asynchronous coroutine to fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.ShortCodeInstance {}>".format(context) + + +class ShortCodeContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the ShortCodeContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to fetch the resource from. + :param sid: The SID of the ShortCode resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/ShortCodes/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the ShortCodeInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ShortCodeInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ShortCodeInstance: + """ + Fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ShortCodeInstance: + """ + Asynchronous coroutine to fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.ShortCodeContext {}>".format(context) + + +class ShortCodePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ShortCodeInstance: + """ + Build an instance of ShortCodeInstance + + :param payload: Payload response from the API + """ + return ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.ShortCodePage>" + + +class ShortCodeList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ShortCodeList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/chat/rest/service-resource) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/ShortCodes".format(**self._solution) + + def create(self, short_code_sid: str) -> ShortCodeInstance: + """ + Create the ShortCodeInstance + + :param short_code_sid: The SID of the ShortCode resource being added to the Service. + + :returns: The created ShortCodeInstance + """ + + data = values.of( + { + "ShortCodeSid": short_code_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async(self, short_code_sid: str) -> ShortCodeInstance: + """ + Asynchronously create the ShortCodeInstance + + :param short_code_sid: The SID of the ShortCode resource being added to the Service. + + :returns: The created ShortCodeInstance + """ + + data = values.of( + { + "ShortCodeSid": short_code_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ShortCodeInstance]: + """ + Streams ShortCodeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ShortCodeInstance]: + """ + Asynchronously streams ShortCodeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ShortCodeInstance]: + """ + Lists ShortCodeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ShortCodeInstance]: + """ + Asynchronously lists ShortCodeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ShortCodePage: + """ + Retrieve a single page of ShortCodeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ShortCodeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ShortCodePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ShortCodePage: + """ + Asynchronously retrieve a single page of ShortCodeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ShortCodeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ShortCodePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ShortCodePage: + """ + Retrieve a specific page of ShortCodeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ShortCodeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ShortCodePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ShortCodePage: + """ + Asynchronously retrieve a specific page of ShortCodeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ShortCodeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ShortCodePage(self._version, response, self._solution) + + def get(self, sid: str) -> ShortCodeContext: + """ + Constructs a ShortCodeContext + + :param sid: The SID of the ShortCode resource to fetch. + """ + return ShortCodeContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ShortCodeContext: + """ + Constructs a ShortCodeContext + + :param sid: The SID of the ShortCode resource to fetch. + """ + return ShortCodeContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.ShortCodeList>" diff --git a/twilio/rest/messaging/v1/service/us_app_to_person.py b/twilio/rest/messaging/v1/service/us_app_to_person.py new file mode 100644 index 0000000000..dd451f5c59 --- /dev/null +++ b/twilio/rest/messaging/v1/service/us_app_to_person.py @@ -0,0 +1,866 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UsAppToPersonInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies a US A2P Compliance resource `QE2c6890da8086d771620e9b13fadeba0b`. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the Campaign belongs to. + :ivar brand_registration_sid: The unique string to identify the A2P brand. + :ivar messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. + :ivar description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :ivar message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :ivar us_app_to_person_usecase: A2P Campaign Use Case. Examples: [ 2FA, EMERGENCY, MARKETING, SOLE_PROPRIETOR...]. SOLE_PROPRIETOR campaign use cases can only be created by SOLE_PROPRIETOR Brands, and there can only be one SOLE_PROPRIETOR campaign created per SOLE_PROPRIETOR Brand. + :ivar has_embedded_links: Indicate that this SMS campaign will send messages that contain links. + :ivar has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :ivar subscriber_opt_in: A boolean that specifies whether campaign has Subscriber Optin or not. + :ivar age_gated: A boolean that specifies whether campaign is age gated or not. + :ivar direct_lending: A boolean that specifies whether campaign allows direct lending or not. + :ivar campaign_status: Campaign status. Examples: IN_PROGRESS, VERIFIED, FAILED. + :ivar campaign_id: The Campaign Registry (TCR) Campaign ID. + :ivar is_externally_registered: Indicates whether the campaign was registered externally or not. + :ivar rate_limits: Rate limit and/or classification set by each carrier, Ex. AT&T or T-Mobile. + :ivar message_flow: Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :ivar opt_in_message: If end users can text in a keyword to start receiving messages from this campaign, the auto-reply messages sent to the end users must be provided. The opt-in response should include the Brand name, confirmation of opt-in enrollment to a recurring message campaign, how to get help, and clear description of how to opt-out. This field is required if end users can text in a keyword to start receiving messages from this campaign. 20 character minimum. 320 character maximum. + :ivar opt_out_message: Upon receiving the opt-out keywords from the end users, Twilio customers are expected to send back an auto-generated response, which must provide acknowledgment of the opt-out request and confirmation that no further messages will be sent. It is also recommended that these opt-out messages include the brand name. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + :ivar help_message: When customers receive the help keywords from their end users, Twilio customers are expected to send back an auto-generated response; this may include the brand name and additional support contact information. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + :ivar opt_in_keywords: If end users can text in a keyword to start receiving messages from this campaign, those keywords must be provided. This field is required if end users can text in a keyword to start receiving messages from this campaign. Values must be alphanumeric. 255 character maximum. + :ivar opt_out_keywords: End users should be able to text in a keyword to stop receiving messages from this campaign. Those keywords must be provided. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + :ivar help_keywords: End users should be able to text in a keyword to receive help. Those keywords must be provided as part of the campaign registration request. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the US App to Person resource. + :ivar mock: A boolean that specifies whether campaign is a mock or not. Mock campaigns will be automatically created if using a mock brand. Mock campaigns should only be used for testing purposes. + :ivar errors: Details indicating why a campaign registration failed. These errors can indicate one or more fields that were incorrect or did not meet review requirements. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + messaging_service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.brand_registration_sid: Optional[str] = payload.get( + "brand_registration_sid" + ) + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.description: Optional[str] = payload.get("description") + self.message_samples: Optional[List[str]] = payload.get("message_samples") + self.us_app_to_person_usecase: Optional[str] = payload.get( + "us_app_to_person_usecase" + ) + self.has_embedded_links: Optional[bool] = payload.get("has_embedded_links") + self.has_embedded_phone: Optional[bool] = payload.get("has_embedded_phone") + self.subscriber_opt_in: Optional[bool] = payload.get("subscriber_opt_in") + self.age_gated: Optional[bool] = payload.get("age_gated") + self.direct_lending: Optional[bool] = payload.get("direct_lending") + self.campaign_status: Optional[str] = payload.get("campaign_status") + self.campaign_id: Optional[str] = payload.get("campaign_id") + self.is_externally_registered: Optional[bool] = payload.get( + "is_externally_registered" + ) + self.rate_limits: Optional[Dict[str, object]] = payload.get("rate_limits") + self.message_flow: Optional[str] = payload.get("message_flow") + self.opt_in_message: Optional[str] = payload.get("opt_in_message") + self.opt_out_message: Optional[str] = payload.get("opt_out_message") + self.help_message: Optional[str] = payload.get("help_message") + self.opt_in_keywords: Optional[List[str]] = payload.get("opt_in_keywords") + self.opt_out_keywords: Optional[List[str]] = payload.get("opt_out_keywords") + self.help_keywords: Optional[List[str]] = payload.get("help_keywords") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.mock: Optional[bool] = payload.get("mock") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") + + self._solution = { + "messaging_service_sid": messaging_service_sid, + "sid": sid or self.sid, + } + self._context: Optional[UsAppToPersonContext] = None + + @property + def _proxy(self) -> "UsAppToPersonContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UsAppToPersonContext for this UsAppToPersonInstance + """ + if self._context is None: + self._context = UsAppToPersonContext( + self._version, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UsAppToPersonInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UsAppToPersonInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UsAppToPersonInstance": + """ + Fetch the UsAppToPersonInstance + + + :returns: The fetched UsAppToPersonInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UsAppToPersonInstance": + """ + Asynchronous coroutine to fetch the UsAppToPersonInstance + + + :returns: The fetched UsAppToPersonInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + has_embedded_links: bool, + has_embedded_phone: bool, + message_samples: List[str], + message_flow: str, + description: str, + age_gated: bool, + direct_lending: bool, + ) -> "UsAppToPersonInstance": + """ + Update the UsAppToPersonInstance + + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + + :returns: The updated UsAppToPersonInstance + """ + return self._proxy.update( + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + message_samples=message_samples, + message_flow=message_flow, + description=description, + age_gated=age_gated, + direct_lending=direct_lending, + ) + + async def update_async( + self, + has_embedded_links: bool, + has_embedded_phone: bool, + message_samples: List[str], + message_flow: str, + description: str, + age_gated: bool, + direct_lending: bool, + ) -> "UsAppToPersonInstance": + """ + Asynchronous coroutine to update the UsAppToPersonInstance + + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + + :returns: The updated UsAppToPersonInstance + """ + return await self._proxy.update_async( + has_embedded_links=has_embedded_links, + has_embedded_phone=has_embedded_phone, + message_samples=message_samples, + message_flow=message_flow, + description=description, + age_gated=age_gated, + direct_lending=direct_lending, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.UsAppToPersonInstance {}>".format(context) + + +class UsAppToPersonContext(InstanceContext): + + def __init__(self, version: Version, messaging_service_sid: str, sid: str): + """ + Initialize the UsAppToPersonContext + + :param version: Version that contains the resource + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services/api) to update the resource from. + :param sid: The SID of the US A2P Compliance resource to update `QE2c6890da8086d771620e9b13fadeba0b`. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "messaging_service_sid": messaging_service_sid, + "sid": sid, + } + self._uri = "/Services/{messaging_service_sid}/Compliance/Usa2p/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the UsAppToPersonInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UsAppToPersonInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UsAppToPersonInstance: + """ + Fetch the UsAppToPersonInstance + + + :returns: The fetched UsAppToPersonInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> UsAppToPersonInstance: + """ + Asynchronous coroutine to fetch the UsAppToPersonInstance + + + :returns: The fetched UsAppToPersonInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + has_embedded_links: bool, + has_embedded_phone: bool, + message_samples: List[str], + message_flow: str, + description: str, + age_gated: bool, + direct_lending: bool, + ) -> UsAppToPersonInstance: + """ + Update the UsAppToPersonInstance + + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + + :returns: The updated UsAppToPersonInstance + """ + + data = values.of( + { + "HasEmbeddedLinks": serialize.boolean_to_string(has_embedded_links), + "HasEmbeddedPhone": serialize.boolean_to_string(has_embedded_phone), + "MessageSamples": serialize.map(message_samples, lambda e: e), + "MessageFlow": message_flow, + "Description": description, + "AgeGated": serialize.boolean_to_string(age_gated), + "DirectLending": serialize.boolean_to_string(direct_lending), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + has_embedded_links: bool, + has_embedded_phone: bool, + message_samples: List[str], + message_flow: str, + description: str, + age_gated: bool, + direct_lending: bool, + ) -> UsAppToPersonInstance: + """ + Asynchronous coroutine to update the UsAppToPersonInstance + + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param age_gated: A boolean that specifies whether campaign requires age gate for federally legal content. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + + :returns: The updated UsAppToPersonInstance + """ + + data = values.of( + { + "HasEmbeddedLinks": serialize.boolean_to_string(has_embedded_links), + "HasEmbeddedPhone": serialize.boolean_to_string(has_embedded_phone), + "MessageSamples": serialize.map(message_samples, lambda e: e), + "MessageFlow": message_flow, + "Description": description, + "AgeGated": serialize.boolean_to_string(age_gated), + "DirectLending": serialize.boolean_to_string(direct_lending), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.UsAppToPersonContext {}>".format(context) + + +class UsAppToPersonPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UsAppToPersonInstance: + """ + Build an instance of UsAppToPersonInstance + + :param payload: Payload response from the API + """ + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.UsAppToPersonPage>" + + +class UsAppToPersonList(ListResource): + + def __init__(self, version: Version, messaging_service_sid: str): + """ + Initialize the UsAppToPersonList + + :param version: Version that contains the resource + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to fetch the resource from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "messaging_service_sid": messaging_service_sid, + } + self._uri = "/Services/{messaging_service_sid}/Compliance/Usa2p".format( + **self._solution + ) + + def create( + self, + brand_registration_sid: str, + description: str, + message_flow: str, + message_samples: List[str], + us_app_to_person_usecase: str, + has_embedded_links: bool, + has_embedded_phone: bool, + opt_in_message: Union[str, object] = values.unset, + opt_out_message: Union[str, object] = values.unset, + help_message: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + opt_out_keywords: Union[List[str], object] = values.unset, + help_keywords: Union[List[str], object] = values.unset, + subscriber_opt_in: Union[bool, object] = values.unset, + age_gated: Union[bool, object] = values.unset, + direct_lending: Union[bool, object] = values.unset, + ) -> UsAppToPersonInstance: + """ + Create the UsAppToPersonInstance + + :param brand_registration_sid: A2P Brand Registration SID + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param us_app_to_person_usecase: A2P Campaign Use Case. Examples: [ 2FA, EMERGENCY, MARKETING..] + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param opt_in_message: If end users can text in a keyword to start receiving messages from this campaign, the auto-reply messages sent to the end users must be provided. The opt-in response should include the Brand name, confirmation of opt-in enrollment to a recurring message campaign, how to get help, and clear description of how to opt-out. This field is required if end users can text in a keyword to start receiving messages from this campaign. 20 character minimum. 320 character maximum. + :param opt_out_message: Upon receiving the opt-out keywords from the end users, Twilio customers are expected to send back an auto-generated response, which must provide acknowledgment of the opt-out request and confirmation that no further messages will be sent. It is also recommended that these opt-out messages include the brand name. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + :param help_message: When customers receive the help keywords from their end users, Twilio customers are expected to send back an auto-generated response; this may include the brand name and additional support contact information. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + :param opt_in_keywords: If end users can text in a keyword to start receiving messages from this campaign, those keywords must be provided. This field is required if end users can text in a keyword to start receiving messages from this campaign. Values must be alphanumeric. 255 character maximum. + :param opt_out_keywords: End users should be able to text in a keyword to stop receiving messages from this campaign. Those keywords must be provided. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + :param help_keywords: End users should be able to text in a keyword to receive help. Those keywords must be provided as part of the campaign registration request. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + :param subscriber_opt_in: A boolean that specifies whether campaign has Subscriber Optin or not. + :param age_gated: A boolean that specifies whether campaign is age gated or not. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + + :returns: The created UsAppToPersonInstance + """ + + data = values.of( + { + "BrandRegistrationSid": brand_registration_sid, + "Description": description, + "MessageFlow": message_flow, + "MessageSamples": serialize.map(message_samples, lambda e: e), + "UsAppToPersonUsecase": us_app_to_person_usecase, + "HasEmbeddedLinks": serialize.boolean_to_string(has_embedded_links), + "HasEmbeddedPhone": serialize.boolean_to_string(has_embedded_phone), + "OptInMessage": opt_in_message, + "OptOutMessage": opt_out_message, + "HelpMessage": help_message, + "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), + "OptOutKeywords": serialize.map(opt_out_keywords, lambda e: e), + "HelpKeywords": serialize.map(help_keywords, lambda e: e), + "SubscriberOptIn": serialize.boolean_to_string(subscriber_opt_in), + "AgeGated": serialize.boolean_to_string(age_gated), + "DirectLending": serialize.boolean_to_string(direct_lending), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + async def create_async( + self, + brand_registration_sid: str, + description: str, + message_flow: str, + message_samples: List[str], + us_app_to_person_usecase: str, + has_embedded_links: bool, + has_embedded_phone: bool, + opt_in_message: Union[str, object] = values.unset, + opt_out_message: Union[str, object] = values.unset, + help_message: Union[str, object] = values.unset, + opt_in_keywords: Union[List[str], object] = values.unset, + opt_out_keywords: Union[List[str], object] = values.unset, + help_keywords: Union[List[str], object] = values.unset, + subscriber_opt_in: Union[bool, object] = values.unset, + age_gated: Union[bool, object] = values.unset, + direct_lending: Union[bool, object] = values.unset, + ) -> UsAppToPersonInstance: + """ + Asynchronously create the UsAppToPersonInstance + + :param brand_registration_sid: A2P Brand Registration SID + :param description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. + :param message_flow: Required for all Campaigns. Details around how a consumer opts-in to their campaign, therefore giving consent to receive their messages. If multiple opt-in methods can be used for the same campaign, they must all be listed. 40 character minimum. 2048 character maximum. + :param message_samples: An array of sample message strings, min two and max five. Min length for each sample: 20 chars. Max length for each sample: 1024 chars. + :param us_app_to_person_usecase: A2P Campaign Use Case. Examples: [ 2FA, EMERGENCY, MARKETING..] + :param has_embedded_links: Indicates that this SMS campaign will send messages that contain links. + :param has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :param opt_in_message: If end users can text in a keyword to start receiving messages from this campaign, the auto-reply messages sent to the end users must be provided. The opt-in response should include the Brand name, confirmation of opt-in enrollment to a recurring message campaign, how to get help, and clear description of how to opt-out. This field is required if end users can text in a keyword to start receiving messages from this campaign. 20 character minimum. 320 character maximum. + :param opt_out_message: Upon receiving the opt-out keywords from the end users, Twilio customers are expected to send back an auto-generated response, which must provide acknowledgment of the opt-out request and confirmation that no further messages will be sent. It is also recommended that these opt-out messages include the brand name. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + :param help_message: When customers receive the help keywords from their end users, Twilio customers are expected to send back an auto-generated response; this may include the brand name and additional support contact information. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). 20 character minimum. 320 character maximum. + :param opt_in_keywords: If end users can text in a keyword to start receiving messages from this campaign, those keywords must be provided. This field is required if end users can text in a keyword to start receiving messages from this campaign. Values must be alphanumeric. 255 character maximum. + :param opt_out_keywords: End users should be able to text in a keyword to stop receiving messages from this campaign. Those keywords must be provided. This field is required if managing opt out keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + :param help_keywords: End users should be able to text in a keyword to receive help. Those keywords must be provided as part of the campaign registration request. This field is required if managing help keywords yourself (i.e. not using Twilio's Default or Advanced Opt Out features). Values must be alphanumeric. 255 character maximum. + :param subscriber_opt_in: A boolean that specifies whether campaign has Subscriber Optin or not. + :param age_gated: A boolean that specifies whether campaign is age gated or not. + :param direct_lending: A boolean that specifies whether campaign allows direct lending or not. + + :returns: The created UsAppToPersonInstance + """ + + data = values.of( + { + "BrandRegistrationSid": brand_registration_sid, + "Description": description, + "MessageFlow": message_flow, + "MessageSamples": serialize.map(message_samples, lambda e: e), + "UsAppToPersonUsecase": us_app_to_person_usecase, + "HasEmbeddedLinks": serialize.boolean_to_string(has_embedded_links), + "HasEmbeddedPhone": serialize.boolean_to_string(has_embedded_phone), + "OptInMessage": opt_in_message, + "OptOutMessage": opt_out_message, + "HelpMessage": help_message, + "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), + "OptOutKeywords": serialize.map(opt_out_keywords, lambda e: e), + "HelpKeywords": serialize.map(help_keywords, lambda e: e), + "SubscriberOptIn": serialize.boolean_to_string(subscriber_opt_in), + "AgeGated": serialize.boolean_to_string(age_gated), + "DirectLending": serialize.boolean_to_string(direct_lending), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UsAppToPersonInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UsAppToPersonInstance]: + """ + Streams UsAppToPersonInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UsAppToPersonInstance]: + """ + Asynchronously streams UsAppToPersonInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UsAppToPersonInstance]: + """ + Lists UsAppToPersonInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UsAppToPersonInstance]: + """ + Asynchronously lists UsAppToPersonInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UsAppToPersonPage: + """ + Retrieve a single page of UsAppToPersonInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UsAppToPersonInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsAppToPersonPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UsAppToPersonPage: + """ + Asynchronously retrieve a single page of UsAppToPersonInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UsAppToPersonInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsAppToPersonPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UsAppToPersonPage: + """ + Retrieve a specific page of UsAppToPersonInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UsAppToPersonInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UsAppToPersonPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UsAppToPersonPage: + """ + Asynchronously retrieve a specific page of UsAppToPersonInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UsAppToPersonInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UsAppToPersonPage(self._version, response, self._solution) + + def get(self, sid: str) -> UsAppToPersonContext: + """ + Constructs a UsAppToPersonContext + + :param sid: The SID of the US A2P Compliance resource to update `QE2c6890da8086d771620e9b13fadeba0b`. + """ + return UsAppToPersonContext( + self._version, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> UsAppToPersonContext: + """ + Constructs a UsAppToPersonContext + + :param sid: The SID of the US A2P Compliance resource to update `QE2c6890da8086d771620e9b13fadeba0b`. + """ + return UsAppToPersonContext( + self._version, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.UsAppToPersonList>" diff --git a/twilio/rest/messaging/v1/service/us_app_to_person_usecase.py b/twilio/rest/messaging/v1/service/us_app_to_person_usecase.py new file mode 100644 index 0000000000..bf9e48e626 --- /dev/null +++ b/twilio/rest/messaging/v1/service/us_app_to_person_usecase.py @@ -0,0 +1,137 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class UsAppToPersonUsecaseInstance(InstanceResource): + """ + :ivar us_app_to_person_usecases: Human readable name, code, description and post_approval_required (indicates whether or not post approval is required for this Use Case) of A2P Campaign Use Cases. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], messaging_service_sid: str + ): + super().__init__(version) + + self.us_app_to_person_usecases: Optional[List[Dict[str, object]]] = payload.get( + "us_app_to_person_usecases" + ) + + self._solution = { + "messaging_service_sid": messaging_service_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.UsAppToPersonUsecaseInstance {}>".format(context) + + +class UsAppToPersonUsecaseList(ListResource): + + def __init__(self, version: Version, messaging_service_sid: str): + """ + Initialize the UsAppToPersonUsecaseList + + :param version: Version that contains the resource + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to fetch the resource from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "messaging_service_sid": messaging_service_sid, + } + self._uri = ( + "/Services/{messaging_service_sid}/Compliance/Usa2p/Usecases".format( + **self._solution + ) + ) + + def fetch( + self, brand_registration_sid: Union[str, object] = values.unset + ) -> UsAppToPersonUsecaseInstance: + """ + Asynchronously fetch the UsAppToPersonUsecaseInstance + + :param brand_registration_sid: The unique string to identify the A2P brand. + :returns: The fetched UsAppToPersonUsecaseInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "BrandRegistrationSid": brand_registration_sid, + } + ) + + payload = self._version.fetch( + method="GET", uri=self._uri, headers=headers, params=params + ) + + return UsAppToPersonUsecaseInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + async def fetch_async( + self, brand_registration_sid: Union[str, object] = values.unset + ) -> UsAppToPersonUsecaseInstance: + """ + Asynchronously fetch the UsAppToPersonUsecaseInstance + + :param brand_registration_sid: The unique string to identify the A2P brand. + :returns: The fetched UsAppToPersonUsecaseInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "BrandRegistrationSid": brand_registration_sid, + } + ) + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + return UsAppToPersonUsecaseInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.UsAppToPersonUsecaseList>" diff --git a/twilio/rest/messaging/v1/tollfree_verification.py b/twilio/rest/messaging/v1/tollfree_verification.py new file mode 100644 index 0000000000..00cf9c96e3 --- /dev/null +++ b/twilio/rest/messaging/v1/tollfree_verification.py @@ -0,0 +1,1173 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TollfreeVerificationInstance(InstanceResource): + + class OptInType(object): + VERBAL = "VERBAL" + WEB_FORM = "WEB_FORM" + PAPER_FORM = "PAPER_FORM" + VIA_TEXT = "VIA_TEXT" + MOBILE_QR_CODE = "MOBILE_QR_CODE" + IMPORT = "IMPORT" + IMPORT_PLEASE_REPLACE = "IMPORT_PLEASE_REPLACE" + + class Status(object): + PENDING_REVIEW = "PENDING_REVIEW" + IN_REVIEW = "IN_REVIEW" + TWILIO_APPROVED = "TWILIO_APPROVED" + TWILIO_REJECTED = "TWILIO_REJECTED" + + """ + :ivar sid: The unique string to identify Tollfree Verification. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Tollfree Verification resource. + :ivar customer_profile_sid: Customer's Profile Bundle BundleSid. + :ivar trust_product_sid: Tollfree TrustProduct Bundle BundleSid. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar regulated_item_sid: The SID of the Regulated Item. + :ivar business_name: The name of the business or organization using the Tollfree number. + :ivar business_street_address: The address of the business or organization using the Tollfree number. + :ivar business_street_address2: The address of the business or organization using the Tollfree number. + :ivar business_city: The city of the business or organization using the Tollfree number. + :ivar business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :ivar business_postal_code: The postal code of the business or organization using the Tollfree number. + :ivar business_country: The country of the business or organization using the Tollfree number. + :ivar business_website: The website of the business or organization using the Tollfree number. + :ivar business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :ivar business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :ivar business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :ivar business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :ivar notification_email: The email address to receive the notification about the verification result. . + :ivar use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :ivar use_case_summary: Use this to further explain how messaging is used by the business or organization. + :ivar production_message_sample: An example of message content, i.e. a sample message. + :ivar opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :ivar opt_in_type: + :ivar message_volume: Estimate monthly volume of messages from the Tollfree Number. + :ivar additional_information: Additional information to be provided for verification. + :ivar tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :ivar status: + :ivar url: The absolute URL of the Tollfree Verification resource. + :ivar rejection_reason: The rejection reason given when a Tollfree Verification has been rejected. + :ivar error_code: The error code given when a Tollfree Verification has been rejected. + :ivar edit_expiration: The date and time when the ability to edit a rejected verification expires. + :ivar edit_allowed: If a rejected verification is allowed to be edited/resubmitted. Some rejection reasons allow editing and some do not. + :ivar rejection_reasons: A list of rejection reasons and codes describing why a Tollfree Verification has been rejected. + :ivar resource_links: The URLs of the documents associated with the Tollfree Verification resource. + :ivar external_reference_id: An optional external reference ID supplied by customer and echoed back on status retrieval. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.customer_profile_sid: Optional[str] = payload.get("customer_profile_sid") + self.trust_product_sid: Optional[str] = payload.get("trust_product_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.regulated_item_sid: Optional[str] = payload.get("regulated_item_sid") + self.business_name: Optional[str] = payload.get("business_name") + self.business_street_address: Optional[str] = payload.get( + "business_street_address" + ) + self.business_street_address2: Optional[str] = payload.get( + "business_street_address2" + ) + self.business_city: Optional[str] = payload.get("business_city") + self.business_state_province_region: Optional[str] = payload.get( + "business_state_province_region" + ) + self.business_postal_code: Optional[str] = payload.get("business_postal_code") + self.business_country: Optional[str] = payload.get("business_country") + self.business_website: Optional[str] = payload.get("business_website") + self.business_contact_first_name: Optional[str] = payload.get( + "business_contact_first_name" + ) + self.business_contact_last_name: Optional[str] = payload.get( + "business_contact_last_name" + ) + self.business_contact_email: Optional[str] = payload.get( + "business_contact_email" + ) + self.business_contact_phone: Optional[str] = payload.get( + "business_contact_phone" + ) + self.notification_email: Optional[str] = payload.get("notification_email") + self.use_case_categories: Optional[List[str]] = payload.get( + "use_case_categories" + ) + self.use_case_summary: Optional[str] = payload.get("use_case_summary") + self.production_message_sample: Optional[str] = payload.get( + "production_message_sample" + ) + self.opt_in_image_urls: Optional[List[str]] = payload.get("opt_in_image_urls") + self.opt_in_type: Optional["TollfreeVerificationInstance.OptInType"] = ( + payload.get("opt_in_type") + ) + self.message_volume: Optional[str] = payload.get("message_volume") + self.additional_information: Optional[str] = payload.get( + "additional_information" + ) + self.tollfree_phone_number_sid: Optional[str] = payload.get( + "tollfree_phone_number_sid" + ) + self.status: Optional["TollfreeVerificationInstance.Status"] = payload.get( + "status" + ) + self.url: Optional[str] = payload.get("url") + self.rejection_reason: Optional[str] = payload.get("rejection_reason") + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.edit_expiration: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("edit_expiration") + ) + self.edit_allowed: Optional[bool] = payload.get("edit_allowed") + self.rejection_reasons: Optional[List[Dict[str, object]]] = payload.get( + "rejection_reasons" + ) + self.resource_links: Optional[Dict[str, object]] = payload.get("resource_links") + self.external_reference_id: Optional[str] = payload.get("external_reference_id") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[TollfreeVerificationContext] = None + + @property + def _proxy(self) -> "TollfreeVerificationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TollfreeVerificationContext for this TollfreeVerificationInstance + """ + if self._context is None: + self._context = TollfreeVerificationContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TollfreeVerificationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TollfreeVerificationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TollfreeVerificationInstance": + """ + Fetch the TollfreeVerificationInstance + + + :returns: The fetched TollfreeVerificationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TollfreeVerificationInstance": + """ + Asynchronous coroutine to fetch the TollfreeVerificationInstance + + + :returns: The fetched TollfreeVerificationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "TollfreeVerificationInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + edit_reason: Union[str, object] = values.unset, + ) -> "TollfreeVerificationInstance": + """ + Update the TollfreeVerificationInstance + + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. + + :returns: The updated TollfreeVerificationInstance + """ + return self._proxy.update( + business_name=business_name, + business_website=business_website, + notification_email=notification_email, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + edit_reason=edit_reason, + ) + + async def update_async( + self, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "TollfreeVerificationInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + edit_reason: Union[str, object] = values.unset, + ) -> "TollfreeVerificationInstance": + """ + Asynchronous coroutine to update the TollfreeVerificationInstance + + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. + + :returns: The updated TollfreeVerificationInstance + """ + return await self._proxy.update_async( + business_name=business_name, + business_website=business_website, + notification_email=notification_email, + use_case_categories=use_case_categories, + use_case_summary=use_case_summary, + production_message_sample=production_message_sample, + opt_in_image_urls=opt_in_image_urls, + opt_in_type=opt_in_type, + message_volume=message_volume, + business_street_address=business_street_address, + business_street_address2=business_street_address2, + business_city=business_city, + business_state_province_region=business_state_province_region, + business_postal_code=business_postal_code, + business_country=business_country, + additional_information=additional_information, + business_contact_first_name=business_contact_first_name, + business_contact_last_name=business_contact_last_name, + business_contact_email=business_contact_email, + business_contact_phone=business_contact_phone, + edit_reason=edit_reason, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.TollfreeVerificationInstance {}>".format(context) + + +class TollfreeVerificationContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the TollfreeVerificationContext + + :param version: Version that contains the resource + :param sid: The unique string to identify Tollfree Verification. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Tollfree/Verifications/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the TollfreeVerificationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TollfreeVerificationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TollfreeVerificationInstance: + """ + Fetch the TollfreeVerificationInstance + + + :returns: The fetched TollfreeVerificationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TollfreeVerificationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TollfreeVerificationInstance: + """ + Asynchronous coroutine to fetch the TollfreeVerificationInstance + + + :returns: The fetched TollfreeVerificationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TollfreeVerificationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "TollfreeVerificationInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + edit_reason: Union[str, object] = values.unset, + ) -> TollfreeVerificationInstance: + """ + Update the TollfreeVerificationInstance + + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. + + :returns: The updated TollfreeVerificationInstance + """ + + data = values.of( + { + "BusinessName": business_name, + "BusinessWebsite": business_website, + "NotificationEmail": notification_email, + "UseCaseCategories": serialize.map(use_case_categories, lambda e: e), + "UseCaseSummary": use_case_summary, + "ProductionMessageSample": production_message_sample, + "OptInImageUrls": serialize.map(opt_in_image_urls, lambda e: e), + "OptInType": opt_in_type, + "MessageVolume": message_volume, + "BusinessStreetAddress": business_street_address, + "BusinessStreetAddress2": business_street_address2, + "BusinessCity": business_city, + "BusinessStateProvinceRegion": business_state_province_region, + "BusinessPostalCode": business_postal_code, + "BusinessCountry": business_country, + "AdditionalInformation": additional_information, + "BusinessContactFirstName": business_contact_first_name, + "BusinessContactLastName": business_contact_last_name, + "BusinessContactEmail": business_contact_email, + "BusinessContactPhone": business_contact_phone, + "EditReason": edit_reason, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TollfreeVerificationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "TollfreeVerificationInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + edit_reason: Union[str, object] = values.unset, + ) -> TollfreeVerificationInstance: + """ + Asynchronous coroutine to update the TollfreeVerificationInstance + + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param edit_reason: Describe why the verification is being edited. If the verification was rejected because of a technical issue, such as the website being down, and the issue has been resolved this parameter should be set to something similar to 'Website fixed'. + + :returns: The updated TollfreeVerificationInstance + """ + + data = values.of( + { + "BusinessName": business_name, + "BusinessWebsite": business_website, + "NotificationEmail": notification_email, + "UseCaseCategories": serialize.map(use_case_categories, lambda e: e), + "UseCaseSummary": use_case_summary, + "ProductionMessageSample": production_message_sample, + "OptInImageUrls": serialize.map(opt_in_image_urls, lambda e: e), + "OptInType": opt_in_type, + "MessageVolume": message_volume, + "BusinessStreetAddress": business_street_address, + "BusinessStreetAddress2": business_street_address2, + "BusinessCity": business_city, + "BusinessStateProvinceRegion": business_state_province_region, + "BusinessPostalCode": business_postal_code, + "BusinessCountry": business_country, + "AdditionalInformation": additional_information, + "BusinessContactFirstName": business_contact_first_name, + "BusinessContactLastName": business_contact_last_name, + "BusinessContactEmail": business_contact_email, + "BusinessContactPhone": business_contact_phone, + "EditReason": edit_reason, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TollfreeVerificationInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V1.TollfreeVerificationContext {}>".format(context) + + +class TollfreeVerificationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TollfreeVerificationInstance: + """ + Build an instance of TollfreeVerificationInstance + + :param payload: Payload response from the API + """ + return TollfreeVerificationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.TollfreeVerificationPage>" + + +class TollfreeVerificationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TollfreeVerificationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Tollfree/Verifications" + + def create( + self, + business_name: str, + business_website: str, + notification_email: str, + use_case_categories: List[str], + use_case_summary: str, + production_message_sample: str, + opt_in_image_urls: List[str], + opt_in_type: "TollfreeVerificationInstance.OptInType", + message_volume: str, + tollfree_phone_number_sid: str, + customer_profile_sid: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + ) -> TollfreeVerificationInstance: + """ + Create the TollfreeVerificationInstance + + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param customer_profile_sid: Customer's Profile Bundle BundleSid. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param external_reference_id: An optional external reference ID supplied by customer and echoed back on status retrieval. + + :returns: The created TollfreeVerificationInstance + """ + + data = values.of( + { + "BusinessName": business_name, + "BusinessWebsite": business_website, + "NotificationEmail": notification_email, + "UseCaseCategories": serialize.map(use_case_categories, lambda e: e), + "UseCaseSummary": use_case_summary, + "ProductionMessageSample": production_message_sample, + "OptInImageUrls": serialize.map(opt_in_image_urls, lambda e: e), + "OptInType": opt_in_type, + "MessageVolume": message_volume, + "TollfreePhoneNumberSid": tollfree_phone_number_sid, + "CustomerProfileSid": customer_profile_sid, + "BusinessStreetAddress": business_street_address, + "BusinessStreetAddress2": business_street_address2, + "BusinessCity": business_city, + "BusinessStateProvinceRegion": business_state_province_region, + "BusinessPostalCode": business_postal_code, + "BusinessCountry": business_country, + "AdditionalInformation": additional_information, + "BusinessContactFirstName": business_contact_first_name, + "BusinessContactLastName": business_contact_last_name, + "BusinessContactEmail": business_contact_email, + "BusinessContactPhone": business_contact_phone, + "ExternalReferenceId": external_reference_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TollfreeVerificationInstance(self._version, payload) + + async def create_async( + self, + business_name: str, + business_website: str, + notification_email: str, + use_case_categories: List[str], + use_case_summary: str, + production_message_sample: str, + opt_in_image_urls: List[str], + opt_in_type: "TollfreeVerificationInstance.OptInType", + message_volume: str, + tollfree_phone_number_sid: str, + customer_profile_sid: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + ) -> TollfreeVerificationInstance: + """ + Asynchronously create the TollfreeVerificationInstance + + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param notification_email: The email address to receive the notification about the verification result. . + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param customer_profile_sid: Customer's Profile Bundle BundleSid. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The E.164 formatted phone number of the contact for the business or organization using the Tollfree number. + :param external_reference_id: An optional external reference ID supplied by customer and echoed back on status retrieval. + + :returns: The created TollfreeVerificationInstance + """ + + data = values.of( + { + "BusinessName": business_name, + "BusinessWebsite": business_website, + "NotificationEmail": notification_email, + "UseCaseCategories": serialize.map(use_case_categories, lambda e: e), + "UseCaseSummary": use_case_summary, + "ProductionMessageSample": production_message_sample, + "OptInImageUrls": serialize.map(opt_in_image_urls, lambda e: e), + "OptInType": opt_in_type, + "MessageVolume": message_volume, + "TollfreePhoneNumberSid": tollfree_phone_number_sid, + "CustomerProfileSid": customer_profile_sid, + "BusinessStreetAddress": business_street_address, + "BusinessStreetAddress2": business_street_address2, + "BusinessCity": business_city, + "BusinessStateProvinceRegion": business_state_province_region, + "BusinessPostalCode": business_postal_code, + "BusinessCountry": business_country, + "AdditionalInformation": additional_information, + "BusinessContactFirstName": business_contact_first_name, + "BusinessContactLastName": business_contact_last_name, + "BusinessContactEmail": business_contact_email, + "BusinessContactPhone": business_contact_phone, + "ExternalReferenceId": external_reference_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TollfreeVerificationInstance(self._version, payload) + + def stream( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TollfreeVerificationInstance]: + """ + Streams TollfreeVerificationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. + :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + tollfree_phone_number_sid=tollfree_phone_number_sid, + status=status, + external_reference_id=external_reference_id, + include_sub_accounts=include_sub_accounts, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TollfreeVerificationInstance]: + """ + Asynchronously streams TollfreeVerificationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. + :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + tollfree_phone_number_sid=tollfree_phone_number_sid, + status=status, + external_reference_id=external_reference_id, + include_sub_accounts=include_sub_accounts, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TollfreeVerificationInstance]: + """ + Lists TollfreeVerificationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. + :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + tollfree_phone_number_sid=tollfree_phone_number_sid, + status=status, + external_reference_id=external_reference_id, + include_sub_accounts=include_sub_accounts, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TollfreeVerificationInstance]: + """ + Asynchronously lists TollfreeVerificationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param "TollfreeVerificationInstance.Status" status: The compliance status of the Tollfree Verification record. + :param str external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param bool include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + tollfree_phone_number_sid=tollfree_phone_number_sid, + status=status, + external_reference_id=external_reference_id, + include_sub_accounts=include_sub_accounts, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TollfreeVerificationPage: + """ + Retrieve a single page of TollfreeVerificationInstance records from the API. + Request is executed immediately + + :param tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param status: The compliance status of the Tollfree Verification record. + :param external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TollfreeVerificationInstance + """ + data = values.of( + { + "TollfreePhoneNumberSid": tollfree_phone_number_sid, + "Status": status, + "ExternalReferenceId": external_reference_id, + "IncludeSubAccounts": serialize.boolean_to_string(include_sub_accounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TollfreeVerificationPage(self._version, response) + + async def page_async( + self, + tollfree_phone_number_sid: Union[str, object] = values.unset, + status: Union["TollfreeVerificationInstance.Status", object] = values.unset, + external_reference_id: Union[str, object] = values.unset, + include_sub_accounts: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TollfreeVerificationPage: + """ + Asynchronously retrieve a single page of TollfreeVerificationInstance records from the API. + Request is executed immediately + + :param tollfree_phone_number_sid: The SID of the Phone Number associated with the Tollfree Verification. + :param status: The compliance status of the Tollfree Verification record. + :param external_reference_id: Customer supplied reference id for the Tollfree Verification record. + :param include_sub_accounts: Whether to include Tollfree Verifications from sub accounts in list response. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TollfreeVerificationInstance + """ + data = values.of( + { + "TollfreePhoneNumberSid": tollfree_phone_number_sid, + "Status": status, + "ExternalReferenceId": external_reference_id, + "IncludeSubAccounts": serialize.boolean_to_string(include_sub_accounts), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TollfreeVerificationPage(self._version, response) + + def get_page(self, target_url: str) -> TollfreeVerificationPage: + """ + Retrieve a specific page of TollfreeVerificationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TollfreeVerificationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TollfreeVerificationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> TollfreeVerificationPage: + """ + Asynchronously retrieve a specific page of TollfreeVerificationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TollfreeVerificationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TollfreeVerificationPage(self._version, response) + + def get(self, sid: str) -> TollfreeVerificationContext: + """ + Constructs a TollfreeVerificationContext + + :param sid: The unique string to identify Tollfree Verification. + """ + return TollfreeVerificationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> TollfreeVerificationContext: + """ + Constructs a TollfreeVerificationContext + + :param sid: The unique string to identify Tollfree Verification. + """ + return TollfreeVerificationContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.TollfreeVerificationList>" diff --git a/twilio/rest/messaging/v1/usecase.py b/twilio/rest/messaging/v1/usecase.py new file mode 100644 index 0000000000..fe811e0c84 --- /dev/null +++ b/twilio/rest/messaging/v1/usecase.py @@ -0,0 +1,94 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class UsecaseInstance(InstanceResource): + """ + :ivar usecases: Human readable use case details (usecase, description and purpose) of Messaging Service Use Cases. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.usecases: Optional[List[Dict[str, object]]] = payload.get("usecases") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Messaging.V1.UsecaseInstance>" + + +class UsecaseList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the UsecaseList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services/Usecases" + + def fetch(self) -> UsecaseInstance: + """ + Asynchronously fetch the UsecaseInstance + + + :returns: The fetched UsecaseInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UsecaseInstance(self._version, payload) + + async def fetch_async(self) -> UsecaseInstance: + """ + Asynchronously fetch the UsecaseInstance + + + :returns: The fetched UsecaseInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UsecaseInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V1.UsecaseList>" diff --git a/twilio/rest/messaging/v2/__init__.py b/twilio/rest/messaging/v2/__init__.py new file mode 100644 index 0000000000..7ef89fdc5a --- /dev/null +++ b/twilio/rest/messaging/v2/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.messaging.v2.channels_sender import ChannelsSenderList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Messaging + + :param domain: The Twilio.messaging domain + """ + super().__init__(domain, "v2") + self._channels_senders: Optional[ChannelsSenderList] = None + + @property + def channels_senders(self) -> ChannelsSenderList: + if self._channels_senders is None: + self._channels_senders = ChannelsSenderList(self) + return self._channels_senders + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V2>" diff --git a/twilio/rest/messaging/v2/channels_sender.py b/twilio/rest/messaging/v2/channels_sender.py new file mode 100644 index 0000000000..a6e4252dc0 --- /dev/null +++ b/twilio/rest/messaging/v2/channels_sender.py @@ -0,0 +1,1104 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Messaging + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ChannelsSenderInstance(InstanceResource): + + class MessagingV2ChannelsSenderConfiguration(object): + """ + :ivar waba_id: The ID of the WhatsApp Business Account to use for this sender. + :ivar verification_method: The method to use for verification. Either \"sms\" or \"voice\". + :ivar verification_code: The verification code to use for this sender. + :ivar voice_application_sid: The SID of the Twilio Voice application to use for this sender. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.waba_id: Optional[str] = payload.get("waba_id") + self.verification_method: Optional["ChannelsSenderInstance.str"] = ( + payload.get("verification_method") + ) + self.verification_code: Optional[str] = payload.get("verification_code") + self.voice_application_sid: Optional[str] = payload.get( + "voice_application_sid" + ) + + def to_dict(self): + return { + "waba_id": self.waba_id, + "verification_method": self.verification_method, + "verification_code": self.verification_code, + "voice_application_sid": self.voice_application_sid, + } + + class MessagingV2ChannelsSenderProfile(object): + """ + :ivar name: The name of the sender. + :ivar about: The about text of the sender. + :ivar address: The address of the sender. + :ivar description: The description of the sender. + :ivar emails: The emails of the sender. + :ivar logo_url: The logo URL of the sender. + :ivar vertical: The vertical of the sender. Allowed values are: - \"Automotive\" - \"Beauty, Spa and Salon\" - \"Clothing and Apparel\" - \"Education\" - \"Entertainment\" - \"Event Planning and Service\" - \"Finance and Banking\" - \"Food and Grocery\" - \"Public Service\" - \"Hotel and Lodging\" - \"Medical and Health\" - \"Non-profit\" - \"Professional Services\" - \"Shopping and Retail\" - \"Travel and Transportation\" - \"Restaurant\" - \"Other\" + :ivar websites: The websites of the sender. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.about: Optional[str] = payload.get("about") + self.address: Optional[str] = payload.get("address") + self.description: Optional[str] = payload.get("description") + self.emails: Optional[Dict[str, object]] = payload.get("emails") + self.logo_url: Optional[str] = payload.get("logo_url") + self.vertical: Optional[str] = payload.get("vertical") + self.websites: Optional[Dict[str, object]] = payload.get("websites") + + def to_dict(self): + return { + "name": self.name, + "about": self.about, + "address": self.address, + "description": self.description, + "emails": self.emails, + "logo_url": self.logo_url, + "vertical": self.vertical, + "websites": self.websites, + } + + class MessagingV2ChannelsSenderRequestsCreate(object): + """ + :ivar sender_id: The ID of this Sender prefixed with the channel, e.g., `whatsapp:E.164` + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.sender_id: Optional[str] = payload.get("sender_id") + self.configuration: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderConfiguration + ] = payload.get("configuration") + self.webhook: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderWebhook + ] = payload.get("webhook") + self.profile: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderProfile + ] = payload.get("profile") + + def to_dict(self): + return { + "sender_id": self.sender_id, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + "webhook": self.webhook.to_dict() if self.webhook is not None else None, + "profile": self.profile.to_dict() if self.profile is not None else None, + } + + class MessagingV2ChannelsSenderRequestsUpdate(object): + """ + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.configuration: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderConfiguration + ] = payload.get("configuration") + self.webhook: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderWebhook + ] = payload.get("webhook") + self.profile: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderProfile + ] = payload.get("profile") + + def to_dict(self): + return { + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + "webhook": self.webhook.to_dict() if self.webhook is not None else None, + "profile": self.profile.to_dict() if self.profile is not None else None, + } + + class MessagingV2ChannelsSenderWebhook(object): + """ + :ivar callback_url: The URL to send the webhook to. + :ivar callback_method: The HTTP method to use for the webhook. Either \"POST\" or \"PUT\". + :ivar fallback_url: The URL to send the fallback webhook to. + :ivar fallback_method: The HTTP method to use for the fallback webhook. Either \"POST\" or \"PUT\". + :ivar status_callback_url: The URL to send the status callback to. + :ivar status_callback_method: The HTTP method to use for the status callback. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.callback_url: Optional[str] = payload.get("callback_url") + self.callback_method: Optional["ChannelsSenderInstance.str"] = payload.get( + "callback_method" + ) + self.fallback_url: Optional[str] = payload.get("fallback_url") + self.fallback_method: Optional["ChannelsSenderInstance.str"] = payload.get( + "fallback_method" + ) + self.status_callback_url: Optional[str] = payload.get("status_callback_url") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + + def to_dict(self): + return { + "callback_url": self.callback_url, + "callback_method": self.callback_method, + "fallback_url": self.fallback_url, + "fallback_method": self.fallback_method, + "status_callback_url": self.status_callback_url, + "status_callback_method": self.status_callback_method, + } + + class Status(object): + CREATING = "CREATING" + ONLINE = "ONLINE" + OFFLINE = "OFFLINE" + PENDING_VERIFICATION = "PENDING_VERIFICATION" + VERIFYING = "VERIFYING" + ONLINE_UPDATING = "ONLINE:UPDATING" + STUBBED = "STUBBED" + + """ + :ivar sid: A 34 character string that uniquely identifies this Sender. + :ivar status: + :ivar sender_id: The ID of this Sender prefixed with the channel, e.g., `whatsapp:E.164` + :ivar configuration: + :ivar webhook: + :ivar profile: + :ivar properties: + :ivar offline_reasons: Reasons why the sender is offline., e.g., [{\"code\": \"21211400\", \"message\": \"Whatsapp business account is banned by provider {provider_name} | Credit line is assigned to another BSP\", \"more_info\": \"https://www.twilio.com/docs/errors/21211400\"}] + :ivar url: The URL of this resource, relative to `https://messaging.twilio.com`. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.status: Optional["ChannelsSenderInstance.Status"] = payload.get("status") + self.sender_id: Optional[str] = payload.get("sender_id") + self.configuration: Optional[str] = payload.get("configuration") + self.webhook: Optional[str] = payload.get("webhook") + self.profile: Optional[str] = payload.get("profile") + self.properties: Optional[str] = payload.get("properties") + self.offline_reasons: Optional[List[str]] = payload.get("offline_reasons") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ChannelsSenderContext] = None + + @property + def _proxy(self) -> "ChannelsSenderContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ChannelsSenderContext for this ChannelsSenderInstance + """ + if self._context is None: + self._context = ChannelsSenderContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ChannelsSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelsSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ChannelsSenderInstance": + """ + Fetch the ChannelsSenderInstance + + + :returns: The fetched ChannelsSenderInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ChannelsSenderInstance": + """ + Asynchronous coroutine to fetch the ChannelsSenderInstance + + + :returns: The fetched ChannelsSenderInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> "ChannelsSenderInstance": + """ + Update the ChannelsSenderInstance + + :param messaging_v2_channels_sender_requests_update: + + :returns: The updated ChannelsSenderInstance + """ + return self._proxy.update( + messaging_v2_channels_sender_requests_update=messaging_v2_channels_sender_requests_update, + ) + + async def update_async( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> "ChannelsSenderInstance": + """ + Asynchronous coroutine to update the ChannelsSenderInstance + + :param messaging_v2_channels_sender_requests_update: + + :returns: The updated ChannelsSenderInstance + """ + return await self._proxy.update_async( + messaging_v2_channels_sender_requests_update=messaging_v2_channels_sender_requests_update, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V2.ChannelsSenderInstance {}>".format(context) + + +class ChannelsSenderContext(InstanceContext): + + class MessagingV2ChannelsSenderConfiguration(object): + """ + :ivar waba_id: The ID of the WhatsApp Business Account to use for this sender. + :ivar verification_method: The method to use for verification. Either \"sms\" or \"voice\". + :ivar verification_code: The verification code to use for this sender. + :ivar voice_application_sid: The SID of the Twilio Voice application to use for this sender. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.waba_id: Optional[str] = payload.get("waba_id") + self.verification_method: Optional["ChannelsSenderInstance.str"] = ( + payload.get("verification_method") + ) + self.verification_code: Optional[str] = payload.get("verification_code") + self.voice_application_sid: Optional[str] = payload.get( + "voice_application_sid" + ) + + def to_dict(self): + return { + "waba_id": self.waba_id, + "verification_method": self.verification_method, + "verification_code": self.verification_code, + "voice_application_sid": self.voice_application_sid, + } + + class MessagingV2ChannelsSenderProfile(object): + """ + :ivar name: The name of the sender. + :ivar about: The about text of the sender. + :ivar address: The address of the sender. + :ivar description: The description of the sender. + :ivar emails: The emails of the sender. + :ivar logo_url: The logo URL of the sender. + :ivar vertical: The vertical of the sender. Allowed values are: - \"Automotive\" - \"Beauty, Spa and Salon\" - \"Clothing and Apparel\" - \"Education\" - \"Entertainment\" - \"Event Planning and Service\" - \"Finance and Banking\" - \"Food and Grocery\" - \"Public Service\" - \"Hotel and Lodging\" - \"Medical and Health\" - \"Non-profit\" - \"Professional Services\" - \"Shopping and Retail\" - \"Travel and Transportation\" - \"Restaurant\" - \"Other\" + :ivar websites: The websites of the sender. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.about: Optional[str] = payload.get("about") + self.address: Optional[str] = payload.get("address") + self.description: Optional[str] = payload.get("description") + self.emails: Optional[Dict[str, object]] = payload.get("emails") + self.logo_url: Optional[str] = payload.get("logo_url") + self.vertical: Optional[str] = payload.get("vertical") + self.websites: Optional[Dict[str, object]] = payload.get("websites") + + def to_dict(self): + return { + "name": self.name, + "about": self.about, + "address": self.address, + "description": self.description, + "emails": self.emails, + "logo_url": self.logo_url, + "vertical": self.vertical, + "websites": self.websites, + } + + class MessagingV2ChannelsSenderRequestsCreate(object): + """ + :ivar sender_id: The ID of this Sender prefixed with the channel, e.g., `whatsapp:E.164` + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.sender_id: Optional[str] = payload.get("sender_id") + self.configuration: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderConfiguration + ] = payload.get("configuration") + self.webhook: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderWebhook + ] = payload.get("webhook") + self.profile: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderProfile + ] = payload.get("profile") + + def to_dict(self): + return { + "sender_id": self.sender_id, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + "webhook": self.webhook.to_dict() if self.webhook is not None else None, + "profile": self.profile.to_dict() if self.profile is not None else None, + } + + class MessagingV2ChannelsSenderRequestsUpdate(object): + """ + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.configuration: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderConfiguration + ] = payload.get("configuration") + self.webhook: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderWebhook + ] = payload.get("webhook") + self.profile: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderProfile + ] = payload.get("profile") + + def to_dict(self): + return { + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + "webhook": self.webhook.to_dict() if self.webhook is not None else None, + "profile": self.profile.to_dict() if self.profile is not None else None, + } + + class MessagingV2ChannelsSenderWebhook(object): + """ + :ivar callback_url: The URL to send the webhook to. + :ivar callback_method: The HTTP method to use for the webhook. Either \"POST\" or \"PUT\". + :ivar fallback_url: The URL to send the fallback webhook to. + :ivar fallback_method: The HTTP method to use for the fallback webhook. Either \"POST\" or \"PUT\". + :ivar status_callback_url: The URL to send the status callback to. + :ivar status_callback_method: The HTTP method to use for the status callback. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.callback_url: Optional[str] = payload.get("callback_url") + self.callback_method: Optional["ChannelsSenderInstance.str"] = payload.get( + "callback_method" + ) + self.fallback_url: Optional[str] = payload.get("fallback_url") + self.fallback_method: Optional["ChannelsSenderInstance.str"] = payload.get( + "fallback_method" + ) + self.status_callback_url: Optional[str] = payload.get("status_callback_url") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + + def to_dict(self): + return { + "callback_url": self.callback_url, + "callback_method": self.callback_method, + "fallback_url": self.fallback_url, + "fallback_method": self.fallback_method, + "status_callback_url": self.status_callback_url, + "status_callback_method": self.status_callback_method, + } + + def __init__(self, version: Version, sid: str): + """ + Initialize the ChannelsSenderContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this Sender. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Channels/Senders/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the ChannelsSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelsSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ChannelsSenderInstance: + """ + Fetch the ChannelsSenderInstance + + + :returns: The fetched ChannelsSenderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ChannelsSenderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ChannelsSenderInstance: + """ + Asynchronous coroutine to fetch the ChannelsSenderInstance + + + :returns: The fetched ChannelsSenderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ChannelsSenderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> ChannelsSenderInstance: + """ + Update the ChannelsSenderInstance + + :param messaging_v2_channels_sender_requests_update: + + :returns: The updated ChannelsSenderInstance + """ + data = messaging_v2_channels_sender_requests_update.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelsSenderInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + messaging_v2_channels_sender_requests_update: Union[ + MessagingV2ChannelsSenderRequestsUpdate, object + ] = values.unset, + ) -> ChannelsSenderInstance: + """ + Asynchronous coroutine to update the ChannelsSenderInstance + + :param messaging_v2_channels_sender_requests_update: + + :returns: The updated ChannelsSenderInstance + """ + data = messaging_v2_channels_sender_requests_update.to_dict() + + headers = values.of({}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelsSenderInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Messaging.V2.ChannelsSenderContext {}>".format(context) + + +class ChannelsSenderPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChannelsSenderInstance: + """ + Build an instance of ChannelsSenderInstance + + :param payload: Payload response from the API + """ + return ChannelsSenderInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V2.ChannelsSenderPage>" + + +class ChannelsSenderList(ListResource): + + class MessagingV2ChannelsSenderConfiguration(object): + """ + :ivar waba_id: The ID of the WhatsApp Business Account to use for this sender. + :ivar verification_method: The method to use for verification. Either \"sms\" or \"voice\". + :ivar verification_code: The verification code to use for this sender. + :ivar voice_application_sid: The SID of the Twilio Voice application to use for this sender. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.waba_id: Optional[str] = payload.get("waba_id") + self.verification_method: Optional["ChannelsSenderInstance.str"] = ( + payload.get("verification_method") + ) + self.verification_code: Optional[str] = payload.get("verification_code") + self.voice_application_sid: Optional[str] = payload.get( + "voice_application_sid" + ) + + def to_dict(self): + return { + "waba_id": self.waba_id, + "verification_method": self.verification_method, + "verification_code": self.verification_code, + "voice_application_sid": self.voice_application_sid, + } + + class MessagingV2ChannelsSenderProfile(object): + """ + :ivar name: The name of the sender. + :ivar about: The about text of the sender. + :ivar address: The address of the sender. + :ivar description: The description of the sender. + :ivar emails: The emails of the sender. + :ivar logo_url: The logo URL of the sender. + :ivar vertical: The vertical of the sender. Allowed values are: - \"Automotive\" - \"Beauty, Spa and Salon\" - \"Clothing and Apparel\" - \"Education\" - \"Entertainment\" - \"Event Planning and Service\" - \"Finance and Banking\" - \"Food and Grocery\" - \"Public Service\" - \"Hotel and Lodging\" - \"Medical and Health\" - \"Non-profit\" - \"Professional Services\" - \"Shopping and Retail\" - \"Travel and Transportation\" - \"Restaurant\" - \"Other\" + :ivar websites: The websites of the sender. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.about: Optional[str] = payload.get("about") + self.address: Optional[str] = payload.get("address") + self.description: Optional[str] = payload.get("description") + self.emails: Optional[Dict[str, object]] = payload.get("emails") + self.logo_url: Optional[str] = payload.get("logo_url") + self.vertical: Optional[str] = payload.get("vertical") + self.websites: Optional[Dict[str, object]] = payload.get("websites") + + def to_dict(self): + return { + "name": self.name, + "about": self.about, + "address": self.address, + "description": self.description, + "emails": self.emails, + "logo_url": self.logo_url, + "vertical": self.vertical, + "websites": self.websites, + } + + class MessagingV2ChannelsSenderRequestsCreate(object): + """ + :ivar sender_id: The ID of this Sender prefixed with the channel, e.g., `whatsapp:E.164` + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.sender_id: Optional[str] = payload.get("sender_id") + self.configuration: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderConfiguration + ] = payload.get("configuration") + self.webhook: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderWebhook + ] = payload.get("webhook") + self.profile: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderProfile + ] = payload.get("profile") + + def to_dict(self): + return { + "sender_id": self.sender_id, + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + "webhook": self.webhook.to_dict() if self.webhook is not None else None, + "profile": self.profile.to_dict() if self.profile is not None else None, + } + + class MessagingV2ChannelsSenderRequestsUpdate(object): + """ + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.configuration: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderConfiguration + ] = payload.get("configuration") + self.webhook: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderWebhook + ] = payload.get("webhook") + self.profile: Optional[ + ChannelsSenderList.MessagingV2ChannelsSenderProfile + ] = payload.get("profile") + + def to_dict(self): + return { + "configuration": ( + self.configuration.to_dict() + if self.configuration is not None + else None + ), + "webhook": self.webhook.to_dict() if self.webhook is not None else None, + "profile": self.profile.to_dict() if self.profile is not None else None, + } + + class MessagingV2ChannelsSenderWebhook(object): + """ + :ivar callback_url: The URL to send the webhook to. + :ivar callback_method: The HTTP method to use for the webhook. Either \"POST\" or \"PUT\". + :ivar fallback_url: The URL to send the fallback webhook to. + :ivar fallback_method: The HTTP method to use for the fallback webhook. Either \"POST\" or \"PUT\". + :ivar status_callback_url: The URL to send the status callback to. + :ivar status_callback_method: The HTTP method to use for the status callback. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.callback_url: Optional[str] = payload.get("callback_url") + self.callback_method: Optional["ChannelsSenderInstance.str"] = payload.get( + "callback_method" + ) + self.fallback_url: Optional[str] = payload.get("fallback_url") + self.fallback_method: Optional["ChannelsSenderInstance.str"] = payload.get( + "fallback_method" + ) + self.status_callback_url: Optional[str] = payload.get("status_callback_url") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + + def to_dict(self): + return { + "callback_url": self.callback_url, + "callback_method": self.callback_method, + "fallback_url": self.fallback_url, + "fallback_method": self.fallback_method, + "status_callback_url": self.status_callback_url, + "status_callback_method": self.status_callback_method, + } + + def __init__(self, version: Version): + """ + Initialize the ChannelsSenderList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Channels/Senders" + + def create( + self, + messaging_v2_channels_sender_requests_create: MessagingV2ChannelsSenderRequestsCreate, + ) -> ChannelsSenderInstance: + """ + Create the ChannelsSenderInstance + + :param messaging_v2_channels_sender_requests_create: + + :returns: The created ChannelsSenderInstance + """ + data = messaging_v2_channels_sender_requests_create.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelsSenderInstance(self._version, payload) + + async def create_async( + self, + messaging_v2_channels_sender_requests_create: MessagingV2ChannelsSenderRequestsCreate, + ) -> ChannelsSenderInstance: + """ + Asynchronously create the ChannelsSenderInstance + + :param messaging_v2_channels_sender_requests_create: + + :returns: The created ChannelsSenderInstance + """ + data = messaging_v2_channels_sender_requests_create.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChannelsSenderInstance(self._version, payload) + + def stream( + self, + channel: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChannelsSenderInstance]: + """ + Streams ChannelsSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str channel: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(channel=channel, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + channel: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChannelsSenderInstance]: + """ + Asynchronously streams ChannelsSenderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str channel: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(channel=channel, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + channel: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelsSenderInstance]: + """ + Lists ChannelsSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str channel: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + channel=channel, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + channel: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChannelsSenderInstance]: + """ + Asynchronously lists ChannelsSenderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str channel: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + channel=channel, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + channel: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelsSenderPage: + """ + Retrieve a single page of ChannelsSenderInstance records from the API. + Request is executed immediately + + :param channel: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelsSenderInstance + """ + data = values.of( + { + "Channel": channel, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelsSenderPage(self._version, response) + + async def page_async( + self, + channel: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelsSenderPage: + """ + Asynchronously retrieve a single page of ChannelsSenderInstance records from the API. + Request is executed immediately + + :param channel: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChannelsSenderInstance + """ + data = values.of( + { + "Channel": channel, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChannelsSenderPage(self._version, response) + + def get_page(self, target_url: str) -> ChannelsSenderPage: + """ + Retrieve a specific page of ChannelsSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelsSenderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChannelsSenderPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ChannelsSenderPage: + """ + Asynchronously retrieve a specific page of ChannelsSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelsSenderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelsSenderPage(self._version, response) + + def get(self, sid: str) -> ChannelsSenderContext: + """ + Constructs a ChannelsSenderContext + + :param sid: A 34 character string that uniquely identifies this Sender. + """ + return ChannelsSenderContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ChannelsSenderContext: + """ + Constructs a ChannelsSenderContext + + :param sid: A 34 character string that uniquely identifies this Sender. + """ + return ChannelsSenderContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Messaging.V2.ChannelsSenderList>" diff --git a/twilio/rest/monitor/MonitorBase.py b/twilio/rest/monitor/MonitorBase.py new file mode 100644 index 0000000000..4c5c6ebcd6 --- /dev/null +++ b/twilio/rest/monitor/MonitorBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.monitor.v1 import V1 + + +class MonitorBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Monitor Domain + + :returns: Domain for Monitor + """ + super().__init__(twilio, "https://monitor.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Monitor + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Monitor>" diff --git a/twilio/rest/monitor/__init__.py b/twilio/rest/monitor/__init__.py new file mode 100644 index 0000000000..a39a5b248a --- /dev/null +++ b/twilio/rest/monitor/__init__.py @@ -0,0 +1,25 @@ +from warnings import warn + +from twilio.rest.monitor.MonitorBase import MonitorBase +from twilio.rest.monitor.v1.alert import AlertList +from twilio.rest.monitor.v1.event import EventList + + +class Monitor(MonitorBase): + @property + def alerts(self) -> AlertList: + warn( + "alerts is deprecated. Use v1.alerts instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.alerts + + @property + def events(self) -> EventList: + warn( + "events is deprecated. Use v1.events instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.events diff --git a/twilio/rest/monitor/v1/__init__.py b/twilio/rest/monitor/v1/__init__.py new file mode 100644 index 0000000000..e892612b3b --- /dev/null +++ b/twilio/rest/monitor/v1/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Monitor + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.monitor.v1.alert import AlertList +from twilio.rest.monitor.v1.event import EventList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Monitor + + :param domain: The Twilio.monitor domain + """ + super().__init__(domain, "v1") + self._alerts: Optional[AlertList] = None + self._events: Optional[EventList] = None + + @property + def alerts(self) -> AlertList: + if self._alerts is None: + self._alerts = AlertList(self) + return self._alerts + + @property + def events(self) -> EventList: + if self._events is None: + self._events = EventList(self) + return self._events + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Monitor.V1>" diff --git a/twilio/rest/monitor/v1/alert.py b/twilio/rest/monitor/v1/alert.py new file mode 100644 index 0000000000..829e633643 --- /dev/null +++ b/twilio/rest/monitor/v1/alert.py @@ -0,0 +1,501 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Monitor + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AlertInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Alert resource. + :ivar alert_text: The text of the alert. + :ivar api_version: The API version used when the alert was generated. Can be empty for events that don't have a specific API version. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_generated: The date and time in GMT when the alert was generated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. Due to buffering, this can be different than `date_created`. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar error_code: The error code for the condition that generated the alert. See the [Error Dictionary](https://www.twilio.com/docs/api/errors) for possible causes and solutions to the error. + :ivar log_level: The log level. Can be: `error`, `warning`, `notice`, or `debug`. + :ivar more_info: The URL of the page in our [Error Dictionary](https://www.twilio.com/docs/api/errors) with more information about the error condition. + :ivar request_method: The method used by the request that generated the alert. If the alert was generated by a request we made to your server, this is the method we used. If the alert was generated by a request from your application to our API, this is the method your application used. + :ivar request_url: The URL of the request that generated the alert. If the alert was generated by a request we made to your server, this is the URL on your server that generated the alert. If the alert was generated by a request from your application to our API, this is the URL of the resource requested. + :ivar request_variables: The variables passed in the request that generated the alert. This value is only returned when a single Alert resource is fetched. + :ivar resource_sid: The SID of the resource for which the alert was generated. For instance, if your server failed to respond to an HTTP request during the flow of a particular call, this value would be the SID of the server. This value is empty if the alert was not generated for a particular resource. + :ivar response_body: The response body of the request that generated the alert. This value is only returned when a single Alert resource is fetched. + :ivar response_headers: The response headers of the request that generated the alert. This value is only returned when a single Alert resource is fetched. + :ivar sid: The unique string that we created to identify the Alert resource. + :ivar url: The absolute URL of the Alert resource. + :ivar request_headers: The request headers of the request that generated the alert. This value is only returned when a single Alert resource is fetched. + :ivar service_sid: The SID of the service or resource that generated the alert. Can be `null`. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.alert_text: Optional[str] = payload.get("alert_text") + self.api_version: Optional[str] = payload.get("api_version") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_generated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_generated") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.error_code: Optional[str] = payload.get("error_code") + self.log_level: Optional[str] = payload.get("log_level") + self.more_info: Optional[str] = payload.get("more_info") + self.request_method: Optional[str] = payload.get("request_method") + self.request_url: Optional[str] = payload.get("request_url") + self.request_variables: Optional[str] = payload.get("request_variables") + self.resource_sid: Optional[str] = payload.get("resource_sid") + self.response_body: Optional[str] = payload.get("response_body") + self.response_headers: Optional[str] = payload.get("response_headers") + self.sid: Optional[str] = payload.get("sid") + self.url: Optional[str] = payload.get("url") + self.request_headers: Optional[str] = payload.get("request_headers") + self.service_sid: Optional[str] = payload.get("service_sid") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AlertContext] = None + + @property + def _proxy(self) -> "AlertContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AlertContext for this AlertInstance + """ + if self._context is None: + self._context = AlertContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AlertInstance": + """ + Fetch the AlertInstance + + + :returns: The fetched AlertInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AlertInstance": + """ + Asynchronous coroutine to fetch the AlertInstance + + + :returns: The fetched AlertInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Monitor.V1.AlertInstance {}>".format(context) + + +class AlertContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the AlertContext + + :param version: Version that contains the resource + :param sid: The SID of the Alert resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Alerts/{sid}".format(**self._solution) + + def fetch(self) -> AlertInstance: + """ + Fetch the AlertInstance + + + :returns: The fetched AlertInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AlertInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AlertInstance: + """ + Asynchronous coroutine to fetch the AlertInstance + + + :returns: The fetched AlertInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AlertInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Monitor.V1.AlertContext {}>".format(context) + + +class AlertPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AlertInstance: + """ + Build an instance of AlertInstance + + :param payload: Payload response from the API + """ + return AlertInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Monitor.V1.AlertPage>" + + +class AlertList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AlertList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Alerts" + + def stream( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AlertInstance]: + """ + Streams AlertInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param datetime start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param datetime end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + log_level=log_level, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AlertInstance]: + """ + Asynchronously streams AlertInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param datetime start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param datetime end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + log_level=log_level, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AlertInstance]: + """ + Lists AlertInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param datetime start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param datetime end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + log_level=log_level, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AlertInstance]: + """ + Asynchronously lists AlertInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param datetime start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param datetime end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + log_level=log_level, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AlertPage: + """ + Retrieve a single page of AlertInstance records from the API. + Request is executed immediately + + :param log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AlertInstance + """ + data = values.of( + { + "LogLevel": log_level, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AlertPage(self._version, response) + + async def page_async( + self, + log_level: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AlertPage: + """ + Asynchronously retrieve a single page of AlertInstance records from the API. + Request is executed immediately + + :param log_level: Only show alerts for this log-level. Can be: `error`, `warning`, `notice`, or `debug`. + :param start_date: Only include alerts that occurred on or after this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param end_date: Only include alerts that occurred on or before this date and time. Specify the date and time in GMT and format as `YYYY-MM-DD` or `YYYY-MM-DDThh:mm:ssZ`. Queries for alerts older than 30 days are not supported. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AlertInstance + """ + data = values.of( + { + "LogLevel": log_level, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AlertPage(self._version, response) + + def get_page(self, target_url: str) -> AlertPage: + """ + Retrieve a specific page of AlertInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AlertInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AlertPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AlertPage: + """ + Asynchronously retrieve a specific page of AlertInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AlertInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AlertPage(self._version, response) + + def get(self, sid: str) -> AlertContext: + """ + Constructs a AlertContext + + :param sid: The SID of the Alert resource to fetch. + """ + return AlertContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AlertContext: + """ + Constructs a AlertContext + + :param sid: The SID of the Alert resource to fetch. + """ + return AlertContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Monitor.V1.AlertList>" diff --git a/twilio/rest/monitor/v1/event.py b/twilio/rest/monitor/v1/event.py new file mode 100644 index 0000000000..61450c872c --- /dev/null +++ b/twilio/rest/monitor/v1/event.py @@ -0,0 +1,541 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Monitor + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EventInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Event resource. + :ivar actor_sid: The SID of the actor that caused the event, if available. This can be either a User ID (matching the pattern `^US[0-9a-fA-F]{32}$`) or an Account SID (matching the pattern `^AC[0-9a-fA-F]{32}$`). If the actor's SID isn't available, this field will be `null`. + :ivar actor_type: The type of actor that caused the event. Can be: `user` for a change made by a logged-in user in the Twilio Console, `account` for an event caused by an API request by an authenticating Account, `twilio-admin` for an event caused by a Twilio employee, and so on. + :ivar description: A description of the event. Can be `null`. + :ivar event_data: An object with additional data about the event. The contents depend on `event_type`. For example, event-types of the form `RESOURCE.updated`, this value contains a `resource_properties` dictionary that describes the previous and updated properties of the resource. + :ivar event_date: The date and time in GMT when the event was recorded specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar event_type: The event's type. Event-types are typically in the form: `RESOURCE_TYPE.ACTION`, where `RESOURCE_TYPE` is the type of resource that was affected and `ACTION` is what happened to it. For example, `phone-number.created`. For a full list of all event-types, see the [Monitor Event Types](https://www.twilio.com/docs/usage/monitor-events#event-types). + :ivar resource_sid: The SID of the resource that was affected. + :ivar resource_type: The type of resource that was affected. For a full list of all resource-types, see the [Monitor Event Types](https://www.twilio.com/docs/usage/monitor-events#event-types). + :ivar sid: The unique string that we created to identify the Event resource. + :ivar source: The originating system or interface that caused the event. Can be: `web` for events caused by user action in the Twilio Console, `api` for events caused by a request to our API, or `twilio` for events caused by an automated or internal Twilio system. + :ivar source_ip_address: The IP address of the source, if the source is outside the Twilio cloud. This value is `null` for events with `source` of `twilio` + :ivar url: The absolute URL of the resource that was affected. Can be `null`. + :ivar links: The absolute URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.actor_sid: Optional[str] = payload.get("actor_sid") + self.actor_type: Optional[str] = payload.get("actor_type") + self.description: Optional[str] = payload.get("description") + self.event_data: Optional[Dict[str, object]] = payload.get("event_data") + self.event_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("event_date") + ) + self.event_type: Optional[str] = payload.get("event_type") + self.resource_sid: Optional[str] = payload.get("resource_sid") + self.resource_type: Optional[str] = payload.get("resource_type") + self.sid: Optional[str] = payload.get("sid") + self.source: Optional[str] = payload.get("source") + self.source_ip_address: Optional[str] = payload.get("source_ip_address") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[EventContext] = None + + @property + def _proxy(self) -> "EventContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EventContext for this EventInstance + """ + if self._context is None: + self._context = EventContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "EventInstance": + """ + Fetch the EventInstance + + + :returns: The fetched EventInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EventInstance": + """ + Asynchronous coroutine to fetch the EventInstance + + + :returns: The fetched EventInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Monitor.V1.EventInstance {}>".format(context) + + +class EventContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the EventContext + + :param version: Version that contains the resource + :param sid: The SID of the Event resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Events/{sid}".format(**self._solution) + + def fetch(self) -> EventInstance: + """ + Fetch the EventInstance + + + :returns: The fetched EventInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EventInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EventInstance: + """ + Asynchronous coroutine to fetch the EventInstance + + + :returns: The fetched EventInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EventInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Monitor.V1.EventContext {}>".format(context) + + +class EventPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EventInstance: + """ + Build an instance of EventInstance + + :param payload: Payload response from the API + """ + return EventInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Monitor.V1.EventPage>" + + +class EventList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the EventList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Events" + + def stream( + self, + actor_sid: Union[str, object] = values.unset, + event_type: Union[str, object] = values.unset, + resource_sid: Union[str, object] = values.unset, + source_ip_address: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EventInstance]: + """ + Streams EventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param str event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param str resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param str source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param datetime start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param datetime end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + actor_sid=actor_sid, + event_type=event_type, + resource_sid=resource_sid, + source_ip_address=source_ip_address, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + actor_sid: Union[str, object] = values.unset, + event_type: Union[str, object] = values.unset, + resource_sid: Union[str, object] = values.unset, + source_ip_address: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EventInstance]: + """ + Asynchronously streams EventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param str event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param str resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param str source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param datetime start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param datetime end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + actor_sid=actor_sid, + event_type=event_type, + resource_sid=resource_sid, + source_ip_address=source_ip_address, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + actor_sid: Union[str, object] = values.unset, + event_type: Union[str, object] = values.unset, + resource_sid: Union[str, object] = values.unset, + source_ip_address: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: + """ + Lists EventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param str event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param str resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param str source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param datetime start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param datetime end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + actor_sid=actor_sid, + event_type=event_type, + resource_sid=resource_sid, + source_ip_address=source_ip_address, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + actor_sid: Union[str, object] = values.unset, + event_type: Union[str, object] = values.unset, + resource_sid: Union[str, object] = values.unset, + source_ip_address: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: + """ + Asynchronously lists EventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param str event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param str resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param str source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param datetime start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param datetime end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + actor_sid=actor_sid, + event_type=event_type, + resource_sid=resource_sid, + source_ip_address=source_ip_address, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + actor_sid: Union[str, object] = values.unset, + event_type: Union[str, object] = values.unset, + resource_sid: Union[str, object] = values.unset, + source_ip_address: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventPage: + """ + Retrieve a single page of EventInstance records from the API. + Request is executed immediately + + :param actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventInstance + """ + data = values.of( + { + "ActorSid": actor_sid, + "EventType": event_type, + "ResourceSid": resource_sid, + "SourceIpAddress": source_ip_address, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response) + + async def page_async( + self, + actor_sid: Union[str, object] = values.unset, + event_type: Union[str, object] = values.unset, + resource_sid: Union[str, object] = values.unset, + source_ip_address: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventPage: + """ + Asynchronously retrieve a single page of EventInstance records from the API. + Request is executed immediately + + :param actor_sid: Only include events initiated by this Actor. Useful for auditing actions taken by specific users or API credentials. + :param event_type: Only include events of this [Event Type](https://www.twilio.com/docs/usage/monitor-events#event-types). + :param resource_sid: Only include events that refer to this resource. Useful for discovering the history of a specific resource. + :param source_ip_address: Only include events that originated from this IP address. Useful for tracking suspicious activity originating from the API or the Twilio Console. + :param start_date: Only include events that occurred on or after this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include events that occurred on or before this date. Specify the date in GMT and [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventInstance + """ + data = values.of( + { + "ActorSid": actor_sid, + "EventType": event_type, + "ResourceSid": resource_sid, + "SourceIpAddress": source_ip_address, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response) + + def get_page(self, target_url: str) -> EventPage: + """ + Retrieve a specific page of EventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EventPage(self._version, response) + + async def get_page_async(self, target_url: str) -> EventPage: + """ + Asynchronously retrieve a specific page of EventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EventPage(self._version, response) + + def get(self, sid: str) -> EventContext: + """ + Constructs a EventContext + + :param sid: The SID of the Event resource to fetch. + """ + return EventContext(self._version, sid=sid) + + def __call__(self, sid: str) -> EventContext: + """ + Constructs a EventContext + + :param sid: The SID of the Event resource to fetch. + """ + return EventContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Monitor.V1.EventList>" diff --git a/twilio/rest/notify/NotifyBase.py b/twilio/rest/notify/NotifyBase.py new file mode 100644 index 0000000000..2772ed0959 --- /dev/null +++ b/twilio/rest/notify/NotifyBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.notify.v1 import V1 + + +class NotifyBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Notify Domain + + :returns: Domain for Notify + """ + super().__init__(twilio, "https://notify.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Notify + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Notify>" diff --git a/twilio/rest/notify/__init__.py b/twilio/rest/notify/__init__.py new file mode 100644 index 0000000000..61f8fafb6b --- /dev/null +++ b/twilio/rest/notify/__init__.py @@ -0,0 +1,25 @@ +from warnings import warn + +from twilio.rest.notify.NotifyBase import NotifyBase +from twilio.rest.notify.v1.credential import CredentialList +from twilio.rest.notify.v1.service import ServiceList + + +class Notify(NotifyBase): + @property + def credentials(self) -> CredentialList: + warn( + "credentials is deprecated. Use v1.credentials instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.credentials + + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v1.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.services diff --git a/twilio/rest/notify/v1/__init__.py b/twilio/rest/notify/v1/__init__.py new file mode 100644 index 0000000000..90cab95028 --- /dev/null +++ b/twilio/rest/notify/v1/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Notify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.notify.v1.credential import CredentialList +from twilio.rest.notify.v1.service import ServiceList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Notify + + :param domain: The Twilio.notify domain + """ + super().__init__(domain, "v1") + self._credentials: Optional[CredentialList] = None + self._services: Optional[ServiceList] = None + + @property + def credentials(self) -> CredentialList: + if self._credentials is None: + self._credentials = CredentialList(self) + return self._credentials + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Notify.V1>" diff --git a/twilio/rest/notify/v1/credential.py b/twilio/rest/notify/v1/credential.py new file mode 100644 index 0000000000..9ca59927cb --- /dev/null +++ b/twilio/rest/notify/v1/credential.py @@ -0,0 +1,711 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Notify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CredentialInstance(InstanceResource): + + class PushService(object): + GCM = "gcm" + APN = "apn" + FCM = "fcm" + + """ + :ivar sid: The unique string that we created to identify the Credential resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Credential resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the Credential resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["CredentialInstance.PushService"] = payload.get("type") + self.sandbox: Optional[str] = payload.get("sandbox") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CredentialContext] = None + + @property + def _proxy(self) -> "CredentialContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CredentialContext for this CredentialInstance + """ + if self._context is None: + self._context = CredentialContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CredentialInstance": + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialInstance": + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> "CredentialInstance": + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + certificate=certificate, + private_key=private_key, + sandbox=sandbox, + api_key=api_key, + secret=secret, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Notify.V1.CredentialInstance {}>".format(context) + + +class CredentialContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CredentialContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Credentials/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialInstance: + """ + Fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialInstance: + """ + Asynchronous coroutine to fetch the CredentialInstance + + + :returns: The fetched CredentialInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronous coroutine to update the CredentialInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: The updated CredentialInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Notify.V1.CredentialContext {}>".format(context) + + +class CredentialPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialInstance: + """ + Build an instance of CredentialInstance + + :param payload: Payload response from the API + """ + return CredentialInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Notify.V1.CredentialPage>" + + +class CredentialList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CredentialList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Credentials" + + def create( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + async def create_async( + self, + type: "CredentialInstance.PushService", + friendly_name: Union[str, object] = values.unset, + certificate: Union[str, object] = values.unset, + private_key: Union[str, object] = values.unset, + sandbox: Union[bool, object] = values.unset, + api_key: Union[str, object] = values.unset, + secret: Union[str, object] = values.unset, + ) -> CredentialInstance: + """ + Asynchronously create the CredentialInstance + + :param type: + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param certificate: [APN only] The URL-encoded representation of the certificate. Strip everything outside of the headers, e.g. `-----BEGIN CERTIFICATE-----MIIFnTCCBIWgAwIBAgIIAjy9H849+E8wDQYJKoZIhvcNAQEFBQAwgZYxCzAJBgNV.....A==-----END CERTIFICATE-----` + :param private_key: [APN only] The URL-encoded representation of the private key. Strip everything outside of the headers, e.g. `-----BEGIN RSA PRIVATE KEY-----MIIEpQIBAAKCAQEAuyf/lNrH9ck8DmNyo3fGgvCI1l9s+cmBY3WIz+cUDqmxiieR\\\\n.-----END RSA PRIVATE KEY-----` + :param sandbox: [APN only] Whether to send the credential to sandbox APNs. Can be `true` to send to sandbox APNs or `false` to send to production. + :param api_key: [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + :param secret: [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud messaging. + + :returns: The created CredentialInstance + """ + + data = values.of( + { + "Type": type, + "FriendlyName": friendly_name, + "Certificate": certificate, + "PrivateKey": private_key, + "Sandbox": serialize.boolean_to_string(sandbox), + "ApiKey": api_key, + "Secret": secret, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialInstance]: + """ + Streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialInstance]: + """ + Asynchronously streams CredentialInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialInstance]: + """ + Asynchronously lists CredentialInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialPage: + """ + Asynchronously retrieve a single page of CredentialInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialPage(self._version, response) + + def get_page(self, target_url: str) -> CredentialPage: + """ + Retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CredentialPage: + """ + Asynchronously retrieve a specific page of CredentialInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialPage(self._version, response) + + def get(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. + """ + return CredentialContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CredentialContext: + """ + Constructs a CredentialContext + + :param sid: The Twilio-provided string that uniquely identifies the Credential resource to update. + """ + return CredentialContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Notify.V1.CredentialList>" diff --git a/twilio/rest/notify/v1/service/__init__.py b/twilio/rest/notify/v1/service/__init__.py new file mode 100644 index 0000000000..e097e69a67 --- /dev/null +++ b/twilio/rest/notify/v1/service/__init__.py @@ -0,0 +1,948 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Notify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.notify.v1.service.binding import BindingList +from twilio.rest.notify.v1.service.notification import NotificationList + + +class ServiceInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Service resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :ivar gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :ivar fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :ivar messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. In order to send SMS notifications this parameter has to be set. + :ivar facebook_messenger_page_id: Deprecated. + :ivar default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :ivar default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :ivar default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :ivar log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :ivar url: The absolute URL of the Service resource. + :ivar links: The URLs of the Binding, Notification, Segment, and User resources related to the service. + :ivar alexa_skill_id: Deprecated. + :ivar default_alexa_notification_protocol_version: Deprecated. + :ivar delivery_callback_url: URL to send delivery status callback. + :ivar delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.apn_credential_sid: Optional[str] = payload.get("apn_credential_sid") + self.gcm_credential_sid: Optional[str] = payload.get("gcm_credential_sid") + self.fcm_credential_sid: Optional[str] = payload.get("fcm_credential_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.facebook_messenger_page_id: Optional[str] = payload.get( + "facebook_messenger_page_id" + ) + self.default_apn_notification_protocol_version: Optional[str] = payload.get( + "default_apn_notification_protocol_version" + ) + self.default_gcm_notification_protocol_version: Optional[str] = payload.get( + "default_gcm_notification_protocol_version" + ) + self.default_fcm_notification_protocol_version: Optional[str] = payload.get( + "default_fcm_notification_protocol_version" + ) + self.log_enabled: Optional[bool] = payload.get("log_enabled") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.alexa_skill_id: Optional[str] = payload.get("alexa_skill_id") + self.default_alexa_notification_protocol_version: Optional[str] = payload.get( + "default_alexa_notification_protocol_version" + ) + self.delivery_callback_url: Optional[str] = payload.get("delivery_callback_url") + self.delivery_callback_enabled: Optional[bool] = payload.get( + "delivery_callback_enabled" + ) + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + apn_credential_sid=apn_credential_sid, + gcm_credential_sid=gcm_credential_sid, + messaging_service_sid=messaging_service_sid, + facebook_messenger_page_id=facebook_messenger_page_id, + default_apn_notification_protocol_version=default_apn_notification_protocol_version, + default_gcm_notification_protocol_version=default_gcm_notification_protocol_version, + fcm_credential_sid=fcm_credential_sid, + default_fcm_notification_protocol_version=default_fcm_notification_protocol_version, + log_enabled=log_enabled, + alexa_skill_id=alexa_skill_id, + default_alexa_notification_protocol_version=default_alexa_notification_protocol_version, + delivery_callback_url=delivery_callback_url, + delivery_callback_enabled=delivery_callback_enabled, + ) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + return self._proxy.bindings + + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + return self._proxy.notifications + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Notify.V1.ServiceInstance {}>".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._bindings: Optional[BindingList] = None + self._notifications: Optional[NotificationList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApnCredentialSid": apn_credential_sid, + "GcmCredentialSid": gcm_credential_sid, + "MessagingServiceSid": messaging_service_sid, + "FacebookMessengerPageId": facebook_messenger_page_id, + "DefaultApnNotificationProtocolVersion": default_apn_notification_protocol_version, + "DefaultGcmNotificationProtocolVersion": default_gcm_notification_protocol_version, + "FcmCredentialSid": fcm_credential_sid, + "DefaultFcmNotificationProtocolVersion": default_fcm_notification_protocol_version, + "LogEnabled": serialize.boolean_to_string(log_enabled), + "AlexaSkillId": alexa_skill_id, + "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, + "DeliveryCallbackUrl": delivery_callback_url, + "DeliveryCallbackEnabled": serialize.boolean_to_string( + delivery_callback_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApnCredentialSid": apn_credential_sid, + "GcmCredentialSid": gcm_credential_sid, + "MessagingServiceSid": messaging_service_sid, + "FacebookMessengerPageId": facebook_messenger_page_id, + "DefaultApnNotificationProtocolVersion": default_apn_notification_protocol_version, + "DefaultGcmNotificationProtocolVersion": default_gcm_notification_protocol_version, + "FcmCredentialSid": fcm_credential_sid, + "DefaultFcmNotificationProtocolVersion": default_fcm_notification_protocol_version, + "LogEnabled": serialize.boolean_to_string(log_enabled), + "AlexaSkillId": alexa_skill_id, + "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, + "DeliveryCallbackUrl": delivery_callback_url, + "DeliveryCallbackEnabled": serialize.boolean_to_string( + delivery_callback_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def bindings(self) -> BindingList: + """ + Access the bindings + """ + if self._bindings is None: + self._bindings = BindingList( + self._version, + self._solution["sid"], + ) + return self._bindings + + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + if self._notifications is None: + self._notifications = NotificationList( + self._version, + self._solution["sid"], + ) + return self._notifications + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Notify.V1.ServiceContext {}>".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Notify.V1.ServicePage>" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApnCredentialSid": apn_credential_sid, + "GcmCredentialSid": gcm_credential_sid, + "MessagingServiceSid": messaging_service_sid, + "FacebookMessengerPageId": facebook_messenger_page_id, + "DefaultApnNotificationProtocolVersion": default_apn_notification_protocol_version, + "DefaultGcmNotificationProtocolVersion": default_gcm_notification_protocol_version, + "FcmCredentialSid": fcm_credential_sid, + "DefaultFcmNotificationProtocolVersion": default_fcm_notification_protocol_version, + "LogEnabled": serialize.boolean_to_string(log_enabled), + "AlexaSkillId": alexa_skill_id, + "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, + "DeliveryCallbackUrl": delivery_callback_url, + "DeliveryCallbackEnabled": serialize.boolean_to_string( + delivery_callback_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async( + self, + friendly_name: Union[str, object] = values.unset, + apn_credential_sid: Union[str, object] = values.unset, + gcm_credential_sid: Union[str, object] = values.unset, + messaging_service_sid: Union[str, object] = values.unset, + facebook_messenger_page_id: Union[str, object] = values.unset, + default_apn_notification_protocol_version: Union[str, object] = values.unset, + default_gcm_notification_protocol_version: Union[str, object] = values.unset, + fcm_credential_sid: Union[str, object] = values.unset, + default_fcm_notification_protocol_version: Union[str, object] = values.unset, + log_enabled: Union[bool, object] = values.unset, + alexa_skill_id: Union[str, object] = values.unset, + default_alexa_notification_protocol_version: Union[str, object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + delivery_callback_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. + :param gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :param facebook_messenger_page_id: Deprecated. + :param default_apn_notification_protocol_version: The protocol version to use for sending APNS notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param default_gcm_notification_protocol_version: The protocol version to use for sending GCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. + :param default_fcm_notification_protocol_version: The protocol version to use for sending FCM notifications. Can be overridden on a Binding by Binding basis when creating a [Binding](https://www.twilio.com/docs/notify/api/binding-resource) resource. + :param log_enabled: Whether to log notifications. Can be: `true` or `false` and the default is `true`. + :param alexa_skill_id: Deprecated. + :param default_alexa_notification_protocol_version: Deprecated. + :param delivery_callback_url: URL to send delivery status callback. + :param delivery_callback_enabled: Callback configuration that enables delivery callbacks, default false + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ApnCredentialSid": apn_credential_sid, + "GcmCredentialSid": gcm_credential_sid, + "MessagingServiceSid": messaging_service_sid, + "FacebookMessengerPageId": facebook_messenger_page_id, + "DefaultApnNotificationProtocolVersion": default_apn_notification_protocol_version, + "DefaultGcmNotificationProtocolVersion": default_gcm_notification_protocol_version, + "FcmCredentialSid": fcm_credential_sid, + "DefaultFcmNotificationProtocolVersion": default_fcm_notification_protocol_version, + "LogEnabled": serialize.boolean_to_string(log_enabled), + "AlexaSkillId": alexa_skill_id, + "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, + "DeliveryCallbackUrl": delivery_callback_url, + "DeliveryCallbackEnabled": serialize.boolean_to_string( + delivery_callback_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The string that identifies the Service resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The string that identifies the Service resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The string that identifies the Service resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The string that identifies the Service resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param friendly_name: The string that identifies the Service resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param friendly_name: The string that identifies the Service resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Notify.V1.ServiceList>" diff --git a/twilio/rest/notify/v1/service/binding.py b/twilio/rest/notify/v1/service/binding.py new file mode 100644 index 0000000000..33b1a4aac0 --- /dev/null +++ b/twilio/rest/notify/v1/service/binding.py @@ -0,0 +1,681 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Notify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date, datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class BindingInstance(InstanceResource): + + class BindingType(object): + APN = "apn" + GCM = "gcm" + SMS = "sms" + FCM = "fcm" + FACEBOOK_MESSENGER = "facebook-messenger" + ALEXA = "alexa" + + """ + :ivar sid: The unique string that we created to identify the Binding resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Binding resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/notify/api/service-resource) the resource is associated with. + :ivar credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) resource to be used to send notifications to this Binding. If present, this overrides the Credential specified in the Service resource. Applicable only to `apn`, `fcm`, and `gcm` type Bindings. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar notification_protocol_version: The protocol version to use to send the notification. This defaults to the value of `default_xxxx_notification_protocol_version` in the [Service](https://www.twilio.com/docs/notify/api/service-resource) for the protocol. The current version is `\"3\"` for `apn`, `fcm`, and `gcm` type Bindings. The parameter is not applicable to `sms` and `facebook-messenger` type Bindings as the data format is fixed. + :ivar endpoint: Deprecated. + :ivar identity: The `identity` value that uniquely identifies the resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Up to 20 Bindings can be created for the same Identity in a given Service. + :ivar binding_type: The transport technology to use for the Binding. Can be: `apn`, `fcm`, `gcm`, `sms`, or `facebook-messenger`. + :ivar address: The channel-specific address. For APNS, the device token. For FCM and GCM, the registration token. For SMS, a phone number in E.164 format. For Facebook Messenger, the Messenger ID of the user or a phone number in E.164 format. + :ivar tags: The list of tags associated with this Binding. Tags can be used to select the Bindings to use when sending a notification. Maximum 20 tags are allowed. + :ivar url: The absolute URL of the Binding resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.credential_sid: Optional[str] = payload.get("credential_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.notification_protocol_version: Optional[str] = payload.get( + "notification_protocol_version" + ) + self.endpoint: Optional[str] = payload.get("endpoint") + self.identity: Optional[str] = payload.get("identity") + self.binding_type: Optional[str] = payload.get("binding_type") + self.address: Optional[str] = payload.get("address") + self.tags: Optional[List[str]] = payload.get("tags") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[BindingContext] = None + + @property + def _proxy(self) -> "BindingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BindingContext for this BindingInstance + """ + if self._context is None: + self._context = BindingContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "BindingInstance": + """ + Fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BindingInstance": + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Notify.V1.BindingInstance {}>".format(context) + + +class BindingContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the BindingContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/notify/api/service-resource) to fetch the resource from. + :param sid: The Twilio-provided string that uniquely identifies the Binding resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Bindings/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BindingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> BindingInstance: + """ + Fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> BindingInstance: + """ + Asynchronous coroutine to fetch the BindingInstance + + + :returns: The fetched BindingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Notify.V1.BindingContext {}>".format(context) + + +class BindingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: + """ + Build an instance of BindingInstance + + :param payload: Payload response from the API + """ + return BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Notify.V1.BindingPage>" + + +class BindingList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the BindingList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/notify/api/service-resource) to read the resource from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Bindings".format(**self._solution) + + def create( + self, + identity: str, + binding_type: "BindingInstance.BindingType", + address: str, + tag: Union[List[str], object] = values.unset, + notification_protocol_version: Union[str, object] = values.unset, + credential_sid: Union[str, object] = values.unset, + endpoint: Union[str, object] = values.unset, + ) -> BindingInstance: + """ + Create the BindingInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Up to 20 Bindings can be created for the same Identity in a given Service. + :param binding_type: + :param address: The channel-specific address. For APNS, the device token. For FCM and GCM, the registration token. For SMS, a phone number in E.164 format. For Facebook Messenger, the Messenger ID of the user or a phone number in E.164 format. + :param tag: A tag that can be used to select the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 20 tags. + :param notification_protocol_version: The protocol version to use to send the notification. This defaults to the value of `default_xxxx_notification_protocol_version` for the protocol in the [Service](https://www.twilio.com/docs/notify/api/service-resource). The current version is `\\\"3\\\"` for `apn`, `fcm`, and `gcm` type Bindings. The parameter is not applicable to `sms` and `facebook-messenger` type Bindings as the data format is fixed. + :param credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) resource to be used to send notifications to this Binding. If present, this overrides the Credential specified in the Service resource. Applies to only `apn`, `fcm`, and `gcm` type Bindings. + :param endpoint: Deprecated. + + :returns: The created BindingInstance + """ + + data = values.of( + { + "Identity": identity, + "BindingType": binding_type, + "Address": address, + "Tag": serialize.map(tag, lambda e: e), + "NotificationProtocolVersion": notification_protocol_version, + "CredentialSid": credential_sid, + "Endpoint": endpoint, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + identity: str, + binding_type: "BindingInstance.BindingType", + address: str, + tag: Union[List[str], object] = values.unset, + notification_protocol_version: Union[str, object] = values.unset, + credential_sid: Union[str, object] = values.unset, + endpoint: Union[str, object] = values.unset, + ) -> BindingInstance: + """ + Asynchronously create the BindingInstance + + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Up to 20 Bindings can be created for the same Identity in a given Service. + :param binding_type: + :param address: The channel-specific address. For APNS, the device token. For FCM and GCM, the registration token. For SMS, a phone number in E.164 format. For Facebook Messenger, the Messenger ID of the user or a phone number in E.164 format. + :param tag: A tag that can be used to select the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 20 tags. + :param notification_protocol_version: The protocol version to use to send the notification. This defaults to the value of `default_xxxx_notification_protocol_version` for the protocol in the [Service](https://www.twilio.com/docs/notify/api/service-resource). The current version is `\\\"3\\\"` for `apn`, `fcm`, and `gcm` type Bindings. The parameter is not applicable to `sms` and `facebook-messenger` type Bindings as the data format is fixed. + :param credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) resource to be used to send notifications to this Binding. If present, this overrides the Credential specified in the Service resource. Applies to only `apn`, `fcm`, and `gcm` type Bindings. + :param endpoint: Deprecated. + + :returns: The created BindingInstance + """ + + data = values.of( + { + "Identity": identity, + "BindingType": binding_type, + "Address": address, + "Tag": serialize.map(tag, lambda e: e), + "NotificationProtocolVersion": notification_protocol_version, + "CredentialSid": credential_sid, + "Endpoint": endpoint, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BindingInstance]: + """ + Streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param List[str] tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + start_date=start_date, + end_date=end_date, + identity=identity, + tag=tag, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BindingInstance]: + """ + Asynchronously streams BindingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param List[str] tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + start_date=start_date, + end_date=end_date, + identity=identity, + tag=tag, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BindingInstance]: + """ + Lists BindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param List[str] tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + start_date=start_date, + end_date=end_date, + identity=identity, + tag=tag, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BindingInstance]: + """ + Asynchronously lists BindingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param date start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param date end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param List[str] identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param List[str] tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + start_date=start_date, + end_date=end_date, + identity=identity, + tag=tag, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BindingPage: + """ + Retrieve a single page of BindingInstance records from the API. + Request is executed immediately + + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BindingInstance + """ + data = values.of( + { + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "Identity": serialize.map(identity, lambda e: e), + "Tag": serialize.map(tag, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BindingPage(self._version, response, self._solution) + + async def page_async( + self, + start_date: Union[date, object] = values.unset, + end_date: Union[date, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BindingPage: + """ + Asynchronously retrieve a single page of BindingInstance records from the API. + Request is executed immediately + + :param start_date: Only include usage that has occurred on or after this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param end_date: Only include usage that occurred on or before this date. Specify the date in GMT and format as `YYYY-MM-DD`. + :param identity: The [User](https://www.twilio.com/docs/chat/rest/user-resource)'s `identity` value of the resources to read. + :param tag: Only list Bindings that have all of the specified Tags. The following implicit tags are available: `all`, `apn`, `fcm`, `gcm`, `sms`, `facebook-messenger`. Up to 5 tags are allowed. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BindingInstance + """ + data = values.of( + { + "StartDate": serialize.iso8601_date(start_date), + "EndDate": serialize.iso8601_date(end_date), + "Identity": serialize.map(identity, lambda e: e), + "Tag": serialize.map(tag, lambda e: e), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BindingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> BindingPage: + """ + Retrieve a specific page of BindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BindingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BindingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> BindingPage: + """ + Asynchronously retrieve a specific page of BindingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BindingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BindingPage(self._version, response, self._solution) + + def get(self, sid: str) -> BindingContext: + """ + Constructs a BindingContext + + :param sid: The Twilio-provided string that uniquely identifies the Binding resource to fetch. + """ + return BindingContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> BindingContext: + """ + Constructs a BindingContext + + :param sid: The Twilio-provided string that uniquely identifies the Binding resource to fetch. + """ + return BindingContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Notify.V1.BindingList>" diff --git a/twilio/rest/notify/v1/service/notification.py b/twilio/rest/notify/v1/service/notification.py new file mode 100644 index 0000000000..4d228e864f --- /dev/null +++ b/twilio/rest/notify/v1/service/notification.py @@ -0,0 +1,285 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Notify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NotificationInstance(InstanceResource): + + class Priority(object): + HIGH = "high" + LOW = "low" + + """ + :ivar sid: The unique string that we created to identify the Notification resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Notification resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/notify/api/service-resource) the resource is associated with. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar identities: The list of `identity` values of the Users to notify. We will attempt to deliver notifications only to Bindings with an identity in this list. + :ivar tags: The tags that select the Bindings to notify. Notifications will be attempted only to Bindings that have all of the tags listed in this property. + :ivar segments: The list of Segments to notify. The [Segment](https://www.twilio.com/docs/notify/api/segment-resource) resource is deprecated. Use the `tags` property, instead. + :ivar priority: + :ivar ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 2,419,200, which is 4 weeks, the default and the maximum supported time to live (TTL). Delivery should be attempted if the device is offline until the TTL elapses. Zero means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. SMS does not support this property. + :ivar title: The notification title. For FCM and GCM, this translates to the `data.twi_title` value. For APNS, this translates to the `aps.alert.title` value. SMS does not support this property. This field is not visible on iOS phones and tablets but appears on Apple Watch and Android devices. + :ivar body: The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. + :ivar sound: The name of the sound to be played for the notification. For FCM and GCM, this Translates to `data.twi_sound`. For APNS, this translates to `aps.sound`. SMS does not support this property. + :ivar action: The actions to display for the notification. For APNS, translates to the `aps.category` value. For GCM, translates to the `data.twi_action` value. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :ivar data: The custom key-value pairs of the notification's payload. For FCM and GCM, this value translates to `data` in the FCM and GCM payloads. FCM and GCM [reserve certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that cannot be used in those channels. For APNS, attributes of `data` are inserted into the APNS payload as custom properties outside of the `aps` dictionary. In all channels, we reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed and are rejected as 400 Bad request with no delivery attempted. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :ivar apn: The APNS-specific payload that overrides corresponding attributes in the generic payload for APNS Bindings. This property maps to the APNS `Payload` item, therefore the `aps` key must be used to change standard attributes. Adds custom key-value pairs to the root of the dictionary. See the [APNS documentation](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) for more details. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + :ivar gcm: The GCM-specific payload that overrides corresponding attributes in the generic payload for GCM Bindings. This property maps to the root JSON dictionary. Target parameters `to`, `registration_ids`, and `notification_key` are not allowed. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + :ivar fcm: The FCM-specific payload that overrides corresponding attributes in the generic payload for FCM Bindings. This property maps to the root JSON dictionary. See the [FCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream) for more details. Target parameters `to`, `registration_ids`, `condition`, and `notification_key` are not allowed in this parameter. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. FCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref), which cannot be used in that channel. + :ivar sms: The SMS-specific payload that overrides corresponding attributes in the generic payload for SMS Bindings. Each attribute in this value maps to the corresponding `form` parameter of the Twilio [Message](https://www.twilio.com/docs/sms/api/message-resource) resource. These parameters of the Message resource are supported in snake case format: `body`, `media_urls`, `status_callback`, and `max_price`. The `status_callback` parameter overrides the corresponding parameter in the messaging service, if configured. The `media_urls` property expects a JSON array. + :ivar facebook_messenger: Deprecated. + :ivar alexa: Deprecated. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], service_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.identities: Optional[List[str]] = payload.get("identities") + self.tags: Optional[List[str]] = payload.get("tags") + self.segments: Optional[List[str]] = payload.get("segments") + self.priority: Optional["NotificationInstance.Priority"] = payload.get( + "priority" + ) + self.ttl: Optional[int] = deserialize.integer(payload.get("ttl")) + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.sound: Optional[str] = payload.get("sound") + self.action: Optional[str] = payload.get("action") + self.data: Optional[Dict[str, object]] = payload.get("data") + self.apn: Optional[Dict[str, object]] = payload.get("apn") + self.gcm: Optional[Dict[str, object]] = payload.get("gcm") + self.fcm: Optional[Dict[str, object]] = payload.get("fcm") + self.sms: Optional[Dict[str, object]] = payload.get("sms") + self.facebook_messenger: Optional[Dict[str, object]] = payload.get( + "facebook_messenger" + ) + self.alexa: Optional[Dict[str, object]] = payload.get("alexa") + + self._solution = { + "service_sid": service_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Notify.V1.NotificationInstance {}>".format(context) + + +class NotificationList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the NotificationList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/notify/api/service-resource) to create the resource under. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Notifications".format(**self._solution) + + def create( + self, + body: Union[str, object] = values.unset, + priority: Union["NotificationInstance.Priority", object] = values.unset, + ttl: Union[int, object] = values.unset, + title: Union[str, object] = values.unset, + sound: Union[str, object] = values.unset, + action: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + apn: Union[object, object] = values.unset, + gcm: Union[object, object] = values.unset, + sms: Union[object, object] = values.unset, + facebook_messenger: Union[object, object] = values.unset, + fcm: Union[object, object] = values.unset, + segment: Union[List[str], object] = values.unset, + alexa: Union[object, object] = values.unset, + to_binding: Union[List[str], object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + ) -> NotificationInstance: + """ + Create the NotificationInstance + + :param body: The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. + :param priority: + :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 2,419,200, which is 4 weeks, the default and the maximum supported time to live (TTL). Delivery should be attempted if the device is offline until the TTL elapses. Zero means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. SMS does not support this property. + :param title: The notification title. For FCM and GCM, this translates to the `data.twi_title` value. For APNS, this translates to the `aps.alert.title` value. SMS does not support this property. This field is not visible on iOS phones and tablets but appears on Apple Watch and Android devices. + :param sound: The name of the sound to be played for the notification. For FCM and GCM, this Translates to `data.twi_sound`. For APNS, this translates to `aps.sound`. SMS does not support this property. + :param action: The actions to display for the notification. For APNS, translates to the `aps.category` value. For GCM, translates to the `data.twi_action` value. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param data: The custom key-value pairs of the notification's payload. For FCM and GCM, this value translates to `data` in the FCM and GCM payloads. FCM and GCM [reserve certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that cannot be used in those channels. For APNS, attributes of `data` are inserted into the APNS payload as custom properties outside of the `aps` dictionary. In all channels, we reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed and are rejected as 400 Bad request with no delivery attempted. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param apn: The APNS-specific payload that overrides corresponding attributes in the generic payload for APNS Bindings. This property maps to the APNS `Payload` item, therefore the `aps` key must be used to change standard attributes. Adds custom key-value pairs to the root of the dictionary. See the [APNS documentation](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) for more details. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + :param gcm: The GCM-specific payload that overrides corresponding attributes in the generic payload for GCM Bindings. This property maps to the root JSON dictionary. See the [GCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref) for more details. Target parameters `to`, `registration_ids`, and `notification_key` are not allowed. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. GCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref). + :param sms: The SMS-specific payload that overrides corresponding attributes in the generic payload for SMS Bindings. Each attribute in this value maps to the corresponding `form` parameter of the Twilio [Message](https://www.twilio.com/docs/sms/quickstart) resource. These parameters of the Message resource are supported in snake case format: `body`, `media_urls`, `status_callback`, and `max_price`. The `status_callback` parameter overrides the corresponding parameter in the messaging service, if configured. The `media_urls` property expects a JSON array. + :param facebook_messenger: Deprecated. + :param fcm: The FCM-specific payload that overrides corresponding attributes in the generic payload for FCM Bindings. This property maps to the root JSON dictionary. See the [FCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream) for more details. Target parameters `to`, `registration_ids`, `condition`, and `notification_key` are not allowed in this parameter. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. FCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref), which cannot be used in that channel. + :param segment: The Segment resource is deprecated. Use the `tag` parameter, instead. + :param alexa: Deprecated. + :param to_binding: The destination address specified as a JSON string. Multiple `to_binding` parameters can be included but the total size of the request entity should not exceed 1MB. This is typically sufficient for 10,000 phone numbers. + :param delivery_callback_url: URL to send webhooks. + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Delivery will be attempted only to Bindings with an Identity in this list. No more than 20 items are allowed in this list. + :param tag: A tag that selects the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 5 tags. The implicit tag `all` is available to notify all Bindings in a Service instance. Similarly, the implicit tags `apn`, `fcm`, `gcm`, `sms` and `facebook-messenger` are available to notify all Bindings in a specific channel. + + :returns: The created NotificationInstance + """ + + data = values.of( + { + "Body": body, + "Priority": priority, + "Ttl": ttl, + "Title": title, + "Sound": sound, + "Action": action, + "Data": serialize.object(data), + "Apn": serialize.object(apn), + "Gcm": serialize.object(gcm), + "Sms": serialize.object(sms), + "FacebookMessenger": serialize.object(facebook_messenger), + "Fcm": serialize.object(fcm), + "Segment": serialize.map(segment, lambda e: e), + "Alexa": serialize.object(alexa), + "ToBinding": serialize.map(to_binding, lambda e: e), + "DeliveryCallbackUrl": delivery_callback_url, + "Identity": serialize.map(identity, lambda e: e), + "Tag": serialize.map(tag, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NotificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + body: Union[str, object] = values.unset, + priority: Union["NotificationInstance.Priority", object] = values.unset, + ttl: Union[int, object] = values.unset, + title: Union[str, object] = values.unset, + sound: Union[str, object] = values.unset, + action: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + apn: Union[object, object] = values.unset, + gcm: Union[object, object] = values.unset, + sms: Union[object, object] = values.unset, + facebook_messenger: Union[object, object] = values.unset, + fcm: Union[object, object] = values.unset, + segment: Union[List[str], object] = values.unset, + alexa: Union[object, object] = values.unset, + to_binding: Union[List[str], object] = values.unset, + delivery_callback_url: Union[str, object] = values.unset, + identity: Union[List[str], object] = values.unset, + tag: Union[List[str], object] = values.unset, + ) -> NotificationInstance: + """ + Asynchronously create the NotificationInstance + + :param body: The notification text. For FCM and GCM, translates to `data.twi_body`. For APNS, translates to `aps.alert.body`. For SMS, translates to `body`. SMS requires either this `body` value, or `media_urls` attribute defined in the `sms` parameter of the notification. + :param priority: + :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 2,419,200, which is 4 weeks, the default and the maximum supported time to live (TTL). Delivery should be attempted if the device is offline until the TTL elapses. Zero means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. SMS does not support this property. + :param title: The notification title. For FCM and GCM, this translates to the `data.twi_title` value. For APNS, this translates to the `aps.alert.title` value. SMS does not support this property. This field is not visible on iOS phones and tablets but appears on Apple Watch and Android devices. + :param sound: The name of the sound to be played for the notification. For FCM and GCM, this Translates to `data.twi_sound`. For APNS, this translates to `aps.sound`. SMS does not support this property. + :param action: The actions to display for the notification. For APNS, translates to the `aps.category` value. For GCM, translates to the `data.twi_action` value. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param data: The custom key-value pairs of the notification's payload. For FCM and GCM, this value translates to `data` in the FCM and GCM payloads. FCM and GCM [reserve certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref) that cannot be used in those channels. For APNS, attributes of `data` are inserted into the APNS payload as custom properties outside of the `aps` dictionary. In all channels, we reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed and are rejected as 400 Bad request with no delivery attempted. For SMS, this parameter is not supported and is omitted from deliveries to those channels. + :param apn: The APNS-specific payload that overrides corresponding attributes in the generic payload for APNS Bindings. This property maps to the APNS `Payload` item, therefore the `aps` key must be used to change standard attributes. Adds custom key-value pairs to the root of the dictionary. See the [APNS documentation](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingwithAPNs.html) for more details. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. + :param gcm: The GCM-specific payload that overrides corresponding attributes in the generic payload for GCM Bindings. This property maps to the root JSON dictionary. See the [GCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref) for more details. Target parameters `to`, `registration_ids`, and `notification_key` are not allowed. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. GCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref). + :param sms: The SMS-specific payload that overrides corresponding attributes in the generic payload for SMS Bindings. Each attribute in this value maps to the corresponding `form` parameter of the Twilio [Message](https://www.twilio.com/docs/sms/quickstart) resource. These parameters of the Message resource are supported in snake case format: `body`, `media_urls`, `status_callback`, and `max_price`. The `status_callback` parameter overrides the corresponding parameter in the messaging service, if configured. The `media_urls` property expects a JSON array. + :param facebook_messenger: Deprecated. + :param fcm: The FCM-specific payload that overrides corresponding attributes in the generic payload for FCM Bindings. This property maps to the root JSON dictionary. See the [FCM documentation](https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream) for more details. Target parameters `to`, `registration_ids`, `condition`, and `notification_key` are not allowed in this parameter. We reserve keys that start with `twi_` for future use. Custom keys that start with `twi_` are not allowed. FCM also [reserves certain keys](https://firebase.google.com/docs/cloud-messaging/http-server-ref), which cannot be used in that channel. + :param segment: The Segment resource is deprecated. Use the `tag` parameter, instead. + :param alexa: Deprecated. + :param to_binding: The destination address specified as a JSON string. Multiple `to_binding` parameters can be included but the total size of the request entity should not exceed 1MB. This is typically sufficient for 10,000 phone numbers. + :param delivery_callback_url: URL to send webhooks. + :param identity: The `identity` value that uniquely identifies the new resource's [User](https://www.twilio.com/docs/chat/rest/user-resource) within the [Service](https://www.twilio.com/docs/notify/api/service-resource). Delivery will be attempted only to Bindings with an Identity in this list. No more than 20 items are allowed in this list. + :param tag: A tag that selects the Bindings to notify. Repeat this parameter to specify more than one tag, up to a total of 5 tags. The implicit tag `all` is available to notify all Bindings in a Service instance. Similarly, the implicit tags `apn`, `fcm`, `gcm`, `sms` and `facebook-messenger` are available to notify all Bindings in a specific channel. + + :returns: The created NotificationInstance + """ + + data = values.of( + { + "Body": body, + "Priority": priority, + "Ttl": ttl, + "Title": title, + "Sound": sound, + "Action": action, + "Data": serialize.object(data), + "Apn": serialize.object(apn), + "Gcm": serialize.object(gcm), + "Sms": serialize.object(sms), + "FacebookMessenger": serialize.object(facebook_messenger), + "Fcm": serialize.object(fcm), + "Segment": serialize.map(segment, lambda e: e), + "Alexa": serialize.object(alexa), + "ToBinding": serialize.map(to_binding, lambda e: e), + "DeliveryCallbackUrl": delivery_callback_url, + "Identity": serialize.map(identity, lambda e: e), + "Tag": serialize.map(tag, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NotificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Notify.V1.NotificationList>" diff --git a/twilio/rest/numbers/NumbersBase.py b/twilio/rest/numbers/NumbersBase.py new file mode 100644 index 0000000000..7b9e08638f --- /dev/null +++ b/twilio/rest/numbers/NumbersBase.py @@ -0,0 +1,55 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.numbers.v1 import V1 +from twilio.rest.numbers.v2 import V2 + + +class NumbersBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Numbers Domain + + :returns: Domain for Numbers + """ + super().__init__(twilio, "https://numbers.twilio.com") + self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Numbers + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Numbers + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Numbers>" diff --git a/twilio/rest/numbers/__init__.py b/twilio/rest/numbers/__init__.py new file mode 100644 index 0000000000..abe9985d75 --- /dev/null +++ b/twilio/rest/numbers/__init__.py @@ -0,0 +1,15 @@ +from warnings import warn + +from twilio.rest.numbers.NumbersBase import NumbersBase +from twilio.rest.numbers.v2.regulatory_compliance import RegulatoryComplianceList + + +class Numbers(NumbersBase): + @property + def regulatory_compliance(self) -> RegulatoryComplianceList: + warn( + "regulatory_compliance is deprecated. Use v2.regulatory_compliance instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.regulatory_compliance diff --git a/twilio/rest/numbers/v1/__init__.py b/twilio/rest/numbers/v1/__init__.py new file mode 100644 index 0000000000..043364c3d5 --- /dev/null +++ b/twilio/rest/numbers/v1/__init__.py @@ -0,0 +1,135 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.numbers.v1.bulk_eligibility import BulkEligibilityList +from twilio.rest.numbers.v1.eligibility import EligibilityList +from twilio.rest.numbers.v1.porting_port_in import PortingPortInList +from twilio.rest.numbers.v1.porting_port_in_phone_number import ( + PortingPortInPhoneNumberList, +) +from twilio.rest.numbers.v1.porting_portability import PortingPortabilityList +from twilio.rest.numbers.v1.porting_webhook_configuration import ( + PortingWebhookConfigurationList, +) +from twilio.rest.numbers.v1.porting_webhook_configuration_delete import ( + PortingWebhookConfigurationDeleteList, +) +from twilio.rest.numbers.v1.porting_webhook_configuration_fetch import ( + PortingWebhookConfigurationFetchList, +) +from twilio.rest.numbers.v1.signing_request_configuration import ( + SigningRequestConfigurationList, +) + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Numbers + + :param domain: The Twilio.numbers domain + """ + super().__init__(domain, "v1") + self._bulk_eligibilities: Optional[BulkEligibilityList] = None + self._eligibilities: Optional[EligibilityList] = None + self._porting_port_ins: Optional[PortingPortInList] = None + self._porting_port_in_phone_number: Optional[PortingPortInPhoneNumberList] = ( + None + ) + self._porting_portabilities: Optional[PortingPortabilityList] = None + self._porting_webhook_configurations: Optional[ + PortingWebhookConfigurationList + ] = None + self._porting_webhook_configurations_delete: Optional[ + PortingWebhookConfigurationDeleteList + ] = None + self._porting_webhook_configuration_fetch: Optional[ + PortingWebhookConfigurationFetchList + ] = None + self._signing_request_configurations: Optional[ + SigningRequestConfigurationList + ] = None + + @property + def bulk_eligibilities(self) -> BulkEligibilityList: + if self._bulk_eligibilities is None: + self._bulk_eligibilities = BulkEligibilityList(self) + return self._bulk_eligibilities + + @property + def eligibilities(self) -> EligibilityList: + if self._eligibilities is None: + self._eligibilities = EligibilityList(self) + return self._eligibilities + + @property + def porting_port_ins(self) -> PortingPortInList: + if self._porting_port_ins is None: + self._porting_port_ins = PortingPortInList(self) + return self._porting_port_ins + + @property + def porting_port_in_phone_number(self) -> PortingPortInPhoneNumberList: + if self._porting_port_in_phone_number is None: + self._porting_port_in_phone_number = PortingPortInPhoneNumberList(self) + return self._porting_port_in_phone_number + + @property + def porting_portabilities(self) -> PortingPortabilityList: + if self._porting_portabilities is None: + self._porting_portabilities = PortingPortabilityList(self) + return self._porting_portabilities + + @property + def porting_webhook_configurations(self) -> PortingWebhookConfigurationList: + if self._porting_webhook_configurations is None: + self._porting_webhook_configurations = PortingWebhookConfigurationList(self) + return self._porting_webhook_configurations + + @property + def porting_webhook_configurations_delete( + self, + ) -> PortingWebhookConfigurationDeleteList: + if self._porting_webhook_configurations_delete is None: + self._porting_webhook_configurations_delete = ( + PortingWebhookConfigurationDeleteList(self) + ) + return self._porting_webhook_configurations_delete + + @property + def porting_webhook_configuration_fetch( + self, + ) -> PortingWebhookConfigurationFetchList: + if self._porting_webhook_configuration_fetch is None: + self._porting_webhook_configuration_fetch = ( + PortingWebhookConfigurationFetchList(self) + ) + return self._porting_webhook_configuration_fetch + + @property + def signing_request_configurations(self) -> SigningRequestConfigurationList: + if self._signing_request_configurations is None: + self._signing_request_configurations = SigningRequestConfigurationList(self) + return self._signing_request_configurations + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V1>" diff --git a/twilio/rest/numbers/v1/bulk_eligibility.py b/twilio/rest/numbers/v1/bulk_eligibility.py new file mode 100644 index 0000000000..766032f7c4 --- /dev/null +++ b/twilio/rest/numbers/v1/bulk_eligibility.py @@ -0,0 +1,257 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class BulkEligibilityInstance(InstanceResource): + """ + :ivar request_id: The SID of the bulk eligibility check that you want to know about. + :ivar url: This is the url of the request that you're trying to reach out to locate the resource. + :ivar results: The result set that contains the eligibility check response for each requested number, each result has at least the following attributes: phone_number: The requested phone number ,hosting_account_sid: The account sid where the phone number will be hosted, country: Phone number’s country, eligibility_status: Indicates the eligibility status of the PN (Eligible/Ineligible), eligibility_sub_status: Indicates the sub status of the eligibility , ineligibility_reason: Reason for number's ineligibility (if applicable), next_step: Suggested next step in the hosting process based on the eligibility status. + :ivar friendly_name: This is the string that you assigned as a friendly name for describing the eligibility check request. + :ivar status: This is the status of the bulk eligibility check request. (Example: COMPLETE, IN_PROGRESS) + :ivar date_created: + :ivar date_completed: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + request_id: Optional[str] = None, + ): + super().__init__(version) + + self.request_id: Optional[str] = payload.get("request_id") + self.url: Optional[str] = payload.get("url") + self.results: Optional[List[Dict[str, object]]] = payload.get("results") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional[str] = payload.get("status") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_completed: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_completed") + ) + + self._solution = { + "request_id": request_id or self.request_id, + } + self._context: Optional[BulkEligibilityContext] = None + + @property + def _proxy(self) -> "BulkEligibilityContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BulkEligibilityContext for this BulkEligibilityInstance + """ + if self._context is None: + self._context = BulkEligibilityContext( + self._version, + request_id=self._solution["request_id"], + ) + return self._context + + def fetch(self) -> "BulkEligibilityInstance": + """ + Fetch the BulkEligibilityInstance + + + :returns: The fetched BulkEligibilityInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BulkEligibilityInstance": + """ + Asynchronous coroutine to fetch the BulkEligibilityInstance + + + :returns: The fetched BulkEligibilityInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V1.BulkEligibilityInstance {}>".format(context) + + +class BulkEligibilityContext(InstanceContext): + + def __init__(self, version: Version, request_id: str): + """ + Initialize the BulkEligibilityContext + + :param version: Version that contains the resource + :param request_id: The SID of the bulk eligibility check that you want to know about. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "request_id": request_id, + } + self._uri = "/HostedNumber/Eligibility/Bulk/{request_id}".format( + **self._solution + ) + + def fetch(self) -> BulkEligibilityInstance: + """ + Fetch the BulkEligibilityInstance + + + :returns: The fetched BulkEligibilityInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return BulkEligibilityInstance( + self._version, + payload, + request_id=self._solution["request_id"], + ) + + async def fetch_async(self) -> BulkEligibilityInstance: + """ + Asynchronous coroutine to fetch the BulkEligibilityInstance + + + :returns: The fetched BulkEligibilityInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return BulkEligibilityInstance( + self._version, + payload, + request_id=self._solution["request_id"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V1.BulkEligibilityContext {}>".format(context) + + +class BulkEligibilityList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BulkEligibilityList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/HostedNumber/Eligibility/Bulk" + + def create( + self, body: Union[object, object] = values.unset + ) -> BulkEligibilityInstance: + """ + Create the BulkEligibilityInstance + + :param body: + + :returns: The created BulkEligibilityInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BulkEligibilityInstance(self._version, payload) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> BulkEligibilityInstance: + """ + Asynchronously create the BulkEligibilityInstance + + :param body: + + :returns: The created BulkEligibilityInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BulkEligibilityInstance(self._version, payload) + + def get(self, request_id: str) -> BulkEligibilityContext: + """ + Constructs a BulkEligibilityContext + + :param request_id: The SID of the bulk eligibility check that you want to know about. + """ + return BulkEligibilityContext(self._version, request_id=request_id) + + def __call__(self, request_id: str) -> BulkEligibilityContext: + """ + Constructs a BulkEligibilityContext + + :param request_id: The SID of the bulk eligibility check that you want to know about. + """ + return BulkEligibilityContext(self._version, request_id=request_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V1.BulkEligibilityList>" diff --git a/twilio/rest/numbers/v1/eligibility.py b/twilio/rest/numbers/v1/eligibility.py new file mode 100644 index 0000000000..8c5af0ac64 --- /dev/null +++ b/twilio/rest/numbers/v1/eligibility.py @@ -0,0 +1,108 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class EligibilityInstance(InstanceResource): + """ + :ivar results: The result set that contains the eligibility check response for the requested number, each result has at least the following attributes: phone_number: The requested phone number ,hosting_account_sid: The account sid where the phone number will be hosted, date_last_checked: Datetime (ISO 8601) when the PN was last checked for eligibility, country: Phone number’s country, eligibility_status: Indicates the eligibility status of the PN (Eligible/Ineligible), eligibility_sub_status: Indicates the sub status of the eligibility , ineligibility_reason: Reason for number's ineligibility (if applicable), next_step: Suggested next step in the hosting process based on the eligibility status. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.results: Optional[List[Dict[str, object]]] = payload.get("results") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Numbers.V1.EligibilityInstance>" + + +class EligibilityList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the EligibilityList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/HostedNumber/Eligibility" + + def create(self, body: Union[object, object] = values.unset) -> EligibilityInstance: + """ + Create the EligibilityInstance + + :param body: + + :returns: The created EligibilityInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EligibilityInstance(self._version, payload) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> EligibilityInstance: + """ + Asynchronously create the EligibilityInstance + + :param body: + + :returns: The created EligibilityInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EligibilityInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V1.EligibilityList>" diff --git a/twilio/rest/numbers/v1/porting_port_in.py b/twilio/rest/numbers/v1/porting_port_in.py new file mode 100644 index 0000000000..3df2c15462 --- /dev/null +++ b/twilio/rest/numbers/v1/porting_port_in.py @@ -0,0 +1,325 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date, datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PortingPortInInstance(InstanceResource): + """ + :ivar port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. + :ivar url: The URL of this Port In request + :ivar account_sid: Account Sid or subaccount where the phone number(s) will be Ported + :ivar notification_emails: Additional emails to send a copy of the signed LOA to. + :ivar target_port_in_date: Target date to port the number. We cannot guarantee that this date will be honored by the other carriers, please work with Ops to get a confirmation of the firm order commitment (FOC) date. Expected format is ISO Local Date, example: ‘2011-12-03`. This date must be at least 7 days in the future for US ports and 10 days in the future for Japanese ports. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar target_port_in_time_range_start: The earliest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00'. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar target_port_in_time_range_end: The latest time that the port should occur on the target port in date. Expected format is ISO Offset Time, example: ‘10:15:00-08:00'. We can't guarantee the exact date and time, as this depends on the losing carrier + :ivar port_in_request_status: The status of the port in request. The possible values are: In progress, Completed, Expired, In review, Waiting for Signature, Action Required, and Canceled. + :ivar losing_carrier_information: Details regarding the customer’s information with the losing carrier. These values will be used to generate the letter of authorization and should match the losing carrier’s data as closely as possible to ensure the port is accepted. + :ivar phone_numbers: + :ivar documents: List of document SIDs for all phone numbers included in the port in request. At least one document SID referring to a document of the type Utility Bill is required. + :ivar date_created: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + port_in_request_sid: Optional[str] = None, + ): + super().__init__(version) + + self.port_in_request_sid: Optional[str] = payload.get("port_in_request_sid") + self.url: Optional[str] = payload.get("url") + self.account_sid: Optional[str] = payload.get("account_sid") + self.notification_emails: Optional[List[str]] = payload.get( + "notification_emails" + ) + self.target_port_in_date: Optional[date] = deserialize.iso8601_date( + payload.get("target_port_in_date") + ) + self.target_port_in_time_range_start: Optional[str] = payload.get( + "target_port_in_time_range_start" + ) + self.target_port_in_time_range_end: Optional[str] = payload.get( + "target_port_in_time_range_end" + ) + self.port_in_request_status: Optional[str] = payload.get( + "port_in_request_status" + ) + self.losing_carrier_information: Optional[Dict[str, object]] = payload.get( + "losing_carrier_information" + ) + self.phone_numbers: Optional[List[Dict[str, object]]] = payload.get( + "phone_numbers" + ) + self.documents: Optional[List[str]] = payload.get("documents") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + + self._solution = { + "port_in_request_sid": port_in_request_sid or self.port_in_request_sid, + } + self._context: Optional[PortingPortInContext] = None + + @property + def _proxy(self) -> "PortingPortInContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PortingPortInContext for this PortingPortInInstance + """ + if self._context is None: + self._context = PortingPortInContext( + self._version, + port_in_request_sid=self._solution["port_in_request_sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the PortingPortInInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PortingPortInInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "PortingPortInInstance": + """ + Fetch the PortingPortInInstance + + + :returns: The fetched PortingPortInInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PortingPortInInstance": + """ + Asynchronous coroutine to fetch the PortingPortInInstance + + + :returns: The fetched PortingPortInInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V1.PortingPortInInstance {}>".format(context) + + +class PortingPortInContext(InstanceContext): + + def __init__(self, version: Version, port_in_request_sid: str): + """ + Initialize the PortingPortInContext + + :param version: Version that contains the resource + :param port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "port_in_request_sid": port_in_request_sid, + } + self._uri = "/Porting/PortIn/{port_in_request_sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the PortingPortInInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PortingPortInInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> PortingPortInInstance: + """ + Fetch the PortingPortInInstance + + + :returns: The fetched PortingPortInInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PortingPortInInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], + ) + + async def fetch_async(self) -> PortingPortInInstance: + """ + Asynchronous coroutine to fetch the PortingPortInInstance + + + :returns: The fetched PortingPortInInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PortingPortInInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V1.PortingPortInContext {}>".format(context) + + +class PortingPortInList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PortingPortInList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Porting/PortIn" + + def create( + self, body: Union[object, object] = values.unset + ) -> PortingPortInInstance: + """ + Create the PortingPortInInstance + + :param body: + + :returns: The created PortingPortInInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PortingPortInInstance(self._version, payload) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> PortingPortInInstance: + """ + Asynchronously create the PortingPortInInstance + + :param body: + + :returns: The created PortingPortInInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PortingPortInInstance(self._version, payload) + + def get(self, port_in_request_sid: str) -> PortingPortInContext: + """ + Constructs a PortingPortInContext + + :param port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. + """ + return PortingPortInContext( + self._version, port_in_request_sid=port_in_request_sid + ) + + def __call__(self, port_in_request_sid: str) -> PortingPortInContext: + """ + Constructs a PortingPortInContext + + :param port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. + """ + return PortingPortInContext( + self._version, port_in_request_sid=port_in_request_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V1.PortingPortInList>" diff --git a/twilio/rest/numbers/v1/porting_port_in_phone_number.py b/twilio/rest/numbers/v1/porting_port_in_phone_number.py new file mode 100644 index 0000000000..cc8120f78f --- /dev/null +++ b/twilio/rest/numbers/v1/porting_port_in_phone_number.py @@ -0,0 +1,310 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PortingPortInPhoneNumberInstance(InstanceResource): + """ + :ivar port_in_request_sid: The unique identifier for the port in request that this phone number is associated with. + :ivar phone_number_sid: The unique identifier for this phone number associated with this port in request. + :ivar url: URL reference for this resource. + :ivar account_sid: Account Sid or subaccount where the phone number(s) will be Ported. + :ivar phone_number_type: The number type of the phone number. This can be: toll-free, local, mobile or unknown. This field may be null if the number is not portable or if the portability for a number has not yet been evaluated. + :ivar date_created: The timestamp for when this port in phone number was created. + :ivar country: The ISO country code that this number is associated with. This field may be null if the number is not portable or if the portability for a number has not yet been evaluated. + :ivar missing_required_fields: Indicates if the phone number is missing required fields such as a PIN or account number. This field may be null if the number is not portable or if the portability for a number has not yet been evaluated. + :ivar last_updated: Timestamp indicating when the Port In Phone Number resource was last modified. + :ivar phone_number: Phone number to be ported. This will be in the E164 Format. + :ivar portable: If the number is portable by Twilio or not. This field may be null if the number portability has not yet been evaluated. If a number is not portable reference the `not_portability_reason_code` and `not_portability_reason` fields for more details + :ivar not_portability_reason: The not portability reason code description. This field may be null if the number is portable or if the portability for a number has not yet been evaluated. + :ivar not_portability_reason_code: The not portability reason code. This field may be null if the number is portable or if the portability for a number has not yet been evaluated. + :ivar port_in_phone_number_status: The status of the port in phone number. + :ivar port_out_pin: The pin required by the losing carrier to do the port out. + :ivar rejection_reason: The description of the rejection reason provided by the losing carrier. This field may be null if the number has not been rejected by the losing carrier. + :ivar rejection_reason_code: The code for the rejection reason provided by the losing carrier. This field may be null if the number has not been rejected by the losing carrier. + :ivar port_date: The timestamp the phone number will be ported. This will only be set once a port date has been confirmed. Not all carriers can guarantee a specific time on the port date. Twilio will try its best to get the port completed by this time on the port date. Please subscribe to webhooks for confirmation on when a port has actually been completed. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + port_in_request_sid: Optional[str] = None, + phone_number_sid: Optional[str] = None, + ): + super().__init__(version) + + self.port_in_request_sid: Optional[str] = payload.get("port_in_request_sid") + self.phone_number_sid: Optional[str] = payload.get("phone_number_sid") + self.url: Optional[str] = payload.get("url") + self.account_sid: Optional[str] = payload.get("account_sid") + self.phone_number_type: Optional[str] = payload.get("phone_number_type") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.country: Optional[str] = payload.get("country") + self.missing_required_fields: Optional[bool] = payload.get( + "missing_required_fields" + ) + self.last_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("last_updated") + ) + self.phone_number: Optional[str] = payload.get("phone_number") + self.portable: Optional[bool] = payload.get("portable") + self.not_portability_reason: Optional[str] = payload.get( + "not_portability_reason" + ) + self.not_portability_reason_code: Optional[int] = deserialize.integer( + payload.get("not_portability_reason_code") + ) + self.port_in_phone_number_status: Optional[str] = payload.get( + "port_in_phone_number_status" + ) + self.port_out_pin: Optional[int] = deserialize.integer( + payload.get("port_out_pin") + ) + self.rejection_reason: Optional[str] = payload.get("rejection_reason") + self.rejection_reason_code: Optional[int] = deserialize.integer( + payload.get("rejection_reason_code") + ) + self.port_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("port_date") + ) + + self._solution = { + "port_in_request_sid": port_in_request_sid or self.port_in_request_sid, + "phone_number_sid": phone_number_sid or self.phone_number_sid, + } + self._context: Optional[PortingPortInPhoneNumberContext] = None + + @property + def _proxy(self) -> "PortingPortInPhoneNumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PortingPortInPhoneNumberContext for this PortingPortInPhoneNumberInstance + """ + if self._context is None: + self._context = PortingPortInPhoneNumberContext( + self._version, + port_in_request_sid=self._solution["port_in_request_sid"], + phone_number_sid=self._solution["phone_number_sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the PortingPortInPhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PortingPortInPhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "PortingPortInPhoneNumberInstance": + """ + Fetch the PortingPortInPhoneNumberInstance + + + :returns: The fetched PortingPortInPhoneNumberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PortingPortInPhoneNumberInstance": + """ + Asynchronous coroutine to fetch the PortingPortInPhoneNumberInstance + + + :returns: The fetched PortingPortInPhoneNumberInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V1.PortingPortInPhoneNumberInstance {}>".format(context) + + +class PortingPortInPhoneNumberContext(InstanceContext): + + def __init__( + self, version: Version, port_in_request_sid: str, phone_number_sid: str + ): + """ + Initialize the PortingPortInPhoneNumberContext + + :param version: Version that contains the resource + :param port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. + :param phone_number_sid: The SID of the Phone number. This is a unique identifier of the phone number. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "port_in_request_sid": port_in_request_sid, + "phone_number_sid": phone_number_sid, + } + self._uri = "/Porting/PortIn/{port_in_request_sid}/PhoneNumber/{phone_number_sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the PortingPortInPhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PortingPortInPhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> PortingPortInPhoneNumberInstance: + """ + Fetch the PortingPortInPhoneNumberInstance + + + :returns: The fetched PortingPortInPhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PortingPortInPhoneNumberInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], + phone_number_sid=self._solution["phone_number_sid"], + ) + + async def fetch_async(self) -> PortingPortInPhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PortingPortInPhoneNumberInstance + + + :returns: The fetched PortingPortInPhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PortingPortInPhoneNumberInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], + phone_number_sid=self._solution["phone_number_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V1.PortingPortInPhoneNumberContext {}>".format(context) + + +class PortingPortInPhoneNumberList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PortingPortInPhoneNumberList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get( + self, port_in_request_sid: str, phone_number_sid: str + ) -> PortingPortInPhoneNumberContext: + """ + Constructs a PortingPortInPhoneNumberContext + + :param port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. + :param phone_number_sid: The SID of the Phone number. This is a unique identifier of the phone number. + """ + return PortingPortInPhoneNumberContext( + self._version, + port_in_request_sid=port_in_request_sid, + phone_number_sid=phone_number_sid, + ) + + def __call__( + self, port_in_request_sid: str, phone_number_sid: str + ) -> PortingPortInPhoneNumberContext: + """ + Constructs a PortingPortInPhoneNumberContext + + :param port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. + :param phone_number_sid: The SID of the Phone number. This is a unique identifier of the phone number. + """ + return PortingPortInPhoneNumberContext( + self._version, + port_in_request_sid=port_in_request_sid, + phone_number_sid=phone_number_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V1.PortingPortInPhoneNumberList>" diff --git a/twilio/rest/numbers/v1/porting_portability.py b/twilio/rest/numbers/v1/porting_portability.py new file mode 100644 index 0000000000..351cd541af --- /dev/null +++ b/twilio/rest/numbers/v1/porting_portability.py @@ -0,0 +1,265 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PortingPortabilityInstance(InstanceResource): + + class NumberType(object): + LOCAL = "LOCAL" + UNKNOWN = "UNKNOWN" + MOBILE = "MOBILE" + TOLL_FREE = "TOLL-FREE" + + """ + :ivar phone_number: The phone number which portability is to be checked. Phone numbers are in E.164 format (e.g. +16175551212). + :ivar account_sid: Account Sid that the phone number belongs to in Twilio. This is only returned for phone numbers that already exist in Twilio’s inventory and belong to your account or sub account. + :ivar portable: Boolean flag indicates if the phone number can be ported into Twilio through the Porting API or not. + :ivar pin_and_account_number_required: Indicates if the port in process will require a personal identification number (PIN) and an account number for this phone number. If this is true you will be required to submit both a PIN and account number from the losing carrier for this number when opening a port in request. These fields will be required in order to complete the port in process to Twilio. + :ivar not_portable_reason: Reason why the phone number cannot be ported into Twilio, `null` otherwise. + :ivar not_portable_reason_code: The Portability Reason Code for the phone number if it cannot be ported into Twilio, `null` otherwise. + :ivar number_type: + :ivar country: Country the phone number belongs to. + :ivar url: This is the url of the request that you're trying to reach out to locate the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + phone_number: Optional[str] = None, + ): + super().__init__(version) + + self.phone_number: Optional[str] = payload.get("phone_number") + self.account_sid: Optional[str] = payload.get("account_sid") + self.portable: Optional[bool] = payload.get("portable") + self.pin_and_account_number_required: Optional[bool] = payload.get( + "pin_and_account_number_required" + ) + self.not_portable_reason: Optional[str] = payload.get("not_portable_reason") + self.not_portable_reason_code: Optional[int] = deserialize.integer( + payload.get("not_portable_reason_code") + ) + self.number_type: Optional["PortingPortabilityInstance.NumberType"] = ( + payload.get("number_type") + ) + self.country: Optional[str] = payload.get("country") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "phone_number": phone_number or self.phone_number, + } + self._context: Optional[PortingPortabilityContext] = None + + @property + def _proxy(self) -> "PortingPortabilityContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PortingPortabilityContext for this PortingPortabilityInstance + """ + if self._context is None: + self._context = PortingPortabilityContext( + self._version, + phone_number=self._solution["phone_number"], + ) + return self._context + + def fetch( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> "PortingPortabilityInstance": + """ + Fetch the PortingPortabilityInstance + + :param target_account_sid: Account Sid to which the number will be ported. This can be used to determine if a sub account already has the number in its inventory or a different sub account. If this is not provided, the authenticated account will be assumed to be the target account. + :param address_sid: Address Sid of customer to which the number will be ported. + + :returns: The fetched PortingPortabilityInstance + """ + return self._proxy.fetch( + target_account_sid=target_account_sid, + address_sid=address_sid, + ) + + async def fetch_async( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> "PortingPortabilityInstance": + """ + Asynchronous coroutine to fetch the PortingPortabilityInstance + + :param target_account_sid: Account Sid to which the number will be ported. This can be used to determine if a sub account already has the number in its inventory or a different sub account. If this is not provided, the authenticated account will be assumed to be the target account. + :param address_sid: Address Sid of customer to which the number will be ported. + + :returns: The fetched PortingPortabilityInstance + """ + return await self._proxy.fetch_async( + target_account_sid=target_account_sid, + address_sid=address_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V1.PortingPortabilityInstance {}>".format(context) + + +class PortingPortabilityContext(InstanceContext): + + def __init__(self, version: Version, phone_number: str): + """ + Initialize the PortingPortabilityContext + + :param version: Version that contains the resource + :param phone_number: Phone number to check portability in e164 format. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "phone_number": phone_number, + } + self._uri = "/Porting/Portability/PhoneNumber/{phone_number}".format( + **self._solution + ) + + def fetch( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> PortingPortabilityInstance: + """ + Fetch the PortingPortabilityInstance + + :param target_account_sid: Account Sid to which the number will be ported. This can be used to determine if a sub account already has the number in its inventory or a different sub account. If this is not provided, the authenticated account will be assumed to be the target account. + :param address_sid: Address Sid of customer to which the number will be ported. + + :returns: The fetched PortingPortabilityInstance + """ + + data = values.of( + { + "TargetAccountSid": target_account_sid, + "AddressSid": address_sid, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PortingPortabilityInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + async def fetch_async( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> PortingPortabilityInstance: + """ + Asynchronous coroutine to fetch the PortingPortabilityInstance + + :param target_account_sid: Account Sid to which the number will be ported. This can be used to determine if a sub account already has the number in its inventory or a different sub account. If this is not provided, the authenticated account will be assumed to be the target account. + :param address_sid: Address Sid of customer to which the number will be ported. + + :returns: The fetched PortingPortabilityInstance + """ + + data = values.of( + { + "TargetAccountSid": target_account_sid, + "AddressSid": address_sid, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return PortingPortabilityInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V1.PortingPortabilityContext {}>".format(context) + + +class PortingPortabilityList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PortingPortabilityList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, phone_number: str) -> PortingPortabilityContext: + """ + Constructs a PortingPortabilityContext + + :param phone_number: Phone number to check portability in e164 format. + """ + return PortingPortabilityContext(self._version, phone_number=phone_number) + + def __call__(self, phone_number: str) -> PortingPortabilityContext: + """ + Constructs a PortingPortabilityContext + + :param phone_number: Phone number to check portability in e164 format. + """ + return PortingPortabilityContext(self._version, phone_number=phone_number) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V1.PortingPortabilityList>" diff --git a/twilio/rest/numbers/v1/porting_webhook_configuration.py b/twilio/rest/numbers/v1/porting_webhook_configuration.py new file mode 100644 index 0000000000..cfd9e1d0a8 --- /dev/null +++ b/twilio/rest/numbers/v1/porting_webhook_configuration.py @@ -0,0 +1,116 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PortingWebhookConfigurationInstance(InstanceResource): + """ + :ivar url: The URL of the webhook configuration request + :ivar port_in_target_url: The complete webhook url that will be called when a notification event for port in request or port in phone number happens + :ivar port_out_target_url: The complete webhook url that will be called when a notification event for a port out phone number happens. + :ivar notifications_of: A list to filter what notification events to receive for this account and its sub accounts. If it is an empty list, then it means that there are no filters for the notifications events to send in each webhook and all events will get sent. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.url: Optional[str] = payload.get("url") + self.port_in_target_url: Optional[str] = payload.get("port_in_target_url") + self.port_out_target_url: Optional[str] = payload.get("port_out_target_url") + self.notifications_of: Optional[List[str]] = payload.get("notifications_of") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Numbers.V1.PortingWebhookConfigurationInstance>" + + +class PortingWebhookConfigurationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PortingWebhookConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Porting/Configuration/Webhook" + + def create( + self, body: Union[object, object] = values.unset + ) -> PortingWebhookConfigurationInstance: + """ + Create the PortingWebhookConfigurationInstance + + :param body: + + :returns: The created PortingWebhookConfigurationInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PortingWebhookConfigurationInstance(self._version, payload) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> PortingWebhookConfigurationInstance: + """ + Asynchronously create the PortingWebhookConfigurationInstance + + :param body: + + :returns: The created PortingWebhookConfigurationInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PortingWebhookConfigurationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V1.PortingWebhookConfigurationList>" diff --git a/twilio/rest/numbers/v1/porting_webhook_configuration_delete.py b/twilio/rest/numbers/v1/porting_webhook_configuration_delete.py new file mode 100644 index 0000000000..11572f1846 --- /dev/null +++ b/twilio/rest/numbers/v1/porting_webhook_configuration_delete.py @@ -0,0 +1,124 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from twilio.base import values +from twilio.base.instance_context import InstanceContext + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PortingWebhookConfigurationDeleteContext(InstanceContext): + + def __init__( + self, + version: Version, + webhook_type: "PortingWebhookConfigurationDeleteInstance.WebhookType", + ): + """ + Initialize the PortingWebhookConfigurationDeleteContext + + :param version: Version that contains the resource + :param webhook_type: The webhook type for the configuration to be delete. `PORT_IN`, `PORT_OUT` + """ + super().__init__(version) + + # Path Solution + self._solution = { + "webhook_type": webhook_type, + } + self._uri = "/Porting/Configuration/Webhook/{webhook_type}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the PortingWebhookConfigurationDeleteInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PortingWebhookConfigurationDeleteInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V1.PortingWebhookConfigurationDeleteContext {}>".format( + context + ) + + +class PortingWebhookConfigurationDeleteList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PortingWebhookConfigurationDeleteList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get( + self, webhook_type: "PortingWebhookConfigurationDeleteInstance.WebhookType" + ) -> PortingWebhookConfigurationDeleteContext: + """ + Constructs a PortingWebhookConfigurationDeleteContext + + :param webhook_type: The webhook type for the configuration to be delete. `PORT_IN`, `PORT_OUT` + """ + return PortingWebhookConfigurationDeleteContext( + self._version, webhook_type=webhook_type + ) + + def __call__( + self, webhook_type: "PortingWebhookConfigurationDeleteInstance.WebhookType" + ) -> PortingWebhookConfigurationDeleteContext: + """ + Constructs a PortingWebhookConfigurationDeleteContext + + :param webhook_type: The webhook type for the configuration to be delete. `PORT_IN`, `PORT_OUT` + """ + return PortingWebhookConfigurationDeleteContext( + self._version, webhook_type=webhook_type + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V1.PortingWebhookConfigurationDeleteList>" diff --git a/twilio/rest/numbers/v1/porting_webhook_configuration_fetch.py b/twilio/rest/numbers/v1/porting_webhook_configuration_fetch.py new file mode 100644 index 0000000000..5d381768c7 --- /dev/null +++ b/twilio/rest/numbers/v1/porting_webhook_configuration_fetch.py @@ -0,0 +1,109 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PortingWebhookConfigurationFetchInstance(InstanceResource): + """ + :ivar url: The URL of the webhook configuration request + :ivar port_in_target_url: The complete webhook url that will be called when a notification event for port in request or port in phone number happens + :ivar port_out_target_url: The complete webhook url that will be called when a notification event for a port out phone number happens. + :ivar notifications_of: A list to filter what notification events to receive for this account and its sub accounts. If it is an empty list, then it means that there are no filters for the notifications events to send in each webhook and all events will get sent. + :ivar port_in_target_date_created: Creation date for the port in webhook configuration + :ivar port_out_target_date_created: Creation date for the port out webhook configuration + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.url: Optional[str] = payload.get("url") + self.port_in_target_url: Optional[str] = payload.get("port_in_target_url") + self.port_out_target_url: Optional[str] = payload.get("port_out_target_url") + self.notifications_of: Optional[List[str]] = payload.get("notifications_of") + self.port_in_target_date_created: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("port_in_target_date_created")) + ) + self.port_out_target_date_created: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("port_out_target_date_created")) + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Numbers.V1.PortingWebhookConfigurationFetchInstance>" + + +class PortingWebhookConfigurationFetchList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PortingWebhookConfigurationFetchList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Porting/Configuration/Webhook" + + def fetch(self) -> PortingWebhookConfigurationFetchInstance: + """ + Asynchronously fetch the PortingWebhookConfigurationFetchInstance + + + :returns: The fetched PortingWebhookConfigurationFetchInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PortingWebhookConfigurationFetchInstance(self._version, payload) + + async def fetch_async(self) -> PortingWebhookConfigurationFetchInstance: + """ + Asynchronously fetch the PortingWebhookConfigurationFetchInstance + + + :returns: The fetched PortingWebhookConfigurationFetchInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PortingWebhookConfigurationFetchInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V1.PortingWebhookConfigurationFetchList>" diff --git a/twilio/rest/numbers/v1/signing_request_configuration.py b/twilio/rest/numbers/v1/signing_request_configuration.py new file mode 100644 index 0000000000..fcfcd7777b --- /dev/null +++ b/twilio/rest/numbers/v1/signing_request_configuration.py @@ -0,0 +1,375 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SigningRequestConfigurationInstance(InstanceResource): + """ + :ivar logo_sid: The SID of the document that includes the logo that will appear in the LOA. To upload documents follow the following guide: https://www.twilio.com/docs/phone-numbers/regulatory/getting-started/create-new-bundle-public-rest-apis#supporting-document-create + :ivar friendly_name: This is the string that you assigned as a friendly name for describing the creation of the configuration. + :ivar product: The product or service for which is requesting the signature. + :ivar country: The country ISO code to apply the configuration. + :ivar email_subject: Subject of the email that the end client will receive ex: “Twilio Hosting Request”, maximum length of 255 characters. + :ivar email_message: Content of the email that the end client will receive ex: “This is a Hosting request from Twilio, please check the document and sign it”, maximum length of 5,000 characters. + :ivar url_redirection: Url the end client will be redirected after signing a document. + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.logo_sid: Optional[str] = payload.get("logo_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.product: Optional[str] = payload.get("product") + self.country: Optional[str] = payload.get("country") + self.email_subject: Optional[str] = payload.get("email_subject") + self.email_message: Optional[str] = payload.get("email_message") + self.url_redirection: Optional[str] = payload.get("url_redirection") + self.url: Optional[str] = payload.get("url") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Numbers.V1.SigningRequestConfigurationInstance>" + + +class SigningRequestConfigurationPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> SigningRequestConfigurationInstance: + """ + Build an instance of SigningRequestConfigurationInstance + + :param payload: Payload response from the API + """ + return SigningRequestConfigurationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V1.SigningRequestConfigurationPage>" + + +class SigningRequestConfigurationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SigningRequestConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SigningRequest/Configuration" + + def create( + self, body: Union[object, object] = values.unset + ) -> SigningRequestConfigurationInstance: + """ + Create the SigningRequestConfigurationInstance + + :param body: + + :returns: The created SigningRequestConfigurationInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SigningRequestConfigurationInstance(self._version, payload) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> SigningRequestConfigurationInstance: + """ + Asynchronously create the SigningRequestConfigurationInstance + + :param body: + + :returns: The created SigningRequestConfigurationInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SigningRequestConfigurationInstance(self._version, payload) + + def stream( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SigningRequestConfigurationInstance]: + """ + Streams SigningRequestConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str country: The country ISO code to apply this configuration, this is an optional field, Example: US, MX + :param str product: The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + country=country, product=product, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SigningRequestConfigurationInstance]: + """ + Asynchronously streams SigningRequestConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str country: The country ISO code to apply this configuration, this is an optional field, Example: US, MX + :param str product: The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + country=country, product=product, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SigningRequestConfigurationInstance]: + """ + Lists SigningRequestConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str country: The country ISO code to apply this configuration, this is an optional field, Example: US, MX + :param str product: The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + country=country, + product=product, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SigningRequestConfigurationInstance]: + """ + Asynchronously lists SigningRequestConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str country: The country ISO code to apply this configuration, this is an optional field, Example: US, MX + :param str product: The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + country=country, + product=product, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SigningRequestConfigurationPage: + """ + Retrieve a single page of SigningRequestConfigurationInstance records from the API. + Request is executed immediately + + :param country: The country ISO code to apply this configuration, this is an optional field, Example: US, MX + :param product: The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SigningRequestConfigurationInstance + """ + data = values.of( + { + "Country": country, + "Product": product, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SigningRequestConfigurationPage(self._version, response) + + async def page_async( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SigningRequestConfigurationPage: + """ + Asynchronously retrieve a single page of SigningRequestConfigurationInstance records from the API. + Request is executed immediately + + :param country: The country ISO code to apply this configuration, this is an optional field, Example: US, MX + :param product: The product or service for which is requesting the signature, this is an optional field, Example: Porting, Hosting + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SigningRequestConfigurationInstance + """ + data = values.of( + { + "Country": country, + "Product": product, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SigningRequestConfigurationPage(self._version, response) + + def get_page(self, target_url: str) -> SigningRequestConfigurationPage: + """ + Retrieve a specific page of SigningRequestConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SigningRequestConfigurationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SigningRequestConfigurationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SigningRequestConfigurationPage: + """ + Asynchronously retrieve a specific page of SigningRequestConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SigningRequestConfigurationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SigningRequestConfigurationPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V1.SigningRequestConfigurationList>" diff --git a/twilio/rest/numbers/v2/__init__.py b/twilio/rest/numbers/v2/__init__.py new file mode 100644 index 0000000000..04b303486e --- /dev/null +++ b/twilio/rest/numbers/v2/__init__.py @@ -0,0 +1,75 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.numbers.v2.authorization_document import AuthorizationDocumentList +from twilio.rest.numbers.v2.bulk_hosted_number_order import BulkHostedNumberOrderList +from twilio.rest.numbers.v2.bundle_clone import BundleCloneList +from twilio.rest.numbers.v2.hosted_number_order import HostedNumberOrderList +from twilio.rest.numbers.v2.regulatory_compliance import RegulatoryComplianceList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Numbers + + :param domain: The Twilio.numbers domain + """ + super().__init__(domain, "v2") + self._authorization_documents: Optional[AuthorizationDocumentList] = None + self._bulk_hosted_number_orders: Optional[BulkHostedNumberOrderList] = None + self._bundle_clone: Optional[BundleCloneList] = None + self._hosted_number_orders: Optional[HostedNumberOrderList] = None + self._regulatory_compliance: Optional[RegulatoryComplianceList] = None + + @property + def authorization_documents(self) -> AuthorizationDocumentList: + if self._authorization_documents is None: + self._authorization_documents = AuthorizationDocumentList(self) + return self._authorization_documents + + @property + def bulk_hosted_number_orders(self) -> BulkHostedNumberOrderList: + if self._bulk_hosted_number_orders is None: + self._bulk_hosted_number_orders = BulkHostedNumberOrderList(self) + return self._bulk_hosted_number_orders + + @property + def bundle_clone(self) -> BundleCloneList: + if self._bundle_clone is None: + self._bundle_clone = BundleCloneList(self) + return self._bundle_clone + + @property + def hosted_number_orders(self) -> HostedNumberOrderList: + if self._hosted_number_orders is None: + self._hosted_number_orders = HostedNumberOrderList(self) + return self._hosted_number_orders + + @property + def regulatory_compliance(self) -> RegulatoryComplianceList: + if self._regulatory_compliance is None: + self._regulatory_compliance = RegulatoryComplianceList(self) + return self._regulatory_compliance + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2>" diff --git a/twilio/rest/numbers/v2/authorization_document/__init__.py b/twilio/rest/numbers/v2/authorization_document/__init__.py new file mode 100644 index 0000000000..033a32cfd7 --- /dev/null +++ b/twilio/rest/numbers/v2/authorization_document/__init__.py @@ -0,0 +1,629 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.numbers.v2.authorization_document.dependent_hosted_number_order import ( + DependentHostedNumberOrderList, +) + + +class AuthorizationDocumentInstance(InstanceResource): + + class Status(object): + OPENED = "opened" + SIGNING = "signing" + SIGNED = "signed" + CANCELED = "canceled" + FAILED = "failed" + + """ + :ivar sid: A 34 character string that uniquely identifies this AuthorizationDocument. + :ivar address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :ivar status: + :ivar email: Email that this AuthorizationDocument will be sent to for signing. + :ivar cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + :ivar date_created: The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.address_sid: Optional[str] = payload.get("address_sid") + self.status: Optional["AuthorizationDocumentInstance.Status"] = payload.get( + "status" + ) + self.email: Optional[str] = payload.get("email") + self.cc_emails: Optional[List[str]] = payload.get("cc_emails") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AuthorizationDocumentContext] = None + + @property + def _proxy(self) -> "AuthorizationDocumentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AuthorizationDocumentContext for this AuthorizationDocumentInstance + """ + if self._context is None: + self._context = AuthorizationDocumentContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AuthorizationDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AuthorizationDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AuthorizationDocumentInstance": + """ + Fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AuthorizationDocumentInstance": + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + return await self._proxy.fetch_async() + + @property + def dependent_hosted_number_orders(self) -> DependentHostedNumberOrderList: + """ + Access the dependent_hosted_number_orders + """ + return self._proxy.dependent_hosted_number_orders + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.AuthorizationDocumentInstance {}>".format(context) + + +class AuthorizationDocumentContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the AuthorizationDocumentContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/HostedNumber/AuthorizationDocuments/{sid}".format( + **self._solution + ) + + self._dependent_hosted_number_orders: Optional[ + DependentHostedNumberOrderList + ] = None + + def delete(self) -> bool: + """ + Deletes the AuthorizationDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AuthorizationDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AuthorizationDocumentInstance: + """ + Fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AuthorizationDocumentInstance: + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + @property + def dependent_hosted_number_orders(self) -> DependentHostedNumberOrderList: + """ + Access the dependent_hosted_number_orders + """ + if self._dependent_hosted_number_orders is None: + self._dependent_hosted_number_orders = DependentHostedNumberOrderList( + self._version, + self._solution["sid"], + ) + return self._dependent_hosted_number_orders + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.AuthorizationDocumentContext {}>".format(context) + + +class AuthorizationDocumentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AuthorizationDocumentInstance: + """ + Build an instance of AuthorizationDocumentInstance + + :param payload: Payload response from the API + """ + return AuthorizationDocumentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.AuthorizationDocumentPage>" + + +class AuthorizationDocumentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AuthorizationDocumentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/HostedNumber/AuthorizationDocuments" + + def create( + self, + address_sid: str, + email: str, + contact_phone_number: str, + hosted_number_order_sids: List[str], + contact_title: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + ) -> AuthorizationDocumentInstance: + """ + Create the AuthorizationDocumentInstance + + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + + :returns: The created AuthorizationDocumentInstance + """ + + data = values.of( + { + "AddressSid": address_sid, + "Email": email, + "ContactPhoneNumber": contact_phone_number, + "HostedNumberOrderSids": serialize.map( + hosted_number_order_sids, lambda e: e + ), + "ContactTitle": contact_title, + "CcEmails": serialize.map(cc_emails, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthorizationDocumentInstance(self._version, payload) + + async def create_async( + self, + address_sid: str, + email: str, + contact_phone_number: str, + hosted_number_order_sids: List[str], + contact_title: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + ) -> AuthorizationDocumentInstance: + """ + Asynchronously create the AuthorizationDocumentInstance + + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + + :returns: The created AuthorizationDocumentInstance + """ + + data = values.of( + { + "AddressSid": address_sid, + "Email": email, + "ContactPhoneNumber": contact_phone_number, + "HostedNumberOrderSids": serialize.map( + hosted_number_order_sids, lambda e: e + ), + "ContactTitle": contact_title, + "CcEmails": serialize.map(cc_emails, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthorizationDocumentInstance(self._version, payload) + + def stream( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AuthorizationDocumentInstance]: + """ + Streams AuthorizationDocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(email=email, status=status, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AuthorizationDocumentInstance]: + """ + Asynchronously streams AuthorizationDocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + email=email, status=status, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthorizationDocumentInstance]: + """ + Lists AuthorizationDocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + email=email, + status=status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthorizationDocumentInstance]: + """ + Asynchronously lists AuthorizationDocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + email=email, + status=status, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthorizationDocumentPage: + """ + Retrieve a single page of AuthorizationDocumentInstance records from the API. + Request is executed immediately + + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthorizationDocumentInstance + """ + data = values.of( + { + "Email": email, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthorizationDocumentPage(self._version, response) + + async def page_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthorizationDocumentPage: + """ + Asynchronously retrieve a single page of AuthorizationDocumentInstance records from the API. + Request is executed immediately + + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthorizationDocumentInstance + """ + data = values.of( + { + "Email": email, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthorizationDocumentPage(self._version, response) + + def get_page(self, target_url: str) -> AuthorizationDocumentPage: + """ + Retrieve a specific page of AuthorizationDocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthorizationDocumentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AuthorizationDocumentPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AuthorizationDocumentPage: + """ + Asynchronously retrieve a specific page of AuthorizationDocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthorizationDocumentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AuthorizationDocumentPage(self._version, response) + + def get(self, sid: str) -> AuthorizationDocumentContext: + """ + Constructs a AuthorizationDocumentContext + + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. + """ + return AuthorizationDocumentContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AuthorizationDocumentContext: + """ + Constructs a AuthorizationDocumentContext + + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. + """ + return AuthorizationDocumentContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.AuthorizationDocumentList>" diff --git a/twilio/rest/numbers/v2/authorization_document/dependent_hosted_number_order.py b/twilio/rest/numbers/v2/authorization_document/dependent_hosted_number_order.py new file mode 100644 index 0000000000..36f961f5ef --- /dev/null +++ b/twilio/rest/numbers/v2/authorization_document/dependent_hosted_number_order.py @@ -0,0 +1,439 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DependentHostedNumberOrderInstance(InstanceResource): + + class Status(object): + RECEIVED = "received" + VERIFIED = "verified" + PENDING_LOA = "pending-loa" + CARRIER_PROCESSING = "carrier-processing" + COMPLETED = "completed" + FAILED = "failed" + ACTION_REQUIRED = "action-required" + + """ + :ivar sid: A 34 character string that uniquely identifies this Authorization Document + :ivar bulk_hosting_request_sid: A 34 character string that uniquely identifies the bulk hosting request associated with this HostedNumberOrder. + :ivar next_step: The next step you need to take to complete the hosted number order and request it successfully. + :ivar account_sid: The unique SID identifier of the Account. + :ivar incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :ivar address_sid: A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :ivar signing_document_sid: A 34 character string that uniquely identifies the LOA document associated with this HostedNumberOrder. + :ivar phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :ivar capabilities: + :ivar friendly_name: A human readable description of this resource, up to 128 characters. + :ivar status: + :ivar failure_reason: A message that explains why a hosted_number_order went to status \"action-required\" + :ivar date_created: The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar email: Email of the owner of this phone number that is being hosted. + :ivar cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :ivar contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :ivar contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], signing_document_sid: str + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.bulk_hosting_request_sid: Optional[str] = payload.get( + "bulk_hosting_request_sid" + ) + self.next_step: Optional[str] = payload.get("next_step") + self.account_sid: Optional[str] = payload.get("account_sid") + self.incoming_phone_number_sid: Optional[str] = payload.get( + "incoming_phone_number_sid" + ) + self.address_sid: Optional[str] = payload.get("address_sid") + self.signing_document_sid: Optional[str] = payload.get("signing_document_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.capabilities: Optional[str] = payload.get("capabilities") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["DependentHostedNumberOrderInstance.Status"] = ( + payload.get("status") + ) + self.failure_reason: Optional[str] = payload.get("failure_reason") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.email: Optional[str] = payload.get("email") + self.cc_emails: Optional[List[str]] = payload.get("cc_emails") + self.contact_title: Optional[str] = payload.get("contact_title") + self.contact_phone_number: Optional[str] = payload.get("contact_phone_number") + + self._solution = { + "signing_document_sid": signing_document_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.DependentHostedNumberOrderInstance {}>".format( + context + ) + + +class DependentHostedNumberOrderPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> DependentHostedNumberOrderInstance: + """ + Build an instance of DependentHostedNumberOrderInstance + + :param payload: Payload response from the API + """ + return DependentHostedNumberOrderInstance( + self._version, + payload, + signing_document_sid=self._solution["signing_document_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.DependentHostedNumberOrderPage>" + + +class DependentHostedNumberOrderList(ListResource): + + def __init__(self, version: Version, signing_document_sid: str): + """ + Initialize the DependentHostedNumberOrderList + + :param version: Version that contains the resource + :param signing_document_sid: A 34 character string that uniquely identifies the LOA document associated with this HostedNumberOrder. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "signing_document_sid": signing_document_sid, + } + self._uri = "/HostedNumber/AuthorizationDocuments/{signing_document_sid}/DependentHostedNumberOrders".format( + **self._solution + ) + + def stream( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DependentHostedNumberOrderInstance]: + """ + Streams DependentHostedNumberOrderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DependentHostedNumberOrderInstance]: + """ + Asynchronously streams DependentHostedNumberOrderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DependentHostedNumberOrderInstance]: + """ + Lists DependentHostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DependentHostedNumberOrderInstance]: + """ + Asynchronously lists DependentHostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DependentHostedNumberOrderPage: + """ + Retrieve a single page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately + + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 128 characters. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DependentHostedNumberOrderInstance + """ + data = values.of( + { + "Status": status, + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentHostedNumberOrderPage(self._version, response, self._solution) + + async def page_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DependentHostedNumberOrderPage: + """ + Asynchronously retrieve a single page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately + + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 128 characters. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DependentHostedNumberOrderInstance + """ + data = values.of( + { + "Status": status, + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentHostedNumberOrderPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DependentHostedNumberOrderPage: + """ + Retrieve a specific page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DependentHostedNumberOrderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DependentHostedNumberOrderPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DependentHostedNumberOrderPage: + """ + Asynchronously retrieve a specific page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DependentHostedNumberOrderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DependentHostedNumberOrderPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.DependentHostedNumberOrderList>" diff --git a/twilio/rest/numbers/v2/bulk_hosted_number_order.py b/twilio/rest/numbers/v2/bulk_hosted_number_order.py new file mode 100644 index 0000000000..7259c801d2 --- /dev/null +++ b/twilio/rest/numbers/v2/bulk_hosted_number_order.py @@ -0,0 +1,305 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class BulkHostedNumberOrderInstance(InstanceResource): + + class RequestStatus(object): + QUEUED = "QUEUED" + IN_PROGRESS = "IN_PROGRESS" + PROCESSED = "PROCESSED" + + """ + :ivar bulk_hosting_sid: A 34 character string that uniquely identifies this BulkHostedNumberOrder. + :ivar request_status: + :ivar friendly_name: A 128 character string that is a human-readable text that describes this resource. + :ivar notification_email: Email address used for send notifications about this Bulk hosted number request. + :ivar date_created: The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_completed: The date that this resource was completed, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The URL of this BulkHostedNumberOrder resource. + :ivar total_count: The total count of phone numbers in this Bulk hosting request. + :ivar results: Contains a list of all the individual hosting orders and their information, for this Bulk request. Each result object is grouped by its order status. To see a complete list of order status, please check 'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values'. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + bulk_hosting_sid: Optional[str] = None, + ): + super().__init__(version) + + self.bulk_hosting_sid: Optional[str] = payload.get("bulk_hosting_sid") + self.request_status: Optional["BulkHostedNumberOrderInstance.RequestStatus"] = ( + payload.get("request_status") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.notification_email: Optional[str] = payload.get("notification_email") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_completed: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_completed") + ) + self.url: Optional[str] = payload.get("url") + self.total_count: Optional[int] = deserialize.integer( + payload.get("total_count") + ) + self.results: Optional[List[Dict[str, object]]] = payload.get("results") + + self._solution = { + "bulk_hosting_sid": bulk_hosting_sid or self.bulk_hosting_sid, + } + self._context: Optional[BulkHostedNumberOrderContext] = None + + @property + def _proxy(self) -> "BulkHostedNumberOrderContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BulkHostedNumberOrderContext for this BulkHostedNumberOrderInstance + """ + if self._context is None: + self._context = BulkHostedNumberOrderContext( + self._version, + bulk_hosting_sid=self._solution["bulk_hosting_sid"], + ) + return self._context + + def fetch( + self, order_status: Union[str, object] = values.unset + ) -> "BulkHostedNumberOrderInstance": + """ + Fetch the BulkHostedNumberOrderInstance + + :param order_status: Order status can be used for filtering on Hosted Number Order status values. To see a complete list of order statuses, please check 'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values'. + + :returns: The fetched BulkHostedNumberOrderInstance + """ + return self._proxy.fetch( + order_status=order_status, + ) + + async def fetch_async( + self, order_status: Union[str, object] = values.unset + ) -> "BulkHostedNumberOrderInstance": + """ + Asynchronous coroutine to fetch the BulkHostedNumberOrderInstance + + :param order_status: Order status can be used for filtering on Hosted Number Order status values. To see a complete list of order statuses, please check 'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values'. + + :returns: The fetched BulkHostedNumberOrderInstance + """ + return await self._proxy.fetch_async( + order_status=order_status, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.BulkHostedNumberOrderInstance {}>".format(context) + + +class BulkHostedNumberOrderContext(InstanceContext): + + def __init__(self, version: Version, bulk_hosting_sid: str): + """ + Initialize the BulkHostedNumberOrderContext + + :param version: Version that contains the resource + :param bulk_hosting_sid: A 34 character string that uniquely identifies this BulkHostedNumberOrder. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bulk_hosting_sid": bulk_hosting_sid, + } + self._uri = "/HostedNumber/Orders/Bulk/{bulk_hosting_sid}".format( + **self._solution + ) + + def fetch( + self, order_status: Union[str, object] = values.unset + ) -> BulkHostedNumberOrderInstance: + """ + Fetch the BulkHostedNumberOrderInstance + + :param order_status: Order status can be used for filtering on Hosted Number Order status values. To see a complete list of order statuses, please check 'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values'. + + :returns: The fetched BulkHostedNumberOrderInstance + """ + + data = values.of( + { + "OrderStatus": order_status, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return BulkHostedNumberOrderInstance( + self._version, + payload, + bulk_hosting_sid=self._solution["bulk_hosting_sid"], + ) + + async def fetch_async( + self, order_status: Union[str, object] = values.unset + ) -> BulkHostedNumberOrderInstance: + """ + Asynchronous coroutine to fetch the BulkHostedNumberOrderInstance + + :param order_status: Order status can be used for filtering on Hosted Number Order status values. To see a complete list of order statuses, please check 'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values'. + + :returns: The fetched BulkHostedNumberOrderInstance + """ + + data = values.of( + { + "OrderStatus": order_status, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return BulkHostedNumberOrderInstance( + self._version, + payload, + bulk_hosting_sid=self._solution["bulk_hosting_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.BulkHostedNumberOrderContext {}>".format(context) + + +class BulkHostedNumberOrderList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BulkHostedNumberOrderList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/HostedNumber/Orders/Bulk" + + def create( + self, body: Union[object, object] = values.unset + ) -> BulkHostedNumberOrderInstance: + """ + Create the BulkHostedNumberOrderInstance + + :param body: + + :returns: The created BulkHostedNumberOrderInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BulkHostedNumberOrderInstance(self._version, payload) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> BulkHostedNumberOrderInstance: + """ + Asynchronously create the BulkHostedNumberOrderInstance + + :param body: + + :returns: The created BulkHostedNumberOrderInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BulkHostedNumberOrderInstance(self._version, payload) + + def get(self, bulk_hosting_sid: str) -> BulkHostedNumberOrderContext: + """ + Constructs a BulkHostedNumberOrderContext + + :param bulk_hosting_sid: A 34 character string that uniquely identifies this BulkHostedNumberOrder. + """ + return BulkHostedNumberOrderContext( + self._version, bulk_hosting_sid=bulk_hosting_sid + ) + + def __call__(self, bulk_hosting_sid: str) -> BulkHostedNumberOrderContext: + """ + Constructs a BulkHostedNumberOrderContext + + :param bulk_hosting_sid: A 34 character string that uniquely identifies this BulkHostedNumberOrder. + """ + return BulkHostedNumberOrderContext( + self._version, bulk_hosting_sid=bulk_hosting_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.BulkHostedNumberOrderList>" diff --git a/twilio/rest/numbers/v2/bundle_clone.py b/twilio/rest/numbers/v2/bundle_clone.py new file mode 100644 index 0000000000..820fbc9db5 --- /dev/null +++ b/twilio/rest/numbers/v2/bundle_clone.py @@ -0,0 +1,268 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class BundleCloneInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PENDING_REVIEW = "pending-review" + IN_REVIEW = "in-review" + TWILIO_REJECTED = "twilio-rejected" + TWILIO_APPROVED = "twilio-approved" + PROVISIONALLY_APPROVED = "provisionally-approved" + + """ + :ivar bundle_sid: The unique string that we created to identify the Bundle resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Bundle resource. + :ivar regulation_sid: The unique string of a regulation that is associated to the Bundle resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar status: + :ivar valid_until: The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format when the resource will be valid until. + :ivar email: The email address that will receive updates when the Bundle resource changes status. + :ivar status_callback: The URL we call to inform your application of status changes. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + bundle_sid: Optional[str] = None, + ): + super().__init__(version) + + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.regulation_sid: Optional[str] = payload.get("regulation_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["BundleCloneInstance.Status"] = payload.get("status") + self.valid_until: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("valid_until") + ) + self.email: Optional[str] = payload.get("email") + self.status_callback: Optional[str] = payload.get("status_callback") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "bundle_sid": bundle_sid or self.bundle_sid, + } + self._context: Optional[BundleCloneContext] = None + + @property + def _proxy(self) -> "BundleCloneContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BundleCloneContext for this BundleCloneInstance + """ + if self._context is None: + self._context = BundleCloneContext( + self._version, + bundle_sid=self._solution["bundle_sid"], + ) + return self._context + + def create( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "BundleCloneInstance": + """ + Create the BundleCloneInstance + + :param target_account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) where the bundle needs to be cloned. + :param move_to_draft: If set to true, the cloned bundle will be in the DRAFT state, else it will be twilio-approved + :param friendly_name: The string that you assigned to describe the cloned bundle. + + :returns: The created BundleCloneInstance + """ + return self._proxy.create( + target_account_sid, + move_to_draft=move_to_draft, + friendly_name=friendly_name, + ) + + async def create_async( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "BundleCloneInstance": + """ + Asynchronous coroutine to create the BundleCloneInstance + + :param target_account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) where the bundle needs to be cloned. + :param move_to_draft: If set to true, the cloned bundle will be in the DRAFT state, else it will be twilio-approved + :param friendly_name: The string that you assigned to describe the cloned bundle. + + :returns: The created BundleCloneInstance + """ + return await self._proxy.create_async( + target_account_sid, + move_to_draft=move_to_draft, + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.BundleCloneInstance {}>".format(context) + + +class BundleCloneContext(InstanceContext): + + def __init__(self, version: Version, bundle_sid: str): + """ + Initialize the BundleCloneContext + + :param version: Version that contains the resource + :param bundle_sid: The unique string that identifies the Bundle to be cloned. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + } + self._uri = "/RegulatoryCompliance/Bundles/{bundle_sid}/Clones".format( + **self._solution + ) + + def create( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> BundleCloneInstance: + """ + Create the BundleCloneInstance + + :param target_account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) where the bundle needs to be cloned. + :param move_to_draft: If set to true, the cloned bundle will be in the DRAFT state, else it will be twilio-approved + :param friendly_name: The string that you assigned to describe the cloned bundle. + + :returns: The created BundleCloneInstance + """ + data = values.of( + { + "TargetAccountSid": target_account_sid, + "MoveToDraft": serialize.boolean_to_string(move_to_draft), + "FriendlyName": friendly_name, + } + ) + + payload = self._version.create(method="POST", uri=self._uri, data=data) + + return BundleCloneInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + async def create_async( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> BundleCloneInstance: + """ + Asynchronous coroutine to create the BundleCloneInstance + + :param target_account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) where the bundle needs to be cloned. + :param move_to_draft: If set to true, the cloned bundle will be in the DRAFT state, else it will be twilio-approved + :param friendly_name: The string that you assigned to describe the cloned bundle. + + :returns: The created BundleCloneInstance + """ + data = values.of( + { + "TargetAccountSid": target_account_sid, + "MoveToDraft": serialize.boolean_to_string(move_to_draft), + "FriendlyName": friendly_name, + } + ) + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data + ) + + return BundleCloneInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.BundleCloneContext {}>".format(context) + + +class BundleCloneList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BundleCloneList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, bundle_sid: str) -> BundleCloneContext: + """ + Constructs a BundleCloneContext + + :param bundle_sid: The unique string that identifies the Bundle to be cloned. + """ + return BundleCloneContext(self._version, bundle_sid=bundle_sid) + + def __call__(self, bundle_sid: str) -> BundleCloneContext: + """ + Constructs a BundleCloneContext + + :param bundle_sid: The unique string that identifies the Bundle to be cloned. + """ + return BundleCloneContext(self._version, bundle_sid=bundle_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.BundleCloneList>" diff --git a/twilio/rest/numbers/v2/hosted_number_order.py b/twilio/rest/numbers/v2/hosted_number_order.py new file mode 100644 index 0000000000..6afa755bd3 --- /dev/null +++ b/twilio/rest/numbers/v2/hosted_number_order.py @@ -0,0 +1,887 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class HostedNumberOrderInstance(InstanceResource): + + class Status(object): + TWILIO_PROCESSING = "twilio-processing" + RECEIVED = "received" + PENDING_VERIFICATION = "pending-verification" + VERIFIED = "verified" + PENDING_LOA = "pending-loa" + CARRIER_PROCESSING = "carrier-processing" + TESTING = "testing" + COMPLETED = "completed" + FAILED = "failed" + ACTION_REQUIRED = "action-required" + + class VerificationType(object): + PHONE_CALL = "phone-call" + + """ + :ivar sid: A 34 character string that uniquely identifies this HostedNumberOrder. + :ivar account_sid: A 34 character string that uniquely identifies the account. + :ivar incoming_phone_number_sid: A 34 character string that uniquely identifies the [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the phone number being hosted. + :ivar address_sid: A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :ivar signing_document_sid: A 34 character string that uniquely identifies the [Authorization Document](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource) the user needs to sign. + :ivar phone_number: Phone number to be hosted. This must be in [E.164](https://en.wikipedia.org/wiki/E.164) format, e.g., +16175551212 + :ivar capabilities: + :ivar friendly_name: A 128 character string that is a human-readable text that describes this resource. + :ivar status: + :ivar failure_reason: A message that explains why a hosted_number_order went to status \"action-required\" + :ivar date_created: The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar email: Email of the owner of this phone number that is being hosted. + :ivar cc_emails: A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :ivar url: The URL of this HostedNumberOrder. + :ivar contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :ivar contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :ivar bulk_hosting_request_sid: A 34 character string that uniquely identifies the bulk hosting request associated with this HostedNumberOrder. + :ivar next_step: The next step you need to take to complete the hosted number order and request it successfully. + :ivar verification_attempts: The number of attempts made to verify ownership via a call for the hosted phone number. + :ivar verification_call_sids: The Call SIDs that identify the calls placed to verify ownership. + :ivar verification_call_delay: The number of seconds to wait before initiating the ownership verification call. Can be a value between 0 and 60, inclusive. + :ivar verification_call_extension: The numerical extension to dial when making the ownership verification call. + :ivar verification_code: The digits the user must pass in the ownership verification call. + :ivar verification_type: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.incoming_phone_number_sid: Optional[str] = payload.get( + "incoming_phone_number_sid" + ) + self.address_sid: Optional[str] = payload.get("address_sid") + self.signing_document_sid: Optional[str] = payload.get("signing_document_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.capabilities: Optional[str] = payload.get("capabilities") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["HostedNumberOrderInstance.Status"] = payload.get( + "status" + ) + self.failure_reason: Optional[str] = payload.get("failure_reason") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.email: Optional[str] = payload.get("email") + self.cc_emails: Optional[List[str]] = payload.get("cc_emails") + self.url: Optional[str] = payload.get("url") + self.contact_title: Optional[str] = payload.get("contact_title") + self.contact_phone_number: Optional[str] = payload.get("contact_phone_number") + self.bulk_hosting_request_sid: Optional[str] = payload.get( + "bulk_hosting_request_sid" + ) + self.next_step: Optional[str] = payload.get("next_step") + self.verification_attempts: Optional[int] = deserialize.integer( + payload.get("verification_attempts") + ) + self.verification_call_sids: Optional[List[str]] = payload.get( + "verification_call_sids" + ) + self.verification_call_delay: Optional[int] = deserialize.integer( + payload.get("verification_call_delay") + ) + self.verification_call_extension: Optional[str] = payload.get( + "verification_call_extension" + ) + self.verification_code: Optional[str] = payload.get("verification_code") + self.verification_type: Optional[ + "HostedNumberOrderInstance.VerificationType" + ] = payload.get("verification_type") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[HostedNumberOrderContext] = None + + @property + def _proxy(self) -> "HostedNumberOrderContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: HostedNumberOrderContext for this HostedNumberOrderInstance + """ + if self._context is None: + self._context = HostedNumberOrderContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the HostedNumberOrderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the HostedNumberOrderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "HostedNumberOrderInstance": + """ + Fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "HostedNumberOrderInstance": + """ + Asynchronous coroutine to fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + status: "HostedNumberOrderInstance.Status", + verification_call_delay: Union[int, object] = values.unset, + verification_call_extension: Union[str, object] = values.unset, + ) -> "HostedNumberOrderInstance": + """ + Update the HostedNumberOrderInstance + + :param status: + :param verification_call_delay: The number of seconds to wait before initiating the ownership verification call. Can be a value between 0 and 60, inclusive. + :param verification_call_extension: The numerical extension to dial when making the ownership verification call. + + :returns: The updated HostedNumberOrderInstance + """ + return self._proxy.update( + status=status, + verification_call_delay=verification_call_delay, + verification_call_extension=verification_call_extension, + ) + + async def update_async( + self, + status: "HostedNumberOrderInstance.Status", + verification_call_delay: Union[int, object] = values.unset, + verification_call_extension: Union[str, object] = values.unset, + ) -> "HostedNumberOrderInstance": + """ + Asynchronous coroutine to update the HostedNumberOrderInstance + + :param status: + :param verification_call_delay: The number of seconds to wait before initiating the ownership verification call. Can be a value between 0 and 60, inclusive. + :param verification_call_extension: The numerical extension to dial when making the ownership verification call. + + :returns: The updated HostedNumberOrderInstance + """ + return await self._proxy.update_async( + status=status, + verification_call_delay=verification_call_delay, + verification_call_extension=verification_call_extension, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.HostedNumberOrderInstance {}>".format(context) + + +class HostedNumberOrderContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the HostedNumberOrderContext + + :param version: Version that contains the resource + :param sid: The SID of the HostedNumberOrder resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/HostedNumber/Orders/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the HostedNumberOrderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the HostedNumberOrderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> HostedNumberOrderInstance: + """ + Fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> HostedNumberOrderInstance: + """ + Asynchronous coroutine to fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + status: "HostedNumberOrderInstance.Status", + verification_call_delay: Union[int, object] = values.unset, + verification_call_extension: Union[str, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Update the HostedNumberOrderInstance + + :param status: + :param verification_call_delay: The number of seconds to wait before initiating the ownership verification call. Can be a value between 0 and 60, inclusive. + :param verification_call_extension: The numerical extension to dial when making the ownership verification call. + + :returns: The updated HostedNumberOrderInstance + """ + + data = values.of( + { + "Status": status, + "VerificationCallDelay": verification_call_delay, + "VerificationCallExtension": verification_call_extension, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, + status: "HostedNumberOrderInstance.Status", + verification_call_delay: Union[int, object] = values.unset, + verification_call_extension: Union[str, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Asynchronous coroutine to update the HostedNumberOrderInstance + + :param status: + :param verification_call_delay: The number of seconds to wait before initiating the ownership verification call. Can be a value between 0 and 60, inclusive. + :param verification_call_extension: The numerical extension to dial when making the ownership verification call. + + :returns: The updated HostedNumberOrderInstance + """ + + data = values.of( + { + "Status": status, + "VerificationCallDelay": verification_call_delay, + "VerificationCallExtension": verification_call_extension, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.HostedNumberOrderContext {}>".format(context) + + +class HostedNumberOrderPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> HostedNumberOrderInstance: + """ + Build an instance of HostedNumberOrderInstance + + :param payload: Payload response from the API + """ + return HostedNumberOrderInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.HostedNumberOrderPage>" + + +class HostedNumberOrderList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the HostedNumberOrderList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/HostedNumber/Orders" + + def create( + self, + phone_number: str, + contact_phone_number: str, + address_sid: str, + email: str, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + contact_title: Union[str, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Create the HostedNumberOrderInstance + + :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :param email: Optional. Email of the owner of this phone number that is being hosted. + :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. + :param friendly_name: A 128 character string that is a human readable text that describes this resource. + :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. + :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. + :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. + :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. + :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. + :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. + :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + + :returns: The created HostedNumberOrderInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "ContactPhoneNumber": contact_phone_number, + "AddressSid": address_sid, + "Email": email, + "AccountSid": account_sid, + "FriendlyName": friendly_name, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsCapability": serialize.boolean_to_string(sms_capability), + "SmsFallbackMethod": sms_fallback_method, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "SmsApplicationSid": sms_application_sid, + "ContactTitle": contact_title, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return HostedNumberOrderInstance(self._version, payload) + + async def create_async( + self, + phone_number: str, + contact_phone_number: str, + address_sid: str, + email: str, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + contact_title: Union[str, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Asynchronously create the HostedNumberOrderInstance + + :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :param email: Optional. Email of the owner of this phone number that is being hosted. + :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. + :param friendly_name: A 128 character string that is a human readable text that describes this resource. + :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. + :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. + :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. + :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. + :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. + :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. + :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + + :returns: The created HostedNumberOrderInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "ContactPhoneNumber": contact_phone_number, + "AddressSid": address_sid, + "Email": email, + "AccountSid": account_sid, + "FriendlyName": friendly_name, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsCapability": serialize.boolean_to_string(sms_capability), + "SmsFallbackMethod": sms_fallback_method, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "SmsApplicationSid": sms_application_sid, + "ContactTitle": contact_title, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return HostedNumberOrderInstance(self._version, payload) + + def stream( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[HostedNumberOrderInstance]: + """ + Streams HostedNumberOrderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param bool sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + sms_capability=sms_capability, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[HostedNumberOrderInstance]: + """ + Asynchronously streams HostedNumberOrderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param bool sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + sms_capability=sms_capability, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[HostedNumberOrderInstance]: + """ + Lists HostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param bool sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + sms_capability=sms_capability, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[HostedNumberOrderInstance]: + """ + Asynchronously lists HostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param bool sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 128 characters. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + sms_capability=sms_capability, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> HostedNumberOrderPage: + """ + Retrieve a single page of HostedNumberOrderInstance records from the API. + Request is executed immediately + + :param status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 128 characters. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of HostedNumberOrderInstance + """ + data = values.of( + { + "Status": status, + "SmsCapability": serialize.boolean_to_string(sms_capability), + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return HostedNumberOrderPage(self._version, response) + + async def page_async( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + sms_capability: Union[bool, object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> HostedNumberOrderPage: + """ + Asynchronously retrieve a single page of HostedNumberOrderInstance records from the API. + Request is executed immediately + + :param status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param sms_capability: Whether the SMS capability will be hosted on our platform. Can be `true` of `false`. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 128 characters. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of HostedNumberOrderInstance + """ + data = values.of( + { + "Status": status, + "SmsCapability": serialize.boolean_to_string(sms_capability), + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return HostedNumberOrderPage(self._version, response) + + def get_page(self, target_url: str) -> HostedNumberOrderPage: + """ + Retrieve a specific page of HostedNumberOrderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of HostedNumberOrderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return HostedNumberOrderPage(self._version, response) + + async def get_page_async(self, target_url: str) -> HostedNumberOrderPage: + """ + Asynchronously retrieve a specific page of HostedNumberOrderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of HostedNumberOrderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return HostedNumberOrderPage(self._version, response) + + def get(self, sid: str) -> HostedNumberOrderContext: + """ + Constructs a HostedNumberOrderContext + + :param sid: The SID of the HostedNumberOrder resource to update. + """ + return HostedNumberOrderContext(self._version, sid=sid) + + def __call__(self, sid: str) -> HostedNumberOrderContext: + """ + Constructs a HostedNumberOrderContext + + :param sid: The SID of the HostedNumberOrder resource to update. + """ + return HostedNumberOrderContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.HostedNumberOrderList>" diff --git a/twilio/rest/numbers/v2/regulatory_compliance/__init__.py b/twilio/rest/numbers/v2/regulatory_compliance/__init__.py new file mode 100644 index 0000000000..189117d85c --- /dev/null +++ b/twilio/rest/numbers/v2/regulatory_compliance/__init__.py @@ -0,0 +1,113 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.numbers.v2.regulatory_compliance.bundle import BundleList +from twilio.rest.numbers.v2.regulatory_compliance.end_user import EndUserList +from twilio.rest.numbers.v2.regulatory_compliance.end_user_type import EndUserTypeList +from twilio.rest.numbers.v2.regulatory_compliance.regulation import RegulationList +from twilio.rest.numbers.v2.regulatory_compliance.supporting_document import ( + SupportingDocumentList, +) +from twilio.rest.numbers.v2.regulatory_compliance.supporting_document_type import ( + SupportingDocumentTypeList, +) + + +class RegulatoryComplianceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RegulatoryComplianceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RegulatoryCompliance" + + self._bundles: Optional[BundleList] = None + self._end_users: Optional[EndUserList] = None + self._end_user_types: Optional[EndUserTypeList] = None + self._regulations: Optional[RegulationList] = None + self._supporting_documents: Optional[SupportingDocumentList] = None + self._supporting_document_types: Optional[SupportingDocumentTypeList] = None + + @property + def bundles(self) -> BundleList: + """ + Access the bundles + """ + if self._bundles is None: + self._bundles = BundleList(self._version) + return self._bundles + + @property + def end_users(self) -> EndUserList: + """ + Access the end_users + """ + if self._end_users is None: + self._end_users = EndUserList(self._version) + return self._end_users + + @property + def end_user_types(self) -> EndUserTypeList: + """ + Access the end_user_types + """ + if self._end_user_types is None: + self._end_user_types = EndUserTypeList(self._version) + return self._end_user_types + + @property + def regulations(self) -> RegulationList: + """ + Access the regulations + """ + if self._regulations is None: + self._regulations = RegulationList(self._version) + return self._regulations + + @property + def supporting_documents(self) -> SupportingDocumentList: + """ + Access the supporting_documents + """ + if self._supporting_documents is None: + self._supporting_documents = SupportingDocumentList(self._version) + return self._supporting_documents + + @property + def supporting_document_types(self) -> SupportingDocumentTypeList: + """ + Access the supporting_document_types + """ + if self._supporting_document_types is None: + self._supporting_document_types = SupportingDocumentTypeList(self._version) + return self._supporting_document_types + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.RegulatoryComplianceList>" diff --git a/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py b/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py new file mode 100644 index 0000000000..079540d87b --- /dev/null +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py @@ -0,0 +1,1013 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.numbers.v2.regulatory_compliance.bundle.bundle_copy import ( + BundleCopyList, +) +from twilio.rest.numbers.v2.regulatory_compliance.bundle.evaluation import ( + EvaluationList, +) +from twilio.rest.numbers.v2.regulatory_compliance.bundle.item_assignment import ( + ItemAssignmentList, +) +from twilio.rest.numbers.v2.regulatory_compliance.bundle.replace_items import ( + ReplaceItemsList, +) + + +class BundleInstance(InstanceResource): + + class EndUserType(object): + INDIVIDUAL = "individual" + BUSINESS = "business" + + class SortBy(object): + VALID_UNTIL = "valid-until" + DATE_UPDATED = "date-updated" + + class SortDirection(object): + ASC = "ASC" + DESC = "DESC" + + class Status(object): + DRAFT = "draft" + PENDING_REVIEW = "pending-review" + IN_REVIEW = "in-review" + TWILIO_REJECTED = "twilio-rejected" + TWILIO_APPROVED = "twilio-approved" + PROVISIONALLY_APPROVED = "provisionally-approved" + + """ + :ivar sid: The unique string that we created to identify the Bundle resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Bundle resource. + :ivar regulation_sid: The unique string of a regulation that is associated to the Bundle resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar status: + :ivar valid_until: The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format when the resource will be valid until. + :ivar email: The email address that will receive updates when the Bundle resource changes status. + :ivar status_callback: The URL we call to inform your application of status changes. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Bundle resource. + :ivar links: The URLs of the Assigned Items of the Bundle resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.regulation_sid: Optional[str] = payload.get("regulation_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["BundleInstance.Status"] = payload.get("status") + self.valid_until: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("valid_until") + ) + self.email: Optional[str] = payload.get("email") + self.status_callback: Optional[str] = payload.get("status_callback") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[BundleContext] = None + + @property + def _proxy(self) -> "BundleContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BundleContext for this BundleInstance + """ + if self._context is None: + self._context = BundleContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the BundleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BundleInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "BundleInstance": + """ + Fetch the BundleInstance + + + :returns: The fetched BundleInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BundleInstance": + """ + Asynchronous coroutine to fetch the BundleInstance + + + :returns: The fetched BundleInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + status: Union["BundleInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> "BundleInstance": + """ + Update the BundleInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + + :returns: The updated BundleInstance + """ + return self._proxy.update( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + + async def update_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> "BundleInstance": + """ + Asynchronous coroutine to update the BundleInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + + :returns: The updated BundleInstance + """ + return await self._proxy.update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + + @property + def bundle_copies(self) -> BundleCopyList: + """ + Access the bundle_copies + """ + return self._proxy.bundle_copies + + @property + def evaluations(self) -> EvaluationList: + """ + Access the evaluations + """ + return self._proxy.evaluations + + @property + def item_assignments(self) -> ItemAssignmentList: + """ + Access the item_assignments + """ + return self._proxy.item_assignments + + @property + def replace_items(self) -> ReplaceItemsList: + """ + Access the replace_items + """ + return self._proxy.replace_items + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.BundleInstance {}>".format(context) + + +class BundleContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the BundleContext + + :param version: Version that contains the resource + :param sid: The unique string that we created to identify the Bundle resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/Bundles/{sid}".format(**self._solution) + + self._bundle_copies: Optional[BundleCopyList] = None + self._evaluations: Optional[EvaluationList] = None + self._item_assignments: Optional[ItemAssignmentList] = None + self._replace_items: Optional[ReplaceItemsList] = None + + def delete(self) -> bool: + """ + Deletes the BundleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BundleInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> BundleInstance: + """ + Fetch the BundleInstance + + + :returns: The fetched BundleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return BundleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> BundleInstance: + """ + Asynchronous coroutine to fetch the BundleInstance + + + :returns: The fetched BundleInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return BundleInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + status: Union["BundleInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> BundleInstance: + """ + Update the BundleInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + + :returns: The updated BundleInstance + """ + + data = values.of( + { + "Status": status, + "StatusCallback": status_callback, + "FriendlyName": friendly_name, + "Email": email, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BundleInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> BundleInstance: + """ + Asynchronous coroutine to update the BundleInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + + :returns: The updated BundleInstance + """ + + data = values.of( + { + "Status": status, + "StatusCallback": status_callback, + "FriendlyName": friendly_name, + "Email": email, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BundleInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def bundle_copies(self) -> BundleCopyList: + """ + Access the bundle_copies + """ + if self._bundle_copies is None: + self._bundle_copies = BundleCopyList( + self._version, + self._solution["sid"], + ) + return self._bundle_copies + + @property + def evaluations(self) -> EvaluationList: + """ + Access the evaluations + """ + if self._evaluations is None: + self._evaluations = EvaluationList( + self._version, + self._solution["sid"], + ) + return self._evaluations + + @property + def item_assignments(self) -> ItemAssignmentList: + """ + Access the item_assignments + """ + if self._item_assignments is None: + self._item_assignments = ItemAssignmentList( + self._version, + self._solution["sid"], + ) + return self._item_assignments + + @property + def replace_items(self) -> ReplaceItemsList: + """ + Access the replace_items + """ + if self._replace_items is None: + self._replace_items = ReplaceItemsList( + self._version, + self._solution["sid"], + ) + return self._replace_items + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.BundleContext {}>".format(context) + + +class BundlePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BundleInstance: + """ + Build an instance of BundleInstance + + :param payload: Payload response from the API + """ + return BundleInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.BundlePage>" + + +class BundleList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BundleList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RegulatoryCompliance/Bundles" + + def create( + self, + friendly_name: str, + email: str, + status_callback: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + end_user_type: Union["BundleInstance.EndUserType", object] = values.unset, + number_type: Union[str, object] = values.unset, + is_test: Union[bool, object] = values.unset, + ) -> BundleInstance: + """ + Create the BundleInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + :param status_callback: The URL we call to inform your application of status changes. + :param regulation_sid: The unique string of a regulation that is associated to the Bundle resource. + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param end_user_type: + :param number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param is_test: Indicates that Bundle is a Test Bundle and will be Auto-Rejected + + :returns: The created BundleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Email": email, + "StatusCallback": status_callback, + "RegulationSid": regulation_sid, + "IsoCountry": iso_country, + "EndUserType": end_user_type, + "NumberType": number_type, + "IsTest": serialize.boolean_to_string(is_test), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BundleInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + email: str, + status_callback: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + end_user_type: Union["BundleInstance.EndUserType", object] = values.unset, + number_type: Union[str, object] = values.unset, + is_test: Union[bool, object] = values.unset, + ) -> BundleInstance: + """ + Asynchronously create the BundleInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Bundle resource changes status. + :param status_callback: The URL we call to inform your application of status changes. + :param regulation_sid: The unique string of a regulation that is associated to the Bundle resource. + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param end_user_type: + :param number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param is_test: Indicates that Bundle is a Test Bundle and will be Auto-Rejected + + :returns: The created BundleInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Email": email, + "StatusCallback": status_callback, + "RegulationSid": regulation_sid, + "IsoCountry": iso_country, + "EndUserType": end_user_type, + "NumberType": number_type, + "IsTest": serialize.boolean_to_string(is_test), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BundleInstance(self._version, payload) + + def stream( + self, + status: Union["BundleInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + has_valid_until_date: Union[bool, object] = values.unset, + sort_by: Union["BundleInstance.SortBy", object] = values.unset, + sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, + valid_until_date: Union[datetime, object] = values.unset, + valid_until_date_before: Union[datetime, object] = values.unset, + valid_until_date_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BundleInstance]: + """ + Streams BundleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "BundleInstance.Status" status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param str friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. + :param str regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. + :param str iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param str number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param bool has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. + :param "BundleInstance.SortBy" sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. + :param "BundleInstance.SortDirection" sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. + :param datetime valid_until_date: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_before: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_after: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + friendly_name=friendly_name, + regulation_sid=regulation_sid, + iso_country=iso_country, + number_type=number_type, + has_valid_until_date=has_valid_until_date, + sort_by=sort_by, + sort_direction=sort_direction, + valid_until_date=valid_until_date, + valid_until_date_before=valid_until_date_before, + valid_until_date_after=valid_until_date_after, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + has_valid_until_date: Union[bool, object] = values.unset, + sort_by: Union["BundleInstance.SortBy", object] = values.unset, + sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, + valid_until_date: Union[datetime, object] = values.unset, + valid_until_date_before: Union[datetime, object] = values.unset, + valid_until_date_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BundleInstance]: + """ + Asynchronously streams BundleInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "BundleInstance.Status" status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param str friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. + :param str regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. + :param str iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param str number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param bool has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. + :param "BundleInstance.SortBy" sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. + :param "BundleInstance.SortDirection" sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. + :param datetime valid_until_date: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_before: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_after: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + friendly_name=friendly_name, + regulation_sid=regulation_sid, + iso_country=iso_country, + number_type=number_type, + has_valid_until_date=has_valid_until_date, + sort_by=sort_by, + sort_direction=sort_direction, + valid_until_date=valid_until_date, + valid_until_date_before=valid_until_date_before, + valid_until_date_after=valid_until_date_after, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["BundleInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + has_valid_until_date: Union[bool, object] = values.unset, + sort_by: Union["BundleInstance.SortBy", object] = values.unset, + sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, + valid_until_date: Union[datetime, object] = values.unset, + valid_until_date_before: Union[datetime, object] = values.unset, + valid_until_date_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BundleInstance]: + """ + Lists BundleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "BundleInstance.Status" status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param str friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. + :param str regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. + :param str iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param str number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param bool has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. + :param "BundleInstance.SortBy" sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. + :param "BundleInstance.SortDirection" sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. + :param datetime valid_until_date: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_before: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_after: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + friendly_name=friendly_name, + regulation_sid=regulation_sid, + iso_country=iso_country, + number_type=number_type, + has_valid_until_date=has_valid_until_date, + sort_by=sort_by, + sort_direction=sort_direction, + valid_until_date=valid_until_date, + valid_until_date_before=valid_until_date_before, + valid_until_date_after=valid_until_date_after, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + has_valid_until_date: Union[bool, object] = values.unset, + sort_by: Union["BundleInstance.SortBy", object] = values.unset, + sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, + valid_until_date: Union[datetime, object] = values.unset, + valid_until_date_before: Union[datetime, object] = values.unset, + valid_until_date_after: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BundleInstance]: + """ + Asynchronously lists BundleInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "BundleInstance.Status" status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param str friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. + :param str regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. + :param str iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param str number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param bool has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. + :param "BundleInstance.SortBy" sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. + :param "BundleInstance.SortDirection" sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. + :param datetime valid_until_date: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_before: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param datetime valid_until_date_after: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + friendly_name=friendly_name, + regulation_sid=regulation_sid, + iso_country=iso_country, + number_type=number_type, + has_valid_until_date=has_valid_until_date, + sort_by=sort_by, + sort_direction=sort_direction, + valid_until_date=valid_until_date, + valid_until_date_before=valid_until_date_before, + valid_until_date_after=valid_until_date_after, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["BundleInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + has_valid_until_date: Union[bool, object] = values.unset, + sort_by: Union["BundleInstance.SortBy", object] = values.unset, + sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, + valid_until_date: Union[datetime, object] = values.unset, + valid_until_date_before: Union[datetime, object] = values.unset, + valid_until_date_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BundlePage: + """ + Retrieve a single page of BundleInstance records from the API. + Request is executed immediately + + :param status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. + :param regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. + :param iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. + :param sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. + :param sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. + :param valid_until_date: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param valid_until_date_before: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param valid_until_date_after: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BundleInstance + """ + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "RegulationSid": regulation_sid, + "IsoCountry": iso_country, + "NumberType": number_type, + "HasValidUntilDate": serialize.boolean_to_string(has_valid_until_date), + "SortBy": sort_by, + "SortDirection": sort_direction, + "ValidUntilDate": serialize.iso8601_datetime(valid_until_date), + "ValidUntilDate<": serialize.iso8601_datetime(valid_until_date_before), + "ValidUntilDate>": serialize.iso8601_datetime(valid_until_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BundlePage(self._version, response) + + async def page_async( + self, + status: Union["BundleInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + regulation_sid: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + has_valid_until_date: Union[bool, object] = values.unset, + sort_by: Union["BundleInstance.SortBy", object] = values.unset, + sort_direction: Union["BundleInstance.SortDirection", object] = values.unset, + valid_until_date: Union[datetime, object] = values.unset, + valid_until_date_before: Union[datetime, object] = values.unset, + valid_until_date_after: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BundlePage: + """ + Asynchronously retrieve a single page of BundleInstance records from the API. + Request is executed immediately + + :param status: The verification status of the Bundle resource. Please refer to [Bundle Statuses](https://www.twilio.com/docs/phone-numbers/regulatory/api/bundles#bundle-statuses) for more details. + :param friendly_name: The string that you assigned to describe the resource. The column can contain 255 variable characters. + :param regulation_sid: The unique string of a [Regulation resource](https://www.twilio.com/docs/phone-numbers/regulatory/api/regulations) that is associated to the Bundle resource. + :param iso_country: The 2-digit [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Bundle's phone number country ownership request. + :param number_type: The type of phone number of the Bundle's ownership request. Can be `local`, `mobile`, `national`, or `toll-free`. + :param has_valid_until_date: Indicates that the Bundle is a valid Bundle until a specified expiration date. + :param sort_by: Can be `valid-until` or `date-updated`. Defaults to `date-created`. + :param sort_direction: Default is `DESC`. Can be `ASC` or `DESC`. + :param valid_until_date: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param valid_until_date_before: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param valid_until_date_after: Date to filter Bundles having their `valid_until_date` before or after the specified date. Can be `ValidUntilDate>=` or `ValidUntilDate<=`. Both can be used in conjunction as well. [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) is the acceptable date format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BundleInstance + """ + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "RegulationSid": regulation_sid, + "IsoCountry": iso_country, + "NumberType": number_type, + "HasValidUntilDate": serialize.boolean_to_string(has_valid_until_date), + "SortBy": sort_by, + "SortDirection": sort_direction, + "ValidUntilDate": serialize.iso8601_datetime(valid_until_date), + "ValidUntilDate<": serialize.iso8601_datetime(valid_until_date_before), + "ValidUntilDate>": serialize.iso8601_datetime(valid_until_date_after), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BundlePage(self._version, response) + + def get_page(self, target_url: str) -> BundlePage: + """ + Retrieve a specific page of BundleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BundleInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BundlePage(self._version, response) + + async def get_page_async(self, target_url: str) -> BundlePage: + """ + Asynchronously retrieve a specific page of BundleInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BundleInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BundlePage(self._version, response) + + def get(self, sid: str) -> BundleContext: + """ + Constructs a BundleContext + + :param sid: The unique string that we created to identify the Bundle resource. + """ + return BundleContext(self._version, sid=sid) + + def __call__(self, sid: str) -> BundleContext: + """ + Constructs a BundleContext + + :param sid: The unique string that we created to identify the Bundle resource. + """ + return BundleContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.BundleList>" diff --git a/twilio/rest/numbers/v2/regulatory_compliance/bundle/bundle_copy.py b/twilio/rest/numbers/v2/regulatory_compliance/bundle/bundle_copy.py new file mode 100644 index 0000000000..d20a569690 --- /dev/null +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/bundle_copy.py @@ -0,0 +1,382 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class BundleCopyInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PENDING_REVIEW = "pending-review" + IN_REVIEW = "in-review" + TWILIO_REJECTED = "twilio-rejected" + TWILIO_APPROVED = "twilio-approved" + PROVISIONALLY_APPROVED = "provisionally-approved" + + """ + :ivar sid: The unique string that we created to identify the Bundle resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Bundle resource. + :ivar regulation_sid: The unique string of a regulation that is associated to the Bundle resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar status: + :ivar valid_until: The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format when the resource will be valid until. + :ivar email: The email address that will receive updates when the Bundle resource changes status. + :ivar status_callback: The URL we call to inform your application of status changes. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], bundle_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.regulation_sid: Optional[str] = payload.get("regulation_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["BundleCopyInstance.Status"] = payload.get("status") + self.valid_until: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("valid_until") + ) + self.email: Optional[str] = payload.get("email") + self.status_callback: Optional[str] = payload.get("status_callback") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "bundle_sid": bundle_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.BundleCopyInstance {}>".format(context) + + +class BundleCopyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BundleCopyInstance: + """ + Build an instance of BundleCopyInstance + + :param payload: Payload response from the API + """ + return BundleCopyInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.BundleCopyPage>" + + +class BundleCopyList(ListResource): + + def __init__(self, version: Version, bundle_sid: str): + """ + Initialize the BundleCopyList + + :param version: Version that contains the resource + :param bundle_sid: The unique string that we created to identify the Bundle resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + } + self._uri = "/RegulatoryCompliance/Bundles/{bundle_sid}/Copies".format( + **self._solution + ) + + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> BundleCopyInstance: + """ + Create the BundleCopyInstance + + :param friendly_name: The string that you assigned to describe the copied bundle. + + :returns: The created BundleCopyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BundleCopyInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> BundleCopyInstance: + """ + Asynchronously create the BundleCopyInstance + + :param friendly_name: The string that you assigned to describe the copied bundle. + + :returns: The created BundleCopyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BundleCopyInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BundleCopyInstance]: + """ + Streams BundleCopyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BundleCopyInstance]: + """ + Asynchronously streams BundleCopyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BundleCopyInstance]: + """ + Lists BundleCopyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BundleCopyInstance]: + """ + Asynchronously lists BundleCopyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BundleCopyPage: + """ + Retrieve a single page of BundleCopyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BundleCopyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BundleCopyPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BundleCopyPage: + """ + Asynchronously retrieve a single page of BundleCopyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BundleCopyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BundleCopyPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> BundleCopyPage: + """ + Retrieve a specific page of BundleCopyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BundleCopyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BundleCopyPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> BundleCopyPage: + """ + Asynchronously retrieve a specific page of BundleCopyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BundleCopyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BundleCopyPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.BundleCopyList>" diff --git a/twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py b/twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py new file mode 100644 index 0000000000..fd45064808 --- /dev/null +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py @@ -0,0 +1,487 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EvaluationInstance(InstanceResource): + + class Status(object): + COMPLIANT = "compliant" + NONCOMPLIANT = "noncompliant" + + """ + :ivar sid: The unique string that identifies the Evaluation resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Bundle resource. + :ivar regulation_sid: The unique string of a regulation that is associated to the Bundle resource. + :ivar bundle_sid: The unique string that we created to identify the Bundle resource. + :ivar status: + :ivar results: The results of the Evaluation which includes the valid and invalid attributes. + :ivar date_created: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + bundle_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.regulation_sid: Optional[str] = payload.get("regulation_sid") + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.status: Optional["EvaluationInstance.Status"] = payload.get("status") + self.results: Optional[List[Dict[str, object]]] = payload.get("results") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "bundle_sid": bundle_sid, + "sid": sid or self.sid, + } + self._context: Optional[EvaluationContext] = None + + @property + def _proxy(self) -> "EvaluationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EvaluationContext for this EvaluationInstance + """ + if self._context is None: + self._context = EvaluationContext( + self._version, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "EvaluationInstance": + """ + Fetch the EvaluationInstance + + + :returns: The fetched EvaluationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EvaluationInstance": + """ + Asynchronous coroutine to fetch the EvaluationInstance + + + :returns: The fetched EvaluationInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.EvaluationInstance {}>".format(context) + + +class EvaluationContext(InstanceContext): + + def __init__(self, version: Version, bundle_sid: str, sid: str): + """ + Initialize the EvaluationContext + + :param version: Version that contains the resource + :param bundle_sid: The unique string that we created to identify the Bundle resource. + :param sid: The unique string that identifies the Evaluation resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + "sid": sid, + } + self._uri = ( + "/RegulatoryCompliance/Bundles/{bundle_sid}/Evaluations/{sid}".format( + **self._solution + ) + ) + + def fetch(self) -> EvaluationInstance: + """ + Fetch the EvaluationInstance + + + :returns: The fetched EvaluationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EvaluationInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EvaluationInstance: + """ + Asynchronous coroutine to fetch the EvaluationInstance + + + :returns: The fetched EvaluationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EvaluationInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.EvaluationContext {}>".format(context) + + +class EvaluationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EvaluationInstance: + """ + Build an instance of EvaluationInstance + + :param payload: Payload response from the API + """ + return EvaluationInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.EvaluationPage>" + + +class EvaluationList(ListResource): + + def __init__(self, version: Version, bundle_sid: str): + """ + Initialize the EvaluationList + + :param version: Version that contains the resource + :param bundle_sid: The unique string that identifies the Bundle resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + } + self._uri = "/RegulatoryCompliance/Bundles/{bundle_sid}/Evaluations".format( + **self._solution + ) + + def create(self) -> EvaluationInstance: + """ + Create the EvaluationInstance + + + :returns: The created EvaluationInstance + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = self._version.create(method="POST", uri=self._uri, headers=headers) + + return EvaluationInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + async def create_async(self) -> EvaluationInstance: + """ + Asynchronously create the EvaluationInstance + + + :returns: The created EvaluationInstance + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, headers=headers + ) + + return EvaluationInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EvaluationInstance]: + """ + Streams EvaluationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EvaluationInstance]: + """ + Asynchronously streams EvaluationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EvaluationInstance]: + """ + Lists EvaluationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EvaluationInstance]: + """ + Asynchronously lists EvaluationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EvaluationPage: + """ + Retrieve a single page of EvaluationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EvaluationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EvaluationPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EvaluationPage: + """ + Asynchronously retrieve a single page of EvaluationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EvaluationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EvaluationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> EvaluationPage: + """ + Retrieve a specific page of EvaluationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EvaluationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EvaluationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> EvaluationPage: + """ + Asynchronously retrieve a specific page of EvaluationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EvaluationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EvaluationPage(self._version, response, self._solution) + + def get(self, sid: str) -> EvaluationContext: + """ + Constructs a EvaluationContext + + :param sid: The unique string that identifies the Evaluation resource. + """ + return EvaluationContext( + self._version, bundle_sid=self._solution["bundle_sid"], sid=sid + ) + + def __call__(self, sid: str) -> EvaluationContext: + """ + Constructs a EvaluationContext + + :param sid: The unique string that identifies the Evaluation resource. + """ + return EvaluationContext( + self._version, bundle_sid=self._solution["bundle_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.EvaluationList>" diff --git a/twilio/rest/numbers/v2/regulatory_compliance/bundle/item_assignment.py b/twilio/rest/numbers/v2/regulatory_compliance/bundle/item_assignment.py new file mode 100644 index 0000000000..4eb1fe2b33 --- /dev/null +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/item_assignment.py @@ -0,0 +1,540 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ItemAssignmentInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Item Assignment resource. + :ivar bundle_sid: The unique string that we created to identify the Bundle resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Item Assignment resource. + :ivar object_sid: The SID of an object bag that holds information of the different items. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Identity resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + bundle_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.object_sid: Optional[str] = payload.get("object_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "bundle_sid": bundle_sid, + "sid": sid or self.sid, + } + self._context: Optional[ItemAssignmentContext] = None + + @property + def _proxy(self) -> "ItemAssignmentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ItemAssignmentContext for this ItemAssignmentInstance + """ + if self._context is None: + self._context = ItemAssignmentContext( + self._version, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ItemAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ItemAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ItemAssignmentInstance": + """ + Fetch the ItemAssignmentInstance + + + :returns: The fetched ItemAssignmentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ItemAssignmentInstance": + """ + Asynchronous coroutine to fetch the ItemAssignmentInstance + + + :returns: The fetched ItemAssignmentInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.ItemAssignmentInstance {}>".format(context) + + +class ItemAssignmentContext(InstanceContext): + + def __init__(self, version: Version, bundle_sid: str, sid: str): + """ + Initialize the ItemAssignmentContext + + :param version: Version that contains the resource + :param bundle_sid: The unique string that we created to identify the Bundle resource. + :param sid: The unique string that we created to identify the Identity resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + "sid": sid, + } + self._uri = ( + "/RegulatoryCompliance/Bundles/{bundle_sid}/ItemAssignments/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the ItemAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ItemAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ItemAssignmentInstance: + """ + Fetch the ItemAssignmentInstance + + + :returns: The fetched ItemAssignmentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ItemAssignmentInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ItemAssignmentInstance: + """ + Asynchronous coroutine to fetch the ItemAssignmentInstance + + + :returns: The fetched ItemAssignmentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ItemAssignmentInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.ItemAssignmentContext {}>".format(context) + + +class ItemAssignmentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ItemAssignmentInstance: + """ + Build an instance of ItemAssignmentInstance + + :param payload: Payload response from the API + """ + return ItemAssignmentInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.ItemAssignmentPage>" + + +class ItemAssignmentList(ListResource): + + def __init__(self, version: Version, bundle_sid: str): + """ + Initialize the ItemAssignmentList + + :param version: Version that contains the resource + :param bundle_sid: The unique string that we created to identify the Bundle resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + } + self._uri = "/RegulatoryCompliance/Bundles/{bundle_sid}/ItemAssignments".format( + **self._solution + ) + + def create(self, object_sid: str) -> ItemAssignmentInstance: + """ + Create the ItemAssignmentInstance + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created ItemAssignmentInstance + """ + + data = values.of( + { + "ObjectSid": object_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ItemAssignmentInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + async def create_async(self, object_sid: str) -> ItemAssignmentInstance: + """ + Asynchronously create the ItemAssignmentInstance + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created ItemAssignmentInstance + """ + + data = values.of( + { + "ObjectSid": object_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ItemAssignmentInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ItemAssignmentInstance]: + """ + Streams ItemAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ItemAssignmentInstance]: + """ + Asynchronously streams ItemAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ItemAssignmentInstance]: + """ + Lists ItemAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ItemAssignmentInstance]: + """ + Asynchronously lists ItemAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ItemAssignmentPage: + """ + Retrieve a single page of ItemAssignmentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ItemAssignmentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ItemAssignmentPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ItemAssignmentPage: + """ + Asynchronously retrieve a single page of ItemAssignmentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ItemAssignmentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ItemAssignmentPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ItemAssignmentPage: + """ + Retrieve a specific page of ItemAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ItemAssignmentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ItemAssignmentPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ItemAssignmentPage: + """ + Asynchronously retrieve a specific page of ItemAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ItemAssignmentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ItemAssignmentPage(self._version, response, self._solution) + + def get(self, sid: str) -> ItemAssignmentContext: + """ + Constructs a ItemAssignmentContext + + :param sid: The unique string that we created to identify the Identity resource. + """ + return ItemAssignmentContext( + self._version, bundle_sid=self._solution["bundle_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ItemAssignmentContext: + """ + Constructs a ItemAssignmentContext + + :param sid: The unique string that we created to identify the Identity resource. + """ + return ItemAssignmentContext( + self._version, bundle_sid=self._solution["bundle_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.ItemAssignmentList>" diff --git a/twilio/rest/numbers/v2/regulatory_compliance/bundle/replace_items.py b/twilio/rest/numbers/v2/regulatory_compliance/bundle/replace_items.py new file mode 100644 index 0000000000..a6a1de024d --- /dev/null +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/replace_items.py @@ -0,0 +1,163 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ReplaceItemsInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PENDING_REVIEW = "pending-review" + IN_REVIEW = "in-review" + TWILIO_REJECTED = "twilio-rejected" + TWILIO_APPROVED = "twilio-approved" + PROVISIONALLY_APPROVED = "provisionally-approved" + + """ + :ivar sid: The unique string that we created to identify the Bundle resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Bundle resource. + :ivar regulation_sid: The unique string of a regulation that is associated to the Bundle resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar status: + :ivar valid_until: The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format when the resource will be valid until. + :ivar email: The email address that will receive updates when the Bundle resource changes status. + :ivar status_callback: The URL we call to inform your application of status changes. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], bundle_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.regulation_sid: Optional[str] = payload.get("regulation_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["ReplaceItemsInstance.Status"] = payload.get("status") + self.valid_until: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("valid_until") + ) + self.email: Optional[str] = payload.get("email") + self.status_callback: Optional[str] = payload.get("status_callback") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "bundle_sid": bundle_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.ReplaceItemsInstance {}>".format(context) + + +class ReplaceItemsList(ListResource): + + def __init__(self, version: Version, bundle_sid: str): + """ + Initialize the ReplaceItemsList + + :param version: Version that contains the resource + :param bundle_sid: The unique string that identifies the Bundle where the item assignments are going to be replaced. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + } + self._uri = "/RegulatoryCompliance/Bundles/{bundle_sid}/ReplaceItems".format( + **self._solution + ) + + def create(self, from_bundle_sid: str) -> ReplaceItemsInstance: + """ + Create the ReplaceItemsInstance + + :param from_bundle_sid: The source bundle sid to copy the item assignments from. + + :returns: The created ReplaceItemsInstance + """ + + data = values.of( + { + "FromBundleSid": from_bundle_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ReplaceItemsInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + async def create_async(self, from_bundle_sid: str) -> ReplaceItemsInstance: + """ + Asynchronously create the ReplaceItemsInstance + + :param from_bundle_sid: The source bundle sid to copy the item assignments from. + + :returns: The created ReplaceItemsInstance + """ + + data = values.of( + { + "FromBundleSid": from_bundle_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ReplaceItemsInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.ReplaceItemsList>" diff --git a/twilio/rest/numbers/v2/regulatory_compliance/end_user.py b/twilio/rest/numbers/v2/regulatory_compliance/end_user.py new file mode 100644 index 0000000000..ab1803372a --- /dev/null +++ b/twilio/rest/numbers/v2/regulatory_compliance/end_user.py @@ -0,0 +1,638 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EndUserInstance(InstanceResource): + + class Type(object): + INDIVIDUAL = "individual" + BUSINESS = "business" + + """ + :ivar sid: The unique string created by Twilio to identify the End User resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the End User resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: + :ivar attributes: The set of parameters that are the attributes of the End Users resource which are listed in the End User Types. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the End User resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional["EndUserInstance.Type"] = payload.get("type") + self.attributes: Optional[Dict[str, object]] = payload.get("attributes") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[EndUserContext] = None + + @property + def _proxy(self) -> "EndUserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EndUserContext for this EndUserInstance + """ + if self._context is None: + self._context = EndUserContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the EndUserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EndUserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "EndUserInstance": + """ + Fetch the EndUserInstance + + + :returns: The fetched EndUserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EndUserInstance": + """ + Asynchronous coroutine to fetch the EndUserInstance + + + :returns: The fetched EndUserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "EndUserInstance": + """ + Update the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The updated EndUserInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + attributes=attributes, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "EndUserInstance": + """ + Asynchronous coroutine to update the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The updated EndUserInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + attributes=attributes, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.EndUserInstance {}>".format(context) + + +class EndUserContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the EndUserContext + + :param version: Version that contains the resource + :param sid: The unique string created by Twilio to identify the End User resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/EndUsers/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the EndUserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EndUserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> EndUserInstance: + """ + Fetch the EndUserInstance + + + :returns: The fetched EndUserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EndUserInstance: + """ + Asynchronous coroutine to fetch the EndUserInstance + + + :returns: The fetched EndUserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Update the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The updated EndUserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EndUserInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Asynchronous coroutine to update the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The updated EndUserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EndUserInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.EndUserContext {}>".format(context) + + +class EndUserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EndUserInstance: + """ + Build an instance of EndUserInstance + + :param payload: Payload response from the API + """ + return EndUserInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.EndUserPage>" + + +class EndUserList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the EndUserList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RegulatoryCompliance/EndUsers" + + def create( + self, + friendly_name: str, + type: "EndUserInstance.Type", + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Create the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The created EndUserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EndUserInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + type: "EndUserInstance.Type", + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Asynchronously create the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The created EndUserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EndUserInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EndUserInstance]: + """ + Streams EndUserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EndUserInstance]: + """ + Asynchronously streams EndUserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EndUserInstance]: + """ + Lists EndUserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EndUserInstance]: + """ + Asynchronously lists EndUserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EndUserPage: + """ + Retrieve a single page of EndUserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EndUserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EndUserPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EndUserPage: + """ + Asynchronously retrieve a single page of EndUserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EndUserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EndUserPage(self._version, response) + + def get_page(self, target_url: str) -> EndUserPage: + """ + Retrieve a specific page of EndUserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EndUserInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EndUserPage(self._version, response) + + async def get_page_async(self, target_url: str) -> EndUserPage: + """ + Asynchronously retrieve a specific page of EndUserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EndUserInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EndUserPage(self._version, response) + + def get(self, sid: str) -> EndUserContext: + """ + Constructs a EndUserContext + + :param sid: The unique string created by Twilio to identify the End User resource. + """ + return EndUserContext(self._version, sid=sid) + + def __call__(self, sid: str) -> EndUserContext: + """ + Constructs a EndUserContext + + :param sid: The unique string created by Twilio to identify the End User resource. + """ + return EndUserContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.EndUserList>" diff --git a/twilio/rest/numbers/v2/regulatory_compliance/end_user_type.py b/twilio/rest/numbers/v2/regulatory_compliance/end_user_type.py new file mode 100644 index 0000000000..f14c8905c7 --- /dev/null +++ b/twilio/rest/numbers/v2/regulatory_compliance/end_user_type.py @@ -0,0 +1,408 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EndUserTypeInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies the End-User Type resource. + :ivar friendly_name: A human-readable description that is assigned to describe the End-User Type resource. Examples can include first name, last name, email, business name, etc + :ivar machine_name: A machine-readable description of the End-User Type resource. Examples can include first_name, last_name, email, business_name, etc. + :ivar fields: The required information for creating an End-User. The required fields will change as regulatory needs change and will differ for businesses and individuals. + :ivar url: The absolute URL of the End-User Type resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.machine_name: Optional[str] = payload.get("machine_name") + self.fields: Optional[List[Dict[str, object]]] = payload.get("fields") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[EndUserTypeContext] = None + + @property + def _proxy(self) -> "EndUserTypeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EndUserTypeContext for this EndUserTypeInstance + """ + if self._context is None: + self._context = EndUserTypeContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "EndUserTypeInstance": + """ + Fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EndUserTypeInstance": + """ + Asynchronous coroutine to fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.EndUserTypeInstance {}>".format(context) + + +class EndUserTypeContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the EndUserTypeContext + + :param version: Version that contains the resource + :param sid: The unique string that identifies the End-User Type resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/EndUserTypes/{sid}".format(**self._solution) + + def fetch(self) -> EndUserTypeInstance: + """ + Fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EndUserTypeInstance: + """ + Asynchronous coroutine to fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.EndUserTypeContext {}>".format(context) + + +class EndUserTypePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EndUserTypeInstance: + """ + Build an instance of EndUserTypeInstance + + :param payload: Payload response from the API + """ + return EndUserTypeInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.EndUserTypePage>" + + +class EndUserTypeList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the EndUserTypeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RegulatoryCompliance/EndUserTypes" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EndUserTypeInstance]: + """ + Streams EndUserTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EndUserTypeInstance]: + """ + Asynchronously streams EndUserTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EndUserTypeInstance]: + """ + Lists EndUserTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EndUserTypeInstance]: + """ + Asynchronously lists EndUserTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EndUserTypePage: + """ + Retrieve a single page of EndUserTypeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EndUserTypeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EndUserTypePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EndUserTypePage: + """ + Asynchronously retrieve a single page of EndUserTypeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EndUserTypeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EndUserTypePage(self._version, response) + + def get_page(self, target_url: str) -> EndUserTypePage: + """ + Retrieve a specific page of EndUserTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EndUserTypeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EndUserTypePage(self._version, response) + + async def get_page_async(self, target_url: str) -> EndUserTypePage: + """ + Asynchronously retrieve a specific page of EndUserTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EndUserTypeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EndUserTypePage(self._version, response) + + def get(self, sid: str) -> EndUserTypeContext: + """ + Constructs a EndUserTypeContext + + :param sid: The unique string that identifies the End-User Type resource. + """ + return EndUserTypeContext(self._version, sid=sid) + + def __call__(self, sid: str) -> EndUserTypeContext: + """ + Constructs a EndUserTypeContext + + :param sid: The unique string that identifies the End-User Type resource. + """ + return EndUserTypeContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.EndUserTypeList>" diff --git a/twilio/rest/numbers/v2/regulatory_compliance/regulation.py b/twilio/rest/numbers/v2/regulatory_compliance/regulation.py new file mode 100644 index 0000000000..9c1227905e --- /dev/null +++ b/twilio/rest/numbers/v2/regulatory_compliance/regulation.py @@ -0,0 +1,525 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RegulationInstance(InstanceResource): + + class EndUserType(object): + INDIVIDUAL = "individual" + BUSINESS = "business" + + """ + :ivar sid: The unique string that identifies the Regulation resource. + :ivar friendly_name: A human-readable description that is assigned to describe the Regulation resource. Examples can include Germany: Mobile - Business. + :ivar iso_country: The ISO country code of the phone number's country. + :ivar number_type: The type of phone number restricted by the regulatory requirement. For example, Germany mobile phone numbers provisioned by businesses require a business name with commercial register proof from the Handelsregisterauszug and a proof of address from Handelsregisterauszug or a trade license by Gewerbeanmeldung. + :ivar end_user_type: + :ivar requirements: The SID of an object that holds the regulatory information of the phone number country, phone number type, and end user type. + :ivar url: The absolute URL of the Regulation resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.iso_country: Optional[str] = payload.get("iso_country") + self.number_type: Optional[str] = payload.get("number_type") + self.end_user_type: Optional["RegulationInstance.EndUserType"] = payload.get( + "end_user_type" + ) + self.requirements: Optional[Dict[str, object]] = payload.get("requirements") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[RegulationContext] = None + + @property + def _proxy(self) -> "RegulationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RegulationContext for this RegulationInstance + """ + if self._context is None: + self._context = RegulationContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch( + self, include_constraints: Union[bool, object] = values.unset + ) -> "RegulationInstance": + """ + Fetch the RegulationInstance + + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + + :returns: The fetched RegulationInstance + """ + return self._proxy.fetch( + include_constraints=include_constraints, + ) + + async def fetch_async( + self, include_constraints: Union[bool, object] = values.unset + ) -> "RegulationInstance": + """ + Asynchronous coroutine to fetch the RegulationInstance + + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + + :returns: The fetched RegulationInstance + """ + return await self._proxy.fetch_async( + include_constraints=include_constraints, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.RegulationInstance {}>".format(context) + + +class RegulationContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the RegulationContext + + :param version: Version that contains the resource + :param sid: The unique string that identifies the Regulation resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/Regulations/{sid}".format(**self._solution) + + def fetch( + self, include_constraints: Union[bool, object] = values.unset + ) -> RegulationInstance: + """ + Fetch the RegulationInstance + + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + + :returns: The fetched RegulationInstance + """ + + data = values.of( + { + "IncludeConstraints": serialize.boolean_to_string(include_constraints), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return RegulationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async( + self, include_constraints: Union[bool, object] = values.unset + ) -> RegulationInstance: + """ + Asynchronous coroutine to fetch the RegulationInstance + + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + + :returns: The fetched RegulationInstance + """ + + data = values.of( + { + "IncludeConstraints": serialize.boolean_to_string(include_constraints), + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return RegulationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.RegulationContext {}>".format(context) + + +class RegulationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RegulationInstance: + """ + Build an instance of RegulationInstance + + :param payload: Payload response from the API + """ + return RegulationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.RegulationPage>" + + +class RegulationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RegulationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RegulatoryCompliance/Regulations" + + def stream( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RegulationInstance]: + """ + Streams RegulationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "RegulationInstance.EndUserType" end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param str iso_country: The ISO country code of the phone number's country. + :param str number_type: The type of phone number that the regulatory requiremnt is restricting. + :param bool include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RegulationInstance]: + """ + Asynchronously streams RegulationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "RegulationInstance.EndUserType" end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param str iso_country: The ISO country code of the phone number's country. + :param str number_type: The type of phone number that the regulatory requiremnt is restricting. + :param bool include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RegulationInstance]: + """ + Lists RegulationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RegulationInstance.EndUserType" end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param str iso_country: The ISO country code of the phone number's country. + :param str number_type: The type of phone number that the regulatory requiremnt is restricting. + :param bool include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RegulationInstance]: + """ + Asynchronously lists RegulationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RegulationInstance.EndUserType" end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param str iso_country: The ISO country code of the phone number's country. + :param str number_type: The type of phone number that the regulatory requiremnt is restricting. + :param bool include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + end_user_type=end_user_type, + iso_country=iso_country, + number_type=number_type, + include_constraints=include_constraints, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RegulationPage: + """ + Retrieve a single page of RegulationInstance records from the API. + Request is executed immediately + + :param end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param iso_country: The ISO country code of the phone number's country. + :param number_type: The type of phone number that the regulatory requiremnt is restricting. + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RegulationInstance + """ + data = values.of( + { + "EndUserType": end_user_type, + "IsoCountry": iso_country, + "NumberType": number_type, + "IncludeConstraints": serialize.boolean_to_string(include_constraints), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RegulationPage(self._version, response) + + async def page_async( + self, + end_user_type: Union["RegulationInstance.EndUserType", object] = values.unset, + iso_country: Union[str, object] = values.unset, + number_type: Union[str, object] = values.unset, + include_constraints: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RegulationPage: + """ + Asynchronously retrieve a single page of RegulationInstance records from the API. + Request is executed immediately + + :param end_user_type: The type of End User the regulation requires - can be `individual` or `business`. + :param iso_country: The ISO country code of the phone number's country. + :param number_type: The type of phone number that the regulatory requiremnt is restricting. + :param include_constraints: A boolean parameter indicating whether to include constraints or not for supporting end user, documents and their fields + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RegulationInstance + """ + data = values.of( + { + "EndUserType": end_user_type, + "IsoCountry": iso_country, + "NumberType": number_type, + "IncludeConstraints": serialize.boolean_to_string(include_constraints), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RegulationPage(self._version, response) + + def get_page(self, target_url: str) -> RegulationPage: + """ + Retrieve a specific page of RegulationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RegulationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RegulationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> RegulationPage: + """ + Asynchronously retrieve a specific page of RegulationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RegulationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RegulationPage(self._version, response) + + def get(self, sid: str) -> RegulationContext: + """ + Constructs a RegulationContext + + :param sid: The unique string that identifies the Regulation resource. + """ + return RegulationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> RegulationContext: + """ + Constructs a RegulationContext + + :param sid: The unique string that identifies the Regulation resource. + """ + return RegulationContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.RegulationList>" diff --git a/twilio/rest/numbers/v2/regulatory_compliance/supporting_document.py b/twilio/rest/numbers/v2/regulatory_compliance/supporting_document.py new file mode 100644 index 0000000000..b72f993858 --- /dev/null +++ b/twilio/rest/numbers/v2/regulatory_compliance/supporting_document.py @@ -0,0 +1,658 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SupportingDocumentInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PENDING_REVIEW = "pending-review" + REJECTED = "rejected" + APPROVED = "approved" + EXPIRED = "expired" + PROVISIONALLY_APPROVED = "provisionally-approved" + + """ + :ivar sid: The unique string created by Twilio to identify the Supporting Document resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Document resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar mime_type: The image type uploaded in the Supporting Document container. + :ivar status: + :ivar failure_reason: The failure reason of the Supporting Document Resource. + :ivar errors: A list of errors that occurred during the registering RC Bundle + :ivar type: The type of the Supporting Document. + :ivar attributes: The set of parameters that are the attributes of the Supporting Documents resource which are listed in the Supporting Document Types. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Supporting Document resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.mime_type: Optional[str] = payload.get("mime_type") + self.status: Optional["SupportingDocumentInstance.Status"] = payload.get( + "status" + ) + self.failure_reason: Optional[str] = payload.get("failure_reason") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") + self.type: Optional[str] = payload.get("type") + self.attributes: Optional[Dict[str, object]] = payload.get("attributes") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SupportingDocumentContext] = None + + @property + def _proxy(self) -> "SupportingDocumentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SupportingDocumentContext for this SupportingDocumentInstance + """ + if self._context is None: + self._context = SupportingDocumentContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SupportingDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SupportingDocumentInstance": + """ + Fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SupportingDocumentInstance": + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "SupportingDocumentInstance": + """ + Update the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: The updated SupportingDocumentInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + attributes=attributes, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "SupportingDocumentInstance": + """ + Asynchronous coroutine to update the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: The updated SupportingDocumentInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + attributes=attributes, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.SupportingDocumentInstance {}>".format(context) + + +class SupportingDocumentContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SupportingDocumentContext + + :param version: Version that contains the resource + :param sid: The unique string created by Twilio to identify the Supporting Document resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/SupportingDocuments/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the SupportingDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SupportingDocumentInstance: + """ + Fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SupportingDocumentInstance: + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Update the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: The updated SupportingDocumentInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Asynchronous coroutine to update the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: The updated SupportingDocumentInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.SupportingDocumentContext {}>".format(context) + + +class SupportingDocumentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentInstance: + """ + Build an instance of SupportingDocumentInstance + + :param payload: Payload response from the API + """ + return SupportingDocumentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.SupportingDocumentPage>" + + +class SupportingDocumentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SupportingDocumentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RegulatoryCompliance/SupportingDocuments" + + def create( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Create the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of the Supporting Document. + :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. + + :returns: The created SupportingDocumentInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SupportingDocumentInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Asynchronously create the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of the Supporting Document. + :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. + + :returns: The created SupportingDocumentInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SupportingDocumentInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SupportingDocumentInstance]: + """ + Streams SupportingDocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SupportingDocumentInstance]: + """ + Asynchronously streams SupportingDocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentInstance]: + """ + Lists SupportingDocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentInstance]: + """ + Asynchronously lists SupportingDocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SupportingDocumentPage: + """ + Retrieve a single page of SupportingDocumentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SupportingDocumentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SupportingDocumentPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SupportingDocumentPage: + """ + Asynchronously retrieve a single page of SupportingDocumentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SupportingDocumentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SupportingDocumentPage(self._version, response) + + def get_page(self, target_url: str) -> SupportingDocumentPage: + """ + Retrieve a specific page of SupportingDocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SupportingDocumentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SupportingDocumentPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SupportingDocumentPage: + """ + Asynchronously retrieve a specific page of SupportingDocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SupportingDocumentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SupportingDocumentPage(self._version, response) + + def get(self, sid: str) -> SupportingDocumentContext: + """ + Constructs a SupportingDocumentContext + + :param sid: The unique string created by Twilio to identify the Supporting Document resource. + """ + return SupportingDocumentContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SupportingDocumentContext: + """ + Constructs a SupportingDocumentContext + + :param sid: The unique string created by Twilio to identify the Supporting Document resource. + """ + return SupportingDocumentContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.SupportingDocumentList>" diff --git a/twilio/rest/numbers/v2/regulatory_compliance/supporting_document_type.py b/twilio/rest/numbers/v2/regulatory_compliance/supporting_document_type.py new file mode 100644 index 0000000000..692248cb45 --- /dev/null +++ b/twilio/rest/numbers/v2/regulatory_compliance/supporting_document_type.py @@ -0,0 +1,410 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Numbers + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SupportingDocumentTypeInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies the Supporting Document Type resource. + :ivar friendly_name: A human-readable description of the Supporting Document Type resource. + :ivar machine_name: The machine-readable description of the Supporting Document Type resource. + :ivar fields: The required information for creating a Supporting Document. The required fields will change as regulatory needs change and will differ for businesses and individuals. + :ivar url: The absolute URL of the Supporting Document Type resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.machine_name: Optional[str] = payload.get("machine_name") + self.fields: Optional[List[Dict[str, object]]] = payload.get("fields") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SupportingDocumentTypeContext] = None + + @property + def _proxy(self) -> "SupportingDocumentTypeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SupportingDocumentTypeContext for this SupportingDocumentTypeInstance + """ + if self._context is None: + self._context = SupportingDocumentTypeContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "SupportingDocumentTypeInstance": + """ + Fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SupportingDocumentTypeInstance": + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.SupportingDocumentTypeInstance {}>".format(context) + + +class SupportingDocumentTypeContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SupportingDocumentTypeContext + + :param version: Version that contains the resource + :param sid: The unique string that identifies the Supporting Document Type resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RegulatoryCompliance/SupportingDocumentTypes/{sid}".format( + **self._solution + ) + + def fetch(self) -> SupportingDocumentTypeInstance: + """ + Fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SupportingDocumentTypeInstance: + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Numbers.V2.SupportingDocumentTypeContext {}>".format(context) + + +class SupportingDocumentTypePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentTypeInstance: + """ + Build an instance of SupportingDocumentTypeInstance + + :param payload: Payload response from the API + """ + return SupportingDocumentTypeInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.SupportingDocumentTypePage>" + + +class SupportingDocumentTypeList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SupportingDocumentTypeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RegulatoryCompliance/SupportingDocumentTypes" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SupportingDocumentTypeInstance]: + """ + Streams SupportingDocumentTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SupportingDocumentTypeInstance]: + """ + Asynchronously streams SupportingDocumentTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentTypeInstance]: + """ + Lists SupportingDocumentTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentTypeInstance]: + """ + Asynchronously lists SupportingDocumentTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SupportingDocumentTypePage: + """ + Retrieve a single page of SupportingDocumentTypeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SupportingDocumentTypeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SupportingDocumentTypePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SupportingDocumentTypePage: + """ + Asynchronously retrieve a single page of SupportingDocumentTypeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SupportingDocumentTypeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SupportingDocumentTypePage(self._version, response) + + def get_page(self, target_url: str) -> SupportingDocumentTypePage: + """ + Retrieve a specific page of SupportingDocumentTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SupportingDocumentTypeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SupportingDocumentTypePage(self._version, response) + + async def get_page_async(self, target_url: str) -> SupportingDocumentTypePage: + """ + Asynchronously retrieve a specific page of SupportingDocumentTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SupportingDocumentTypeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SupportingDocumentTypePage(self._version, response) + + def get(self, sid: str) -> SupportingDocumentTypeContext: + """ + Constructs a SupportingDocumentTypeContext + + :param sid: The unique string that identifies the Supporting Document Type resource. + """ + return SupportingDocumentTypeContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SupportingDocumentTypeContext: + """ + Constructs a SupportingDocumentTypeContext + + :param sid: The unique string that identifies the Supporting Document Type resource. + """ + return SupportingDocumentTypeContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Numbers.V2.SupportingDocumentTypeList>" diff --git a/twilio/rest/oauth/OauthBase.py b/twilio/rest/oauth/OauthBase.py new file mode 100644 index 0000000000..87cbbac248 --- /dev/null +++ b/twilio/rest/oauth/OauthBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.oauth.v1 import V1 + + +class OauthBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Oauth Domain + + :returns: Domain for Oauth + """ + super().__init__(twilio, "https://oauth.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Oauth + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Oauth>" diff --git a/twilio/rest/oauth/__init__.py b/twilio/rest/oauth/__init__.py new file mode 100644 index 0000000000..586cf6b4d9 --- /dev/null +++ b/twilio/rest/oauth/__init__.py @@ -0,0 +1,16 @@ +from warnings import warn + +from twilio.rest.oauth.OauthBase import OauthBase +from twilio.rest.oauth.v1.token import TokenList + + +class Oauth(OauthBase): + + @property + def token(self) -> TokenList: + warn( + "token is deprecated. Use v1.token instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.token diff --git a/twilio/rest/oauth/v1/__init__.py b/twilio/rest/oauth/v1/__init__.py new file mode 100644 index 0000000000..e05c7de520 --- /dev/null +++ b/twilio/rest/oauth/v1/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Oauth + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.oauth.v1.authorize import AuthorizeList +from twilio.rest.oauth.v1.token import TokenList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Oauth + + :param domain: The Twilio.oauth domain + """ + super().__init__(domain, "v1") + self._authorize: Optional[AuthorizeList] = None + self._token: Optional[TokenList] = None + + @property + def authorize(self) -> AuthorizeList: + if self._authorize is None: + self._authorize = AuthorizeList(self) + return self._authorize + + @property + def token(self) -> TokenList: + if self._token is None: + self._token = TokenList(self) + return self._token + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Oauth.V1>" diff --git a/twilio/rest/oauth/v1/authorize.py b/twilio/rest/oauth/v1/authorize.py new file mode 100644 index 0000000000..a353c4b8e0 --- /dev/null +++ b/twilio/rest/oauth/v1/authorize.py @@ -0,0 +1,130 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Oauth + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class AuthorizeInstance(InstanceResource): + """ + :ivar redirect_to: The callback URL + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.redirect_to: Optional[str] = payload.get("redirect_to") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Oauth.V1.AuthorizeInstance>" + + +class AuthorizeList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AuthorizeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/authorize" + + def fetch( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> AuthorizeInstance: + """ + Asynchronously fetch the AuthorizeInstance + + :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback + :returns: The fetched AuthorizeInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "ResponseType": response_type, + "ClientId": client_id, + "RedirectUri": redirect_uri, + "Scope": scope, + "State": state, + } + ) + + payload = self._version.fetch( + method="GET", uri=self._uri, headers=headers, params=params + ) + + return AuthorizeInstance(self._version, payload) + + async def fetch_async( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> AuthorizeInstance: + """ + Asynchronously fetch the AuthorizeInstance + + :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback + :returns: The fetched AuthorizeInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "ResponseType": response_type, + "ClientId": client_id, + "RedirectUri": redirect_uri, + "Scope": scope, + "State": state, + } + ) + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + return AuthorizeInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Oauth.V1.AuthorizeList>" diff --git a/twilio/rest/oauth/v1/token.py b/twilio/rest/oauth/v1/token.py new file mode 100644 index 0000000000..18de1008cb --- /dev/null +++ b/twilio/rest/oauth/v1/token.py @@ -0,0 +1,170 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Oauth + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TokenInstance(InstanceResource): + """ + :ivar access_token: Token which carries the necessary information to access a Twilio resource directly. + :ivar refresh_token: Token which carries the information necessary to get a new access token. + :ivar id_token: Token which carries the information necessary of user profile. + :ivar token_type: Token type + :ivar expires_in: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.access_token: Optional[str] = payload.get("access_token") + self.refresh_token: Optional[str] = payload.get("refresh_token") + self.id_token: Optional[str] = payload.get("id_token") + self.token_type: Optional[str] = payload.get("token_type") + self.expires_in: Optional[int] = payload.get("expires_in") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Oauth.V1.TokenInstance>" + + +class TokenList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TokenList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/token" + + def create( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Create the TokenInstance + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: The created TokenInstance + """ + + data = values.of( + { + "GrantType": grant_type, + "ClientId": client_id, + "ClientSecret": client_secret, + "Code": code, + "RedirectUri": redirect_uri, + "Audience": audience, + "RefreshToken": refresh_token, + "Scope": scope, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TokenInstance(self._version, payload) + + async def create_async( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Asynchronously create the TokenInstance + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: The created TokenInstance + """ + + data = values.of( + { + "GrantType": grant_type, + "ClientId": client_id, + "ClientSecret": client_secret, + "Code": code, + "RedirectUri": redirect_uri, + "Audience": audience, + "RefreshToken": refresh_token, + "Scope": scope, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TokenInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Oauth.V1.TokenList>" diff --git a/twilio/rest/preview/PreviewBase.py b/twilio/rest/preview/PreviewBase.py new file mode 100644 index 0000000000..dd8317b4c0 --- /dev/null +++ b/twilio/rest/preview/PreviewBase.py @@ -0,0 +1,66 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.preview.hosted_numbers import HostedNumbers +from twilio.rest.preview.marketplace import Marketplace +from twilio.rest.preview.wireless import Wireless + + +class PreviewBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Preview Domain + + :returns: Domain for Preview + """ + super().__init__(twilio, "https://preview.twilio.com") + self._hosted_numbers: Optional[HostedNumbers] = None + self._marketplace: Optional[Marketplace] = None + self._wireless: Optional[Wireless] = None + + @property + def hosted_numbers(self) -> HostedNumbers: + """ + :returns: Versions hosted_numbers of Preview + """ + if self._hosted_numbers is None: + self._hosted_numbers = HostedNumbers(self) + return self._hosted_numbers + + @property + def marketplace(self) -> Marketplace: + """ + :returns: Versions marketplace of Preview + """ + if self._marketplace is None: + self._marketplace = Marketplace(self) + return self._marketplace + + @property + def wireless(self) -> Wireless: + """ + :returns: Versions wireless of Preview + """ + if self._wireless is None: + self._wireless = Wireless(self) + return self._wireless + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Preview>" diff --git a/twilio/rest/preview/__init__.py b/twilio/rest/preview/__init__.py new file mode 100644 index 0000000000..501ae417d0 --- /dev/null +++ b/twilio/rest/preview/__init__.py @@ -0,0 +1,88 @@ +from warnings import warn + +from twilio.rest.preview.PreviewBase import PreviewBase +from twilio.rest.preview.hosted_numbers.authorization_document import ( + AuthorizationDocumentList, +) +from twilio.rest.preview.hosted_numbers.hosted_number_order import HostedNumberOrderList +from twilio.rest.preview.marketplace.available_add_on import AvailableAddOnList +from twilio.rest.preview.marketplace.installed_add_on import InstalledAddOnList +from twilio.rest.preview.sync.service import ServiceList +from twilio.rest.preview.wireless.command import CommandList +from twilio.rest.preview.wireless.rate_plan import RatePlanList +from twilio.rest.preview.wireless.sim import SimList + + +class Preview(PreviewBase): + + @property + def authorization_documents(self) -> AuthorizationDocumentList: + warn( + "authorization_documents is deprecated. Use hosted_numbers.authorization_documents instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.hosted_numbers.authorization_documents + + @property + def hosted_number_orders(self) -> HostedNumberOrderList: + warn( + "hosted_number_orders is deprecated. Use hosted_numbers.hosted_number_orders instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.hosted_numbers.hosted_number_orders + + @property + def available_add_ons(self) -> AvailableAddOnList: + warn( + "available_add_ons is deprecated. Use marketplace.available_add_ons instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.marketplace.available_add_ons + + @property + def installed_add_ons(self) -> InstalledAddOnList: + warn( + "installed_add_ons is deprecated. Use marketplace.installed_add_ons instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.marketplace.installed_add_ons + + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use sync.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.sync.services + + @property + def commands(self) -> CommandList: + warn( + "commands is deprecated. Use wireless.commands instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.wireless.commands + + @property + def rate_plans(self) -> RatePlanList: + warn( + "rate_plans is deprecated. Use wireless.rate_plans instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.wireless.rate_plans + + @property + def sims(self) -> SimList: + warn( + "sims is deprecated. Use wireless.sims instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.wireless.sims diff --git a/twilio/rest/preview/hosted_numbers/__init__.py b/twilio/rest/preview/hosted_numbers/__init__.py new file mode 100644 index 0000000000..7b3a767eef --- /dev/null +++ b/twilio/rest/preview/hosted_numbers/__init__.py @@ -0,0 +1,53 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.preview.hosted_numbers.authorization_document import ( + AuthorizationDocumentList, +) +from twilio.rest.preview.hosted_numbers.hosted_number_order import HostedNumberOrderList + + +class HostedNumbers(Version): + + def __init__(self, domain: Domain): + """ + Initialize the HostedNumbers version of Preview + + :param domain: The Twilio.preview domain + """ + super().__init__(domain, "HostedNumbers") + self._authorization_documents: Optional[AuthorizationDocumentList] = None + self._hosted_number_orders: Optional[HostedNumberOrderList] = None + + @property + def authorization_documents(self) -> AuthorizationDocumentList: + if self._authorization_documents is None: + self._authorization_documents = AuthorizationDocumentList(self) + return self._authorization_documents + + @property + def hosted_number_orders(self) -> HostedNumberOrderList: + if self._hosted_number_orders is None: + self._hosted_number_orders = HostedNumberOrderList(self) + return self._hosted_number_orders + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Preview.HostedNumbers>" diff --git a/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py b/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py new file mode 100644 index 0000000000..49d3d40da5 --- /dev/null +++ b/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py @@ -0,0 +1,755 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.preview.hosted_numbers.authorization_document.dependent_hosted_number_order import ( + DependentHostedNumberOrderList, +) + + +class AuthorizationDocumentInstance(InstanceResource): + + class Status(object): + OPENED = "opened" + SIGNING = "signing" + SIGNED = "signed" + CANCELED = "canceled" + FAILED = "failed" + + """ + :ivar sid: A 34 character string that uniquely identifies this AuthorizationDocument. + :ivar address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :ivar status: + :ivar email: Email that this AuthorizationDocument will be sent to for signing. + :ivar cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + :ivar date_created: The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.address_sid: Optional[str] = payload.get("address_sid") + self.status: Optional["AuthorizationDocumentInstance.Status"] = payload.get( + "status" + ) + self.email: Optional[str] = payload.get("email") + self.cc_emails: Optional[List[str]] = payload.get("cc_emails") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AuthorizationDocumentContext] = None + + @property + def _proxy(self) -> "AuthorizationDocumentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AuthorizationDocumentContext for this AuthorizationDocumentInstance + """ + if self._context is None: + self._context = AuthorizationDocumentContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AuthorizationDocumentInstance": + """ + Fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AuthorizationDocumentInstance": + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + hosted_number_order_sids: Union[List[str], object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + contact_title: Union[str, object] = values.unset, + contact_phone_number: Union[str, object] = values.unset, + ) -> "AuthorizationDocumentInstance": + """ + Update the AuthorizationDocumentInstance + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :param status: + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + + :returns: The updated AuthorizationDocumentInstance + """ + return self._proxy.update( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + cc_emails=cc_emails, + status=status, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + ) + + async def update_async( + self, + hosted_number_order_sids: Union[List[str], object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + contact_title: Union[str, object] = values.unset, + contact_phone_number: Union[str, object] = values.unset, + ) -> "AuthorizationDocumentInstance": + """ + Asynchronous coroutine to update the AuthorizationDocumentInstance + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :param status: + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + + :returns: The updated AuthorizationDocumentInstance + """ + return await self._proxy.update_async( + hosted_number_order_sids=hosted_number_order_sids, + address_sid=address_sid, + email=email, + cc_emails=cc_emails, + status=status, + contact_title=contact_title, + contact_phone_number=contact_phone_number, + ) + + @property + def dependent_hosted_number_orders(self) -> DependentHostedNumberOrderList: + """ + Access the dependent_hosted_number_orders + """ + return self._proxy.dependent_hosted_number_orders + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.HostedNumbers.AuthorizationDocumentInstance {}>".format( + context + ) + + +class AuthorizationDocumentContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the AuthorizationDocumentContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/AuthorizationDocuments/{sid}".format(**self._solution) + + self._dependent_hosted_number_orders: Optional[ + DependentHostedNumberOrderList + ] = None + + def fetch(self) -> AuthorizationDocumentInstance: + """ + Fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AuthorizationDocumentInstance: + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + hosted_number_order_sids: Union[List[str], object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + contact_title: Union[str, object] = values.unset, + contact_phone_number: Union[str, object] = values.unset, + ) -> AuthorizationDocumentInstance: + """ + Update the AuthorizationDocumentInstance + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :param status: + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + + :returns: The updated AuthorizationDocumentInstance + """ + + data = values.of( + { + "HostedNumberOrderSids": serialize.map( + hosted_number_order_sids, lambda e: e + ), + "AddressSid": address_sid, + "Email": email, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "Status": status, + "ContactTitle": contact_title, + "ContactPhoneNumber": contact_phone_number, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthorizationDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, + hosted_number_order_sids: Union[List[str], object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + contact_title: Union[str, object] = values.unset, + contact_phone_number: Union[str, object] = values.unset, + ) -> AuthorizationDocumentInstance: + """ + Asynchronous coroutine to update the AuthorizationDocumentInstance + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :param status: + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + + :returns: The updated AuthorizationDocumentInstance + """ + + data = values.of( + { + "HostedNumberOrderSids": serialize.map( + hosted_number_order_sids, lambda e: e + ), + "AddressSid": address_sid, + "Email": email, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "Status": status, + "ContactTitle": contact_title, + "ContactPhoneNumber": contact_phone_number, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthorizationDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + + @property + def dependent_hosted_number_orders(self) -> DependentHostedNumberOrderList: + """ + Access the dependent_hosted_number_orders + """ + if self._dependent_hosted_number_orders is None: + self._dependent_hosted_number_orders = DependentHostedNumberOrderList( + self._version, + self._solution["sid"], + ) + return self._dependent_hosted_number_orders + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.HostedNumbers.AuthorizationDocumentContext {}>".format( + context + ) + + +class AuthorizationDocumentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AuthorizationDocumentInstance: + """ + Build an instance of AuthorizationDocumentInstance + + :param payload: Payload response from the API + """ + return AuthorizationDocumentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.HostedNumbers.AuthorizationDocumentPage>" + + +class AuthorizationDocumentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AuthorizationDocumentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/AuthorizationDocuments" + + def create( + self, + hosted_number_order_sids: List[str], + address_sid: str, + email: str, + contact_title: str, + contact_phone_number: str, + cc_emails: Union[List[str], object] = values.unset, + ) -> AuthorizationDocumentInstance: + """ + Create the AuthorizationDocumentInstance + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + + :returns: The created AuthorizationDocumentInstance + """ + + data = values.of( + { + "HostedNumberOrderSids": serialize.map( + hosted_number_order_sids, lambda e: e + ), + "AddressSid": address_sid, + "Email": email, + "ContactTitle": contact_title, + "ContactPhoneNumber": contact_phone_number, + "CcEmails": serialize.map(cc_emails, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthorizationDocumentInstance(self._version, payload) + + async def create_async( + self, + hosted_number_order_sids: List[str], + address_sid: str, + email: str, + contact_title: str, + contact_phone_number: str, + cc_emails: Union[List[str], object] = values.unset, + ) -> AuthorizationDocumentInstance: + """ + Asynchronously create the AuthorizationDocumentInstance + + :param hosted_number_order_sids: A list of HostedNumberOrder sids that this AuthorizationDocument will authorize for hosting phone number capabilities on Twilio's platform. + :param address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :param contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :param cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + + :returns: The created AuthorizationDocumentInstance + """ + + data = values.of( + { + "HostedNumberOrderSids": serialize.map( + hosted_number_order_sids, lambda e: e + ), + "AddressSid": address_sid, + "Email": email, + "ContactTitle": contact_title, + "ContactPhoneNumber": contact_phone_number, + "CcEmails": serialize.map(cc_emails, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AuthorizationDocumentInstance(self._version, payload) + + def stream( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AuthorizationDocumentInstance]: + """ + Streams AuthorizationDocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(email=email, status=status, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AuthorizationDocumentInstance]: + """ + Asynchronously streams AuthorizationDocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + email=email, status=status, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthorizationDocumentInstance]: + """ + Lists AuthorizationDocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + email=email, + status=status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthorizationDocumentInstance]: + """ + Asynchronously lists AuthorizationDocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str email: Email that this AuthorizationDocument will be sent to for signing. + :param "AuthorizationDocumentInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + email=email, + status=status, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthorizationDocumentPage: + """ + Retrieve a single page of AuthorizationDocumentInstance records from the API. + Request is executed immediately + + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthorizationDocumentInstance + """ + data = values.of( + { + "Email": email, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthorizationDocumentPage(self._version, response) + + async def page_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AuthorizationDocumentPage: + """ + Asynchronously retrieve a single page of AuthorizationDocumentInstance records from the API. + Request is executed immediately + + :param email: Email that this AuthorizationDocument will be sent to for signing. + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AuthorizationDocumentInstance + """ + data = values.of( + { + "Email": email, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthorizationDocumentPage(self._version, response) + + def get_page(self, target_url: str) -> AuthorizationDocumentPage: + """ + Retrieve a specific page of AuthorizationDocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthorizationDocumentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AuthorizationDocumentPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AuthorizationDocumentPage: + """ + Asynchronously retrieve a specific page of AuthorizationDocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthorizationDocumentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AuthorizationDocumentPage(self._version, response) + + def get(self, sid: str) -> AuthorizationDocumentContext: + """ + Constructs a AuthorizationDocumentContext + + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. + """ + return AuthorizationDocumentContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AuthorizationDocumentContext: + """ + Constructs a AuthorizationDocumentContext + + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. + """ + return AuthorizationDocumentContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.HostedNumbers.AuthorizationDocumentList>" diff --git a/twilio/rest/preview/hosted_numbers/authorization_document/dependent_hosted_number_order.py b/twilio/rest/preview/hosted_numbers/authorization_document/dependent_hosted_number_order.py new file mode 100644 index 0000000000..0ec58f8792 --- /dev/null +++ b/twilio/rest/preview/hosted_numbers/authorization_document/dependent_hosted_number_order.py @@ -0,0 +1,477 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DependentHostedNumberOrderInstance(InstanceResource): + + class Status(object): + RECEIVED = "received" + PENDING_VERIFICATION = "pending-verification" + VERIFIED = "verified" + PENDING_LOA = "pending-loa" + CARRIER_PROCESSING = "carrier-processing" + TESTING = "testing" + COMPLETED = "completed" + FAILED = "failed" + ACTION_REQUIRED = "action-required" + + class VerificationType(object): + PHONE_CALL = "phone-call" + PHONE_BILL = "phone-bill" + + """ + :ivar sid: A 34 character string that uniquely identifies this Authorization Document + :ivar account_sid: The unique SID identifier of the Account. + :ivar incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :ivar address_sid: A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :ivar signing_document_sid: A 34 character string that uniquely identifies the LOA document associated with this HostedNumberOrder. + :ivar phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :ivar capabilities: + :ivar friendly_name: A human readable description of this resource, up to 64 characters. + :ivar unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :ivar status: + :ivar failure_reason: A message that explains why a hosted_number_order went to status \"action-required\" + :ivar date_created: The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar verification_attempts: The number of attempts made to verify ownership of the phone number that is being hosted. + :ivar email: Email of the owner of this phone number that is being hosted. + :ivar cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :ivar verification_type: + :ivar verification_document_sid: A 34 character string that uniquely identifies the Identity Document resource that represents the document for verifying ownership of the number to be hosted. + :ivar extension: A numerical extension to be used when making the ownership verification call. + :ivar call_delay: A value between 0-30 specifying the number of seconds to delay initiating the ownership verification call. + :ivar verification_code: The digits passed during the ownership verification call. + :ivar verification_call_sids: A list of 34 character strings that are unique identifiers for the calls placed as part of ownership verification. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], signing_document_sid: str + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.incoming_phone_number_sid: Optional[str] = payload.get( + "incoming_phone_number_sid" + ) + self.address_sid: Optional[str] = payload.get("address_sid") + self.signing_document_sid: Optional[str] = payload.get("signing_document_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.capabilities: Optional[str] = payload.get("capabilities") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.status: Optional["DependentHostedNumberOrderInstance.Status"] = ( + payload.get("status") + ) + self.failure_reason: Optional[str] = payload.get("failure_reason") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.verification_attempts: Optional[int] = deserialize.integer( + payload.get("verification_attempts") + ) + self.email: Optional[str] = payload.get("email") + self.cc_emails: Optional[List[str]] = payload.get("cc_emails") + self.verification_type: Optional[ + "DependentHostedNumberOrderInstance.VerificationType" + ] = payload.get("verification_type") + self.verification_document_sid: Optional[str] = payload.get( + "verification_document_sid" + ) + self.extension: Optional[str] = payload.get("extension") + self.call_delay: Optional[int] = deserialize.integer(payload.get("call_delay")) + self.verification_code: Optional[str] = payload.get("verification_code") + self.verification_call_sids: Optional[List[str]] = payload.get( + "verification_call_sids" + ) + + self._solution = { + "signing_document_sid": signing_document_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.HostedNumbers.DependentHostedNumberOrderInstance {}>".format( + context + ) + + +class DependentHostedNumberOrderPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> DependentHostedNumberOrderInstance: + """ + Build an instance of DependentHostedNumberOrderInstance + + :param payload: Payload response from the API + """ + return DependentHostedNumberOrderInstance( + self._version, + payload, + signing_document_sid=self._solution["signing_document_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.HostedNumbers.DependentHostedNumberOrderPage>" + + +class DependentHostedNumberOrderList(ListResource): + + def __init__(self, version: Version, signing_document_sid: str): + """ + Initialize the DependentHostedNumberOrderList + + :param version: Version that contains the resource + :param signing_document_sid: A 34 character string that uniquely identifies the LOA document associated with this HostedNumberOrder. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "signing_document_sid": signing_document_sid, + } + self._uri = "/AuthorizationDocuments/{signing_document_sid}/DependentHostedNumberOrders".format( + **self._solution + ) + + def stream( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DependentHostedNumberOrderInstance]: + """ + Streams DependentHostedNumberOrderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DependentHostedNumberOrderInstance]: + """ + Asynchronously streams DependentHostedNumberOrderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DependentHostedNumberOrderInstance]: + """ + Lists DependentHostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DependentHostedNumberOrderInstance]: + """ + Asynchronously lists DependentHostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "DependentHostedNumberOrderInstance.Status" status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DependentHostedNumberOrderPage: + """ + Retrieve a single page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately + + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DependentHostedNumberOrderInstance + """ + data = values.of( + { + "Status": status, + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentHostedNumberOrderPage(self._version, response, self._solution) + + async def page_async( + self, + status: Union[ + "DependentHostedNumberOrderInstance.Status", object + ] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DependentHostedNumberOrderPage: + """ + Asynchronously retrieve a single page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately + + :param status: Status of an instance resource. It can hold one of the values: 1. opened 2. signing, 3. signed LOA, 4. canceled, 5. failed. See the section entitled [Status Values](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource#status-values) for more information on each of these statuses. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DependentHostedNumberOrderInstance + """ + data = values.of( + { + "Status": status, + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentHostedNumberOrderPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DependentHostedNumberOrderPage: + """ + Retrieve a specific page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DependentHostedNumberOrderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DependentHostedNumberOrderPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DependentHostedNumberOrderPage: + """ + Asynchronously retrieve a specific page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DependentHostedNumberOrderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DependentHostedNumberOrderPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.HostedNumbers.DependentHostedNumberOrderList>" diff --git a/twilio/rest/preview/hosted_numbers/hosted_number_order.py b/twilio/rest/preview/hosted_numbers/hosted_number_order.py new file mode 100644 index 0000000000..0c20af8791 --- /dev/null +++ b/twilio/rest/preview/hosted_numbers/hosted_number_order.py @@ -0,0 +1,985 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class HostedNumberOrderInstance(InstanceResource): + + class Status(object): + RECEIVED = "received" + PENDING_VERIFICATION = "pending-verification" + VERIFIED = "verified" + PENDING_LOA = "pending-loa" + CARRIER_PROCESSING = "carrier-processing" + TESTING = "testing" + COMPLETED = "completed" + FAILED = "failed" + ACTION_REQUIRED = "action-required" + + class VerificationType(object): + PHONE_CALL = "phone-call" + PHONE_BILL = "phone-bill" + + """ + :ivar sid: A 34 character string that uniquely identifies this HostedNumberOrder. + :ivar account_sid: A 34 character string that uniquely identifies the account. + :ivar incoming_phone_number_sid: A 34 character string that uniquely identifies the [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the phone number being hosted. + :ivar address_sid: A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :ivar signing_document_sid: A 34 character string that uniquely identifies the [Authorization Document](https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/authorization-document-resource) the user needs to sign. + :ivar phone_number: Phone number to be hosted. This must be in [E.164](https://en.wikipedia.org/wiki/E.164) format, e.g., +16175551212 + :ivar capabilities: + :ivar friendly_name: A 64 character string that is a human-readable text that describes this resource. + :ivar unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :ivar status: + :ivar failure_reason: A message that explains why a hosted_number_order went to status \"action-required\" + :ivar date_created: The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date that this resource was updated, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar verification_attempts: The number of attempts made to verify ownership of the phone number that is being hosted. + :ivar email: Email of the owner of this phone number that is being hosted. + :ivar cc_emails: A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :ivar url: The URL of this HostedNumberOrder. + :ivar verification_type: + :ivar verification_document_sid: A 34 character string that uniquely identifies the Identity Document resource that represents the document for verifying ownership of the number to be hosted. + :ivar extension: A numerical extension to be used when making the ownership verification call. + :ivar call_delay: A value between 0-30 specifying the number of seconds to delay initiating the ownership verification call. + :ivar verification_code: A verification code provided in the response for a user to enter when they pick up the phone call. + :ivar verification_call_sids: A list of 34 character strings that are unique identifiers for the calls placed as part of ownership verification. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.incoming_phone_number_sid: Optional[str] = payload.get( + "incoming_phone_number_sid" + ) + self.address_sid: Optional[str] = payload.get("address_sid") + self.signing_document_sid: Optional[str] = payload.get("signing_document_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.capabilities: Optional[str] = payload.get("capabilities") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.status: Optional["HostedNumberOrderInstance.Status"] = payload.get( + "status" + ) + self.failure_reason: Optional[str] = payload.get("failure_reason") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.verification_attempts: Optional[int] = deserialize.integer( + payload.get("verification_attempts") + ) + self.email: Optional[str] = payload.get("email") + self.cc_emails: Optional[List[str]] = payload.get("cc_emails") + self.url: Optional[str] = payload.get("url") + self.verification_type: Optional[ + "HostedNumberOrderInstance.VerificationType" + ] = payload.get("verification_type") + self.verification_document_sid: Optional[str] = payload.get( + "verification_document_sid" + ) + self.extension: Optional[str] = payload.get("extension") + self.call_delay: Optional[int] = deserialize.integer(payload.get("call_delay")) + self.verification_code: Optional[str] = payload.get("verification_code") + self.verification_call_sids: Optional[List[str]] = payload.get( + "verification_call_sids" + ) + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[HostedNumberOrderContext] = None + + @property + def _proxy(self) -> "HostedNumberOrderContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: HostedNumberOrderContext for this HostedNumberOrderInstance + """ + if self._context is None: + self._context = HostedNumberOrderContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the HostedNumberOrderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the HostedNumberOrderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "HostedNumberOrderInstance": + """ + Fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "HostedNumberOrderInstance": + """ + Asynchronous coroutine to fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + verification_code: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + extension: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + ) -> "HostedNumberOrderInstance": + """ + Update the HostedNumberOrderInstance + + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param email: Email of the owner of this phone number that is being hosted. + :param cc_emails: Optional. A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :param status: + :param verification_code: A verification code that is given to the user via a phone call to the phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + :param extension: Digits to dial after connecting the verification call. + :param call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. + + :returns: The updated HostedNumberOrderInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + unique_name=unique_name, + email=email, + cc_emails=cc_emails, + status=status, + verification_code=verification_code, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + extension=extension, + call_delay=call_delay, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + verification_code: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + extension: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + ) -> "HostedNumberOrderInstance": + """ + Asynchronous coroutine to update the HostedNumberOrderInstance + + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param email: Email of the owner of this phone number that is being hosted. + :param cc_emails: Optional. A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :param status: + :param verification_code: A verification code that is given to the user via a phone call to the phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + :param extension: Digits to dial after connecting the verification call. + :param call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. + + :returns: The updated HostedNumberOrderInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + unique_name=unique_name, + email=email, + cc_emails=cc_emails, + status=status, + verification_code=verification_code, + verification_type=verification_type, + verification_document_sid=verification_document_sid, + extension=extension, + call_delay=call_delay, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.HostedNumbers.HostedNumberOrderInstance {}>".format( + context + ) + + +class HostedNumberOrderContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the HostedNumberOrderContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this HostedNumberOrder. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/HostedNumberOrders/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the HostedNumberOrderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the HostedNumberOrderInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> HostedNumberOrderInstance: + """ + Fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> HostedNumberOrderInstance: + """ + Asynchronous coroutine to fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + verification_code: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + extension: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Update the HostedNumberOrderInstance + + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param email: Email of the owner of this phone number that is being hosted. + :param cc_emails: Optional. A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :param status: + :param verification_code: A verification code that is given to the user via a phone call to the phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + :param extension: Digits to dial after connecting the verification call. + :param call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. + + :returns: The updated HostedNumberOrderInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Email": email, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "Status": status, + "VerificationCode": verification_code, + "VerificationType": verification_type, + "VerificationDocumentSid": verification_document_sid, + "Extension": extension, + "CallDelay": call_delay, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + verification_code: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + extension: Union[str, object] = values.unset, + call_delay: Union[int, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Asynchronous coroutine to update the HostedNumberOrderInstance + + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param email: Email of the owner of this phone number that is being hosted. + :param cc_emails: Optional. A list of emails that LOA document for this HostedNumberOrder will be carbon copied to. + :param status: + :param verification_code: A verification code that is given to the user via a phone call to the phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + :param extension: Digits to dial after connecting the verification call. + :param call_delay: The number of seconds, between 0 and 60, to delay before initiating the verification call. Defaults to 0. + + :returns: The updated HostedNumberOrderInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Email": email, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "Status": status, + "VerificationCode": verification_code, + "VerificationType": verification_type, + "VerificationDocumentSid": verification_document_sid, + "Extension": extension, + "CallDelay": call_delay, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return HostedNumberOrderInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.HostedNumbers.HostedNumberOrderContext {}>".format( + context + ) + + +class HostedNumberOrderPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> HostedNumberOrderInstance: + """ + Build an instance of HostedNumberOrderInstance + + :param payload: Payload response from the API + """ + return HostedNumberOrderInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.HostedNumbers.HostedNumberOrderPage>" + + +class HostedNumberOrderList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the HostedNumberOrderList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/HostedNumberOrders" + + def create( + self, + phone_number: str, + sms_capability: bool, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Create the HostedNumberOrderInstance + + :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format + :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. + :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Optional. Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. + :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. + :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. + :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. + :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. + :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :param email: Optional. Email of the owner of this phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + + :returns: The created HostedNumberOrderInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "SmsCapability": serialize.boolean_to_string(sms_capability), + "AccountSid": account_sid, + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "SmsApplicationSid": sms_application_sid, + "AddressSid": address_sid, + "Email": email, + "VerificationType": verification_type, + "VerificationDocumentSid": verification_document_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return HostedNumberOrderInstance(self._version, payload) + + async def create_async( + self, + phone_number: str, + sms_capability: bool, + account_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + cc_emails: Union[List[str], object] = values.unset, + sms_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + sms_application_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + verification_type: Union[ + "HostedNumberOrderInstance.VerificationType", object + ] = values.unset, + verification_document_sid: Union[str, object] = values.unset, + ) -> HostedNumberOrderInstance: + """ + Asynchronously create the HostedNumberOrderInstance + + :param phone_number: The number to host in [+E.164](https://en.wikipedia.org/wiki/E.164) format + :param sms_capability: Used to specify that the SMS capability will be hosted on Twilio's platform. + :param account_sid: This defaults to the AccountSid of the authorization the user is using. This can be provided to specify a subaccount to add the HostedNumberOrder to. + :param friendly_name: A 64 character string that is a human readable text that describes this resource. + :param unique_name: Optional. Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param cc_emails: Optional. A list of emails that the LOA document for this HostedNumberOrder will be carbon copied to. + :param sms_url: The URL that Twilio should request when somebody sends an SMS to the phone number. This will be copied onto the IncomingPhoneNumber resource. + :param sms_method: The HTTP method that should be used to request the SmsUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_url: A URL that Twilio will request if an error occurs requesting or executing the TwiML defined by SmsUrl. This will be copied onto the IncomingPhoneNumber resource. + :param sms_fallback_method: The HTTP method that should be used to request the SmsFallbackUrl. Must be either `GET` or `POST`. This will be copied onto the IncomingPhoneNumber resource. + :param status_callback_url: Optional. The Status Callback URL attached to the IncomingPhoneNumber resource. + :param status_callback_method: Optional. The Status Callback Method attached to the IncomingPhoneNumber resource. + :param sms_application_sid: Optional. The 34 character sid of the application Twilio should use to handle SMS messages sent to this number. If a `SmsApplicationSid` is present, Twilio will ignore all of the SMS urls above and use those set on the application. + :param address_sid: Optional. A 34 character string that uniquely identifies the Address resource that represents the address of the owner of this phone number. + :param email: Optional. Email of the owner of this phone number that is being hosted. + :param verification_type: + :param verification_document_sid: Optional. The unique sid identifier of the Identity Document that represents the document for verifying ownership of the number to be hosted. Required when VerificationType is phone-bill. + + :returns: The created HostedNumberOrderInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "SmsCapability": serialize.boolean_to_string(sms_capability), + "AccountSid": account_sid, + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "CcEmails": serialize.map(cc_emails, lambda e: e), + "SmsUrl": sms_url, + "SmsMethod": sms_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsFallbackMethod": sms_fallback_method, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "SmsApplicationSid": sms_application_sid, + "AddressSid": address_sid, + "Email": email, + "VerificationType": verification_type, + "VerificationDocumentSid": verification_document_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return HostedNumberOrderInstance(self._version, payload) + + def stream( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[HostedNumberOrderInstance]: + """ + Streams HostedNumberOrderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[HostedNumberOrderInstance]: + """ + Asynchronously streams HostedNumberOrderInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[HostedNumberOrderInstance]: + """ + Lists HostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[HostedNumberOrderInstance]: + """ + Asynchronously lists HostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "HostedNumberOrderInstance.Status" status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param str phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param str incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param str friendly_name: A human readable description of this resource, up to 64 characters. + :param str unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + unique_name=unique_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> HostedNumberOrderPage: + """ + Retrieve a single page of HostedNumberOrderInstance records from the API. + Request is executed immediately + + :param status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of HostedNumberOrderInstance + """ + data = values.of( + { + "Status": status, + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return HostedNumberOrderPage(self._version, response) + + async def page_async( + self, + status: Union["HostedNumberOrderInstance.Status", object] = values.unset, + phone_number: Union[str, object] = values.unset, + incoming_phone_number_sid: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + unique_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> HostedNumberOrderPage: + """ + Asynchronously retrieve a single page of HostedNumberOrderInstance records from the API. + Request is executed immediately + + :param status: The Status of this HostedNumberOrder. One of `received`, `pending-verification`, `verified`, `pending-loa`, `carrier-processing`, `testing`, `completed`, `failed`, or `action-required`. + :param phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :param incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :param friendly_name: A human readable description of this resource, up to 64 characters. + :param unique_name: Provides a unique and addressable name to be assigned to this HostedNumberOrder, assigned by the developer, to be optionally used in addition to SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of HostedNumberOrderInstance + """ + data = values.of( + { + "Status": status, + "PhoneNumber": phone_number, + "IncomingPhoneNumberSid": incoming_phone_number_sid, + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return HostedNumberOrderPage(self._version, response) + + def get_page(self, target_url: str) -> HostedNumberOrderPage: + """ + Retrieve a specific page of HostedNumberOrderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of HostedNumberOrderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return HostedNumberOrderPage(self._version, response) + + async def get_page_async(self, target_url: str) -> HostedNumberOrderPage: + """ + Asynchronously retrieve a specific page of HostedNumberOrderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of HostedNumberOrderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return HostedNumberOrderPage(self._version, response) + + def get(self, sid: str) -> HostedNumberOrderContext: + """ + Constructs a HostedNumberOrderContext + + :param sid: A 34 character string that uniquely identifies this HostedNumberOrder. + """ + return HostedNumberOrderContext(self._version, sid=sid) + + def __call__(self, sid: str) -> HostedNumberOrderContext: + """ + Constructs a HostedNumberOrderContext + + :param sid: A 34 character string that uniquely identifies this HostedNumberOrder. + """ + return HostedNumberOrderContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.HostedNumbers.HostedNumberOrderList>" diff --git a/twilio/rest/preview/marketplace/__init__.py b/twilio/rest/preview/marketplace/__init__.py new file mode 100644 index 0000000000..fcc99a4112 --- /dev/null +++ b/twilio/rest/preview/marketplace/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.preview.marketplace.available_add_on import AvailableAddOnList +from twilio.rest.preview.marketplace.installed_add_on import InstalledAddOnList + + +class Marketplace(Version): + + def __init__(self, domain: Domain): + """ + Initialize the Marketplace version of Preview + + :param domain: The Twilio.preview domain + """ + super().__init__(domain, "marketplace") + self._available_add_ons: Optional[AvailableAddOnList] = None + self._installed_add_ons: Optional[InstalledAddOnList] = None + + @property + def available_add_ons(self) -> AvailableAddOnList: + if self._available_add_ons is None: + self._available_add_ons = AvailableAddOnList(self) + return self._available_add_ons + + @property + def installed_add_ons(self) -> InstalledAddOnList: + if self._installed_add_ons is None: + self._installed_add_ons = InstalledAddOnList(self) + return self._installed_add_ons + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Preview.Marketplace>" diff --git a/twilio/rest/preview/marketplace/available_add_on/__init__.py b/twilio/rest/preview/marketplace/available_add_on/__init__.py new file mode 100644 index 0000000000..e81ec649de --- /dev/null +++ b/twilio/rest/preview/marketplace/available_add_on/__init__.py @@ -0,0 +1,438 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.preview.marketplace.available_add_on.available_add_on_extension import ( + AvailableAddOnExtensionList, +) + + +class AvailableAddOnInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the AvailableAddOn resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar description: A short description of the Add-on's functionality. + :ivar pricing_type: How customers are charged for using this Add-on. + :ivar configuration_schema: The JSON object with the configuration that must be provided when installing a given Add-on. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.pricing_type: Optional[str] = payload.get("pricing_type") + self.configuration_schema: Optional[Dict[str, object]] = payload.get( + "configuration_schema" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[AvailableAddOnContext] = None + + @property + def _proxy(self) -> "AvailableAddOnContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AvailableAddOnContext for this AvailableAddOnInstance + """ + if self._context is None: + self._context = AvailableAddOnContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AvailableAddOnInstance": + """ + Fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AvailableAddOnInstance": + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + return await self._proxy.fetch_async() + + @property + def extensions(self) -> AvailableAddOnExtensionList: + """ + Access the extensions + """ + return self._proxy.extensions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.Marketplace.AvailableAddOnInstance {}>".format(context) + + +class AvailableAddOnContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the AvailableAddOnContext + + :param version: Version that contains the resource + :param sid: The SID of the AvailableAddOn resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/AvailableAddOns/{sid}".format(**self._solution) + + self._extensions: Optional[AvailableAddOnExtensionList] = None + + def fetch(self) -> AvailableAddOnInstance: + """ + Fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AvailableAddOnInstance: + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + @property + def extensions(self) -> AvailableAddOnExtensionList: + """ + Access the extensions + """ + if self._extensions is None: + self._extensions = AvailableAddOnExtensionList( + self._version, + self._solution["sid"], + ) + return self._extensions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.Marketplace.AvailableAddOnContext {}>".format(context) + + +class AvailableAddOnPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnInstance: + """ + Build an instance of AvailableAddOnInstance + + :param payload: Payload response from the API + """ + return AvailableAddOnInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.Marketplace.AvailableAddOnPage>" + + +class AvailableAddOnList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AvailableAddOnList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/AvailableAddOns" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AvailableAddOnInstance]: + """ + Streams AvailableAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AvailableAddOnInstance]: + """ + Asynchronously streams AvailableAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnInstance]: + """ + Lists AvailableAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnInstance]: + """ + Asynchronously lists AvailableAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailableAddOnPage: + """ + Retrieve a single page of AvailableAddOnInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AvailableAddOnInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailableAddOnPage: + """ + Asynchronously retrieve a single page of AvailableAddOnInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AvailableAddOnInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnPage(self._version, response) + + def get_page(self, target_url: str) -> AvailableAddOnPage: + """ + Retrieve a specific page of AvailableAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AvailableAddOnPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AvailableAddOnPage: + """ + Asynchronously retrieve a specific page of AvailableAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AvailableAddOnPage(self._version, response) + + def get(self, sid: str) -> AvailableAddOnContext: + """ + Constructs a AvailableAddOnContext + + :param sid: The SID of the AvailableAddOn resource to fetch. + """ + return AvailableAddOnContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AvailableAddOnContext: + """ + Constructs a AvailableAddOnContext + + :param sid: The SID of the AvailableAddOn resource to fetch. + """ + return AvailableAddOnContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.Marketplace.AvailableAddOnList>" diff --git a/twilio/rest/preview/marketplace/available_add_on/available_add_on_extension.py b/twilio/rest/preview/marketplace/available_add_on/available_add_on_extension.py new file mode 100644 index 0000000000..4c05f4244d --- /dev/null +++ b/twilio/rest/preview/marketplace/available_add_on/available_add_on_extension.py @@ -0,0 +1,445 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AvailableAddOnExtensionInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the AvailableAddOnExtension resource. + :ivar available_add_on_sid: The SID of the AvailableAddOn resource to which this extension applies. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar product_name: The name of the Product this Extension is used within. + :ivar unique_name: An application-defined string that uniquely identifies the resource. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + available_add_on_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.available_add_on_sid: Optional[str] = payload.get("available_add_on_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.product_name: Optional[str] = payload.get("product_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "available_add_on_sid": available_add_on_sid, + "sid": sid or self.sid, + } + self._context: Optional[AvailableAddOnExtensionContext] = None + + @property + def _proxy(self) -> "AvailableAddOnExtensionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AvailableAddOnExtensionContext for this AvailableAddOnExtensionInstance + """ + if self._context is None: + self._context = AvailableAddOnExtensionContext( + self._version, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AvailableAddOnExtensionInstance": + """ + Fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AvailableAddOnExtensionInstance": + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.Marketplace.AvailableAddOnExtensionInstance {}>".format( + context + ) + + +class AvailableAddOnExtensionContext(InstanceContext): + + def __init__(self, version: Version, available_add_on_sid: str, sid: str): + """ + Initialize the AvailableAddOnExtensionContext + + :param version: Version that contains the resource + :param available_add_on_sid: The SID of the AvailableAddOn resource with the extension to fetch. + :param sid: The SID of the AvailableAddOn Extension resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "available_add_on_sid": available_add_on_sid, + "sid": sid, + } + self._uri = "/AvailableAddOns/{available_add_on_sid}/Extensions/{sid}".format( + **self._solution + ) + + def fetch(self) -> AvailableAddOnExtensionInstance: + """ + Fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AvailableAddOnExtensionInstance: + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.Marketplace.AvailableAddOnExtensionContext {}>".format( + context + ) + + +class AvailableAddOnExtensionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnExtensionInstance: + """ + Build an instance of AvailableAddOnExtensionInstance + + :param payload: Payload response from the API + """ + return AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.Marketplace.AvailableAddOnExtensionPage>" + + +class AvailableAddOnExtensionList(ListResource): + + def __init__(self, version: Version, available_add_on_sid: str): + """ + Initialize the AvailableAddOnExtensionList + + :param version: Version that contains the resource + :param available_add_on_sid: The SID of the AvailableAddOn resource with the extensions to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "available_add_on_sid": available_add_on_sid, + } + self._uri = "/AvailableAddOns/{available_add_on_sid}/Extensions".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AvailableAddOnExtensionInstance]: + """ + Streams AvailableAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AvailableAddOnExtensionInstance]: + """ + Asynchronously streams AvailableAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnExtensionInstance]: + """ + Lists AvailableAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnExtensionInstance]: + """ + Asynchronously lists AvailableAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailableAddOnExtensionPage: + """ + Retrieve a single page of AvailableAddOnExtensionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AvailableAddOnExtensionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnExtensionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailableAddOnExtensionPage: + """ + Asynchronously retrieve a single page of AvailableAddOnExtensionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AvailableAddOnExtensionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AvailableAddOnExtensionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AvailableAddOnExtensionPage: + """ + Retrieve a specific page of AvailableAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnExtensionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AvailableAddOnExtensionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AvailableAddOnExtensionPage: + """ + Asynchronously retrieve a specific page of AvailableAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnExtensionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AvailableAddOnExtensionPage(self._version, response, self._solution) + + def get(self, sid: str) -> AvailableAddOnExtensionContext: + """ + Constructs a AvailableAddOnExtensionContext + + :param sid: The SID of the AvailableAddOn Extension resource to fetch. + """ + return AvailableAddOnExtensionContext( + self._version, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AvailableAddOnExtensionContext: + """ + Constructs a AvailableAddOnExtensionContext + + :param sid: The SID of the AvailableAddOn Extension resource to fetch. + """ + return AvailableAddOnExtensionContext( + self._version, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.Marketplace.AvailableAddOnExtensionList>" diff --git a/twilio/rest/preview/marketplace/installed_add_on/__init__.py b/twilio/rest/preview/marketplace/installed_add_on/__init__.py new file mode 100644 index 0000000000..7f1fadc510 --- /dev/null +++ b/twilio/rest/preview/marketplace/installed_add_on/__init__.py @@ -0,0 +1,671 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension import ( + InstalledAddOnExtensionList, +) + + +class InstalledAddOnInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the InstalledAddOn resource. This Sid can also be found in the Console on that specific Add-ons page as the 'Available Add-on Sid'. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the InstalledAddOn resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar description: A short description of the Add-on's functionality. + :ivar configuration: The JSON object that represents the current configuration of installed Add-on. + :ivar unique_name: An application-defined string that uniquely identifies the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.unique_name: Optional[str] = payload.get("unique_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[InstalledAddOnContext] = None + + @property + def _proxy(self) -> "InstalledAddOnContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InstalledAddOnContext for this InstalledAddOnInstance + """ + if self._context is None: + self._context = InstalledAddOnContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the InstalledAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "InstalledAddOnInstance": + """ + Fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InstalledAddOnInstance": + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> "InstalledAddOnInstance": + """ + Update the InstalledAddOnInstance + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The updated InstalledAddOnInstance + """ + return self._proxy.update( + configuration=configuration, + unique_name=unique_name, + ) + + async def update_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> "InstalledAddOnInstance": + """ + Asynchronous coroutine to update the InstalledAddOnInstance + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The updated InstalledAddOnInstance + """ + return await self._proxy.update_async( + configuration=configuration, + unique_name=unique_name, + ) + + @property + def extensions(self) -> InstalledAddOnExtensionList: + """ + Access the extensions + """ + return self._proxy.extensions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.Marketplace.InstalledAddOnInstance {}>".format(context) + + +class InstalledAddOnContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the InstalledAddOnContext + + :param version: Version that contains the resource + :param sid: The SID of the InstalledAddOn resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/InstalledAddOns/{sid}".format(**self._solution) + + self._extensions: Optional[InstalledAddOnExtensionList] = None + + def delete(self) -> bool: + """ + Deletes the InstalledAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> InstalledAddOnInstance: + """ + Fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InstalledAddOnInstance: + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: + """ + Update the InstalledAddOnInstance + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The updated InstalledAddOnInstance + """ + + data = values.of( + { + "Configuration": serialize.object(configuration), + "UniqueName": unique_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: + """ + Asynchronous coroutine to update the InstalledAddOnInstance + + :param configuration: Valid JSON object that conform to the configuration schema exposed by the associated AvailableAddOn resource. This is only required by Add-ons that need to be configured + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The updated InstalledAddOnInstance + """ + + data = values.of( + { + "Configuration": serialize.object(configuration), + "UniqueName": unique_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def extensions(self) -> InstalledAddOnExtensionList: + """ + Access the extensions + """ + if self._extensions is None: + self._extensions = InstalledAddOnExtensionList( + self._version, + self._solution["sid"], + ) + return self._extensions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.Marketplace.InstalledAddOnContext {}>".format(context) + + +class InstalledAddOnPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnInstance: + """ + Build an instance of InstalledAddOnInstance + + :param payload: Payload response from the API + """ + return InstalledAddOnInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.Marketplace.InstalledAddOnPage>" + + +class InstalledAddOnList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InstalledAddOnList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/InstalledAddOns" + + def create( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: + """ + Create the InstalledAddOnInstance + + :param available_add_on_sid: The SID of the AvaliableAddOn to install. + :param accept_terms_of_service: Whether the Terms of Service were accepted. + :param configuration: The JSON object that represents the configuration of the new Add-on being installed. + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The created InstalledAddOnInstance + """ + + data = values.of( + { + "AvailableAddOnSid": available_add_on_sid, + "AcceptTermsOfService": serialize.boolean_to_string( + accept_terms_of_service + ), + "Configuration": serialize.object(configuration), + "UniqueName": unique_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnInstance(self._version, payload) + + async def create_async( + self, + available_add_on_sid: str, + accept_terms_of_service: bool, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> InstalledAddOnInstance: + """ + Asynchronously create the InstalledAddOnInstance + + :param available_add_on_sid: The SID of the AvaliableAddOn to install. + :param accept_terms_of_service: Whether the Terms of Service were accepted. + :param configuration: The JSON object that represents the configuration of the new Add-on being installed. + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within the Account. + + :returns: The created InstalledAddOnInstance + """ + + data = values.of( + { + "AvailableAddOnSid": available_add_on_sid, + "AcceptTermsOfService": serialize.boolean_to_string( + accept_terms_of_service + ), + "Configuration": serialize.object(configuration), + "UniqueName": unique_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InstalledAddOnInstance]: + """ + Streams InstalledAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InstalledAddOnInstance]: + """ + Asynchronously streams InstalledAddOnInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InstalledAddOnInstance]: + """ + Lists InstalledAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InstalledAddOnInstance]: + """ + Asynchronously lists InstalledAddOnInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InstalledAddOnPage: + """ + Retrieve a single page of InstalledAddOnInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InstalledAddOnInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InstalledAddOnPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InstalledAddOnPage: + """ + Asynchronously retrieve a single page of InstalledAddOnInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InstalledAddOnInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InstalledAddOnPage(self._version, response) + + def get_page(self, target_url: str) -> InstalledAddOnPage: + """ + Retrieve a specific page of InstalledAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InstalledAddOnPage(self._version, response) + + async def get_page_async(self, target_url: str) -> InstalledAddOnPage: + """ + Asynchronously retrieve a specific page of InstalledAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InstalledAddOnPage(self._version, response) + + def get(self, sid: str) -> InstalledAddOnContext: + """ + Constructs a InstalledAddOnContext + + :param sid: The SID of the InstalledAddOn resource to update. + """ + return InstalledAddOnContext(self._version, sid=sid) + + def __call__(self, sid: str) -> InstalledAddOnContext: + """ + Constructs a InstalledAddOnContext + + :param sid: The SID of the InstalledAddOn resource to update. + """ + return InstalledAddOnContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.Marketplace.InstalledAddOnList>" diff --git a/twilio/rest/preview/marketplace/installed_add_on/installed_add_on_extension.py b/twilio/rest/preview/marketplace/installed_add_on/installed_add_on_extension.py new file mode 100644 index 0000000000..e0574ee2fd --- /dev/null +++ b/twilio/rest/preview/marketplace/installed_add_on/installed_add_on_extension.py @@ -0,0 +1,533 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InstalledAddOnExtensionInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the InstalledAddOn Extension resource. + :ivar installed_add_on_sid: The SID of the InstalledAddOn resource to which this extension applies. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar product_name: The name of the Product this Extension is used within. + :ivar unique_name: An application-defined string that uniquely identifies the resource. + :ivar enabled: Whether the Extension will be invoked. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + installed_add_on_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.installed_add_on_sid: Optional[str] = payload.get("installed_add_on_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.product_name: Optional[str] = payload.get("product_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.enabled: Optional[bool] = payload.get("enabled") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + "sid": sid or self.sid, + } + self._context: Optional[InstalledAddOnExtensionContext] = None + + @property + def _proxy(self) -> "InstalledAddOnExtensionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InstalledAddOnExtensionContext for this InstalledAddOnExtensionInstance + """ + if self._context is None: + self._context = InstalledAddOnExtensionContext( + self._version, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "InstalledAddOnExtensionInstance": + """ + Fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InstalledAddOnExtensionInstance": + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + return await self._proxy.fetch_async() + + def update(self, enabled: bool) -> "InstalledAddOnExtensionInstance": + """ + Update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + return self._proxy.update( + enabled=enabled, + ) + + async def update_async(self, enabled: bool) -> "InstalledAddOnExtensionInstance": + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + return await self._proxy.update_async( + enabled=enabled, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.Marketplace.InstalledAddOnExtensionInstance {}>".format( + context + ) + + +class InstalledAddOnExtensionContext(InstanceContext): + + def __init__(self, version: Version, installed_add_on_sid: str, sid: str): + """ + Initialize the InstalledAddOnExtensionContext + + :param version: Version that contains the resource + :param installed_add_on_sid: The SID of the InstalledAddOn resource with the extension to update. + :param sid: The SID of the InstalledAddOn Extension resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + "sid": sid, + } + self._uri = "/InstalledAddOns/{installed_add_on_sid}/Extensions/{sid}".format( + **self._solution + ) + + def fetch(self) -> InstalledAddOnExtensionInstance: + """ + Fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InstalledAddOnExtensionInstance: + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + def update(self, enabled: bool) -> InstalledAddOnExtensionInstance: + """ + Update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, enabled: bool) -> InstalledAddOnExtensionInstance: + """ + Asynchronous coroutine to update the InstalledAddOnExtensionInstance + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.Marketplace.InstalledAddOnExtensionContext {}>".format( + context + ) + + +class InstalledAddOnExtensionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnExtensionInstance: + """ + Build an instance of InstalledAddOnExtensionInstance + + :param payload: Payload response from the API + """ + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.Marketplace.InstalledAddOnExtensionPage>" + + +class InstalledAddOnExtensionList(ListResource): + + def __init__(self, version: Version, installed_add_on_sid: str): + """ + Initialize the InstalledAddOnExtensionList + + :param version: Version that contains the resource + :param installed_add_on_sid: The SID of the InstalledAddOn resource with the extensions to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + } + self._uri = "/InstalledAddOns/{installed_add_on_sid}/Extensions".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InstalledAddOnExtensionInstance]: + """ + Streams InstalledAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InstalledAddOnExtensionInstance]: + """ + Asynchronously streams InstalledAddOnExtensionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InstalledAddOnExtensionInstance]: + """ + Lists InstalledAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InstalledAddOnExtensionInstance]: + """ + Asynchronously lists InstalledAddOnExtensionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InstalledAddOnExtensionPage: + """ + Retrieve a single page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InstalledAddOnExtensionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InstalledAddOnExtensionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InstalledAddOnExtensionPage: + """ + Asynchronously retrieve a single page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InstalledAddOnExtensionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InstalledAddOnExtensionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> InstalledAddOnExtensionPage: + """ + Retrieve a specific page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnExtensionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InstalledAddOnExtensionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> InstalledAddOnExtensionPage: + """ + Asynchronously retrieve a specific page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnExtensionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InstalledAddOnExtensionPage(self._version, response, self._solution) + + def get(self, sid: str) -> InstalledAddOnExtensionContext: + """ + Constructs a InstalledAddOnExtensionContext + + :param sid: The SID of the InstalledAddOn Extension resource to update. + """ + return InstalledAddOnExtensionContext( + self._version, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InstalledAddOnExtensionContext: + """ + Constructs a InstalledAddOnExtensionContext + + :param sid: The SID of the InstalledAddOn Extension resource to update. + """ + return InstalledAddOnExtensionContext( + self._version, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.Marketplace.InstalledAddOnExtensionList>" diff --git a/twilio/rest/preview/wireless/__init__.py b/twilio/rest/preview/wireless/__init__.py new file mode 100644 index 0000000000..85ed4fb54d --- /dev/null +++ b/twilio/rest/preview/wireless/__init__.py @@ -0,0 +1,59 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.preview.wireless.command import CommandList +from twilio.rest.preview.wireless.rate_plan import RatePlanList +from twilio.rest.preview.wireless.sim import SimList + + +class Wireless(Version): + + def __init__(self, domain: Domain): + """ + Initialize the Wireless version of Preview + + :param domain: The Twilio.preview domain + """ + super().__init__(domain, "wireless") + self._commands: Optional[CommandList] = None + self._rate_plans: Optional[RatePlanList] = None + self._sims: Optional[SimList] = None + + @property + def commands(self) -> CommandList: + if self._commands is None: + self._commands = CommandList(self) + return self._commands + + @property + def rate_plans(self) -> RatePlanList: + if self._rate_plans is None: + self._rate_plans = RatePlanList(self) + return self._rate_plans + + @property + def sims(self) -> SimList: + if self._sims is None: + self._sims = SimList(self) + return self._sims + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Preview.Wireless>" diff --git a/twilio/rest/preview/wireless/command.py b/twilio/rest/preview/wireless/command.py new file mode 100644 index 0000000000..8e715e09ef --- /dev/null +++ b/twilio/rest/preview/wireless/command.py @@ -0,0 +1,595 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CommandInstance(InstanceResource): + """ + :ivar sid: + :ivar account_sid: + :ivar device_sid: + :ivar sim_sid: + :ivar command: + :ivar command_mode: + :ivar status: + :ivar direction: + :ivar date_created: + :ivar date_updated: + :ivar url: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.device_sid: Optional[str] = payload.get("device_sid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.command: Optional[str] = payload.get("command") + self.command_mode: Optional[str] = payload.get("command_mode") + self.status: Optional[str] = payload.get("status") + self.direction: Optional[str] = payload.get("direction") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CommandContext] = None + + @property + def _proxy(self) -> "CommandContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CommandContext for this CommandInstance + """ + if self._context is None: + self._context = CommandContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "CommandInstance": + """ + Fetch the CommandInstance + + + :returns: The fetched CommandInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CommandInstance": + """ + Asynchronous coroutine to fetch the CommandInstance + + + :returns: The fetched CommandInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.Wireless.CommandInstance {}>".format(context) + + +class CommandContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CommandContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Commands/{sid}".format(**self._solution) + + def fetch(self) -> CommandInstance: + """ + Fetch the CommandInstance + + + :returns: The fetched CommandInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CommandInstance: + """ + Asynchronous coroutine to fetch the CommandInstance + + + :returns: The fetched CommandInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.Wireless.CommandContext {}>".format(context) + + +class CommandPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CommandInstance: + """ + Build an instance of CommandInstance + + :param payload: Payload response from the API + """ + return CommandInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.Wireless.CommandPage>" + + +class CommandList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CommandList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Commands" + + def create( + self, + command: str, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union[str, object] = values.unset, + include_sid: Union[str, object] = values.unset, + ) -> CommandInstance: + """ + Create the CommandInstance + + :param command: + :param device: + :param sim: + :param callback_method: + :param callback_url: + :param command_mode: + :param include_sid: + + :returns: The created CommandInstance + """ + + data = values.of( + { + "Command": command, + "Device": device, + "Sim": sim, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "CommandMode": command_mode, + "IncludeSid": include_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CommandInstance(self._version, payload) + + async def create_async( + self, + command: str, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union[str, object] = values.unset, + include_sid: Union[str, object] = values.unset, + ) -> CommandInstance: + """ + Asynchronously create the CommandInstance + + :param command: + :param device: + :param sim: + :param callback_method: + :param callback_url: + :param command_mode: + :param include_sid: + + :returns: The created CommandInstance + """ + + data = values.of( + { + "Command": command, + "Device": device, + "Sim": sim, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "CommandMode": command_mode, + "IncludeSid": include_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CommandInstance(self._version, payload) + + def stream( + self, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CommandInstance]: + """ + Streams CommandInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str device: + :param str sim: + :param str status: + :param str direction: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + device=device, + sim=sim, + status=status, + direction=direction, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CommandInstance]: + """ + Asynchronously streams CommandInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str device: + :param str sim: + :param str status: + :param str direction: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + device=device, + sim=sim, + status=status, + direction=direction, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CommandInstance]: + """ + Lists CommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str device: + :param str sim: + :param str status: + :param str direction: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + device=device, + sim=sim, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CommandInstance]: + """ + Asynchronously lists CommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str device: + :param str sim: + :param str status: + :param str direction: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + device=device, + sim=sim, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CommandPage: + """ + Retrieve a single page of CommandInstance records from the API. + Request is executed immediately + + :param device: + :param sim: + :param status: + :param direction: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CommandInstance + """ + data = values.of( + { + "Device": device, + "Sim": sim, + "Status": status, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CommandPage(self._version, response) + + async def page_async( + self, + device: Union[str, object] = values.unset, + sim: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + direction: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CommandPage: + """ + Asynchronously retrieve a single page of CommandInstance records from the API. + Request is executed immediately + + :param device: + :param sim: + :param status: + :param direction: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CommandInstance + """ + data = values.of( + { + "Device": device, + "Sim": sim, + "Status": status, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CommandPage(self._version, response) + + def get_page(self, target_url: str) -> CommandPage: + """ + Retrieve a specific page of CommandInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CommandInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CommandPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CommandPage: + """ + Asynchronously retrieve a specific page of CommandInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CommandInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CommandPage(self._version, response) + + def get(self, sid: str) -> CommandContext: + """ + Constructs a CommandContext + + :param sid: + """ + return CommandContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CommandContext: + """ + Constructs a CommandContext + + :param sid: + """ + return CommandContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.Wireless.CommandList>" diff --git a/twilio/rest/preview/wireless/rate_plan.py b/twilio/rest/preview/wireless/rate_plan.py new file mode 100644 index 0000000000..95e45f1ef2 --- /dev/null +++ b/twilio/rest/preview/wireless/rate_plan.py @@ -0,0 +1,699 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RatePlanInstance(InstanceResource): + """ + :ivar sid: + :ivar unique_name: + :ivar account_sid: + :ivar friendly_name: + :ivar data_enabled: + :ivar data_metering: + :ivar data_limit: + :ivar messaging_enabled: + :ivar voice_enabled: + :ivar national_roaming_enabled: + :ivar international_roaming: + :ivar date_created: + :ivar date_updated: + :ivar url: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.data_enabled: Optional[bool] = payload.get("data_enabled") + self.data_metering: Optional[str] = payload.get("data_metering") + self.data_limit: Optional[int] = deserialize.integer(payload.get("data_limit")) + self.messaging_enabled: Optional[bool] = payload.get("messaging_enabled") + self.voice_enabled: Optional[bool] = payload.get("voice_enabled") + self.national_roaming_enabled: Optional[bool] = payload.get( + "national_roaming_enabled" + ) + self.international_roaming: Optional[List[str]] = payload.get( + "international_roaming" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[RatePlanContext] = None + + @property + def _proxy(self) -> "RatePlanContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RatePlanContext for this RatePlanInstance + """ + if self._context is None: + self._context = RatePlanContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RatePlanInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RatePlanInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RatePlanInstance": + """ + Fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RatePlanInstance": + """ + Asynchronous coroutine to fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "RatePlanInstance": + """ + Update the RatePlanInstance + + :param unique_name: + :param friendly_name: + + :returns: The updated RatePlanInstance + """ + return self._proxy.update( + unique_name=unique_name, + friendly_name=friendly_name, + ) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "RatePlanInstance": + """ + Asynchronous coroutine to update the RatePlanInstance + + :param unique_name: + :param friendly_name: + + :returns: The updated RatePlanInstance + """ + return await self._proxy.update_async( + unique_name=unique_name, + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.Wireless.RatePlanInstance {}>".format(context) + + +class RatePlanContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the RatePlanContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RatePlans/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RatePlanInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RatePlanInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RatePlanInstance: + """ + Fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RatePlanInstance: + """ + Asynchronous coroutine to fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> RatePlanInstance: + """ + Update the RatePlanInstance + + :param unique_name: + :param friendly_name: + + :returns: The updated RatePlanInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> RatePlanInstance: + """ + Asynchronous coroutine to update the RatePlanInstance + + :param unique_name: + :param friendly_name: + + :returns: The updated RatePlanInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.Wireless.RatePlanContext {}>".format(context) + + +class RatePlanPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RatePlanInstance: + """ + Build an instance of RatePlanInstance + + :param payload: Payload response from the API + """ + return RatePlanInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.Wireless.RatePlanPage>" + + +class RatePlanList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RatePlanList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RatePlans" + + def create( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + commands_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + ) -> RatePlanInstance: + """ + Create the RatePlanInstance + + :param unique_name: + :param friendly_name: + :param data_enabled: + :param data_limit: + :param data_metering: + :param messaging_enabled: + :param voice_enabled: + :param commands_enabled: + :param national_roaming_enabled: + :param international_roaming: + + :returns: The created RatePlanInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "DataEnabled": serialize.boolean_to_string(data_enabled), + "DataLimit": data_limit, + "DataMetering": data_metering, + "MessagingEnabled": serialize.boolean_to_string(messaging_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "CommandsEnabled": serialize.boolean_to_string(commands_enabled), + "NationalRoamingEnabled": serialize.boolean_to_string( + national_roaming_enabled + ), + "InternationalRoaming": serialize.map( + international_roaming, lambda e: e + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RatePlanInstance(self._version, payload) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + commands_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + ) -> RatePlanInstance: + """ + Asynchronously create the RatePlanInstance + + :param unique_name: + :param friendly_name: + :param data_enabled: + :param data_limit: + :param data_metering: + :param messaging_enabled: + :param voice_enabled: + :param commands_enabled: + :param national_roaming_enabled: + :param international_roaming: + + :returns: The created RatePlanInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "DataEnabled": serialize.boolean_to_string(data_enabled), + "DataLimit": data_limit, + "DataMetering": data_metering, + "MessagingEnabled": serialize.boolean_to_string(messaging_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "CommandsEnabled": serialize.boolean_to_string(commands_enabled), + "NationalRoamingEnabled": serialize.boolean_to_string( + national_roaming_enabled + ), + "InternationalRoaming": serialize.map( + international_roaming, lambda e: e + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RatePlanInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RatePlanInstance]: + """ + Streams RatePlanInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RatePlanInstance]: + """ + Asynchronously streams RatePlanInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RatePlanInstance]: + """ + Lists RatePlanInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RatePlanInstance]: + """ + Asynchronously lists RatePlanInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RatePlanPage: + """ + Retrieve a single page of RatePlanInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RatePlanInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RatePlanPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RatePlanPage: + """ + Asynchronously retrieve a single page of RatePlanInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RatePlanInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RatePlanPage(self._version, response) + + def get_page(self, target_url: str) -> RatePlanPage: + """ + Retrieve a specific page of RatePlanInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RatePlanInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RatePlanPage(self._version, response) + + async def get_page_async(self, target_url: str) -> RatePlanPage: + """ + Asynchronously retrieve a specific page of RatePlanInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RatePlanInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RatePlanPage(self._version, response) + + def get(self, sid: str) -> RatePlanContext: + """ + Constructs a RatePlanContext + + :param sid: + """ + return RatePlanContext(self._version, sid=sid) + + def __call__(self, sid: str) -> RatePlanContext: + """ + Constructs a RatePlanContext + + :param sid: + """ + return RatePlanContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.Wireless.RatePlanList>" diff --git a/twilio/rest/preview/wireless/sim/__init__.py b/twilio/rest/preview/wireless/sim/__init__.py new file mode 100644 index 0000000000..07a9e74da0 --- /dev/null +++ b/twilio/rest/preview/wireless/sim/__init__.py @@ -0,0 +1,833 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.preview.wireless.sim.usage import UsageList + + +class SimInstance(InstanceResource): + """ + :ivar sid: + :ivar unique_name: + :ivar account_sid: + :ivar rate_plan_sid: + :ivar friendly_name: + :ivar iccid: + :ivar e_id: + :ivar status: + :ivar commands_callback_url: + :ivar commands_callback_method: + :ivar sms_fallback_method: + :ivar sms_fallback_url: + :ivar sms_method: + :ivar sms_url: + :ivar voice_fallback_method: + :ivar voice_fallback_url: + :ivar voice_method: + :ivar voice_url: + :ivar date_created: + :ivar date_updated: + :ivar url: + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.rate_plan_sid: Optional[str] = payload.get("rate_plan_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.iccid: Optional[str] = payload.get("iccid") + self.e_id: Optional[str] = payload.get("e_id") + self.status: Optional[str] = payload.get("status") + self.commands_callback_url: Optional[str] = payload.get("commands_callback_url") + self.commands_callback_method: Optional[str] = payload.get( + "commands_callback_method" + ) + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_url: Optional[str] = payload.get("sms_url") + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_url: Optional[str] = payload.get("voice_url") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SimContext] = None + + @property + def _proxy(self) -> "SimContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SimContext for this SimInstance + """ + if self._context is None: + self._context = SimContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "SimInstance": + """ + Fetch the SimInstance + + + :returns: The fetched SimInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SimInstance": + """ + Asynchronous coroutine to fetch the SimInstance + + + :returns: The fetched SimInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> "SimInstance": + """ + Update the SimInstance + + :param unique_name: + :param callback_method: + :param callback_url: + :param friendly_name: + :param rate_plan: + :param status: + :param commands_callback_method: + :param commands_callback_url: + :param sms_fallback_method: + :param sms_fallback_url: + :param sms_method: + :param sms_url: + :param voice_fallback_method: + :param voice_fallback_url: + :param voice_method: + :param voice_url: + + :returns: The updated SimInstance + """ + return self._proxy.update( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + ) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> "SimInstance": + """ + Asynchronous coroutine to update the SimInstance + + :param unique_name: + :param callback_method: + :param callback_url: + :param friendly_name: + :param rate_plan: + :param status: + :param commands_callback_method: + :param commands_callback_url: + :param sms_fallback_method: + :param sms_fallback_url: + :param sms_method: + :param sms_url: + :param voice_fallback_method: + :param voice_fallback_url: + :param voice_method: + :param voice_url: + + :returns: The updated SimInstance + """ + return await self._proxy.update_async( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + ) + + @property + def usage(self) -> UsageList: + """ + Access the usage + """ + return self._proxy.usage + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.Wireless.SimInstance {}>".format(context) + + +class SimContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SimContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Sims/{sid}".format(**self._solution) + + self._usage: Optional[UsageList] = None + + def fetch(self) -> SimInstance: + """ + Fetch the SimInstance + + + :returns: The fetched SimInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SimInstance: + """ + Asynchronous coroutine to fetch the SimInstance + + + :returns: The fetched SimInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> SimInstance: + """ + Update the SimInstance + + :param unique_name: + :param callback_method: + :param callback_url: + :param friendly_name: + :param rate_plan: + :param status: + :param commands_callback_method: + :param commands_callback_url: + :param sms_fallback_method: + :param sms_fallback_url: + :param sms_method: + :param sms_url: + :param voice_fallback_method: + :param voice_fallback_url: + :param voice_method: + :param voice_url: + + :returns: The updated SimInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "FriendlyName": friendly_name, + "RatePlan": rate_plan, + "Status": status, + "CommandsCallbackMethod": commands_callback_method, + "CommandsCallbackUrl": commands_callback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union[str, object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + ) -> SimInstance: + """ + Asynchronous coroutine to update the SimInstance + + :param unique_name: + :param callback_method: + :param callback_url: + :param friendly_name: + :param rate_plan: + :param status: + :param commands_callback_method: + :param commands_callback_url: + :param sms_fallback_method: + :param sms_fallback_url: + :param sms_method: + :param sms_url: + :param voice_fallback_method: + :param voice_fallback_url: + :param voice_method: + :param voice_url: + + :returns: The updated SimInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "FriendlyName": friendly_name, + "RatePlan": rate_plan, + "Status": status, + "CommandsCallbackMethod": commands_callback_method, + "CommandsCallbackUrl": commands_callback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def usage(self) -> UsageList: + """ + Access the usage + """ + if self._usage is None: + self._usage = UsageList( + self._version, + self._solution["sid"], + ) + return self._usage + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.Wireless.SimContext {}>".format(context) + + +class SimPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SimInstance: + """ + Build an instance of SimInstance + + :param payload: Payload response from the API + """ + return SimInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.Wireless.SimPage>" + + +class SimList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SimList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Sims" + + def stream( + self, + status: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SimInstance]: + """ + Streams SimInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str status: + :param str iccid: + :param str rate_plan: + :param str e_id: + :param str sim_registration_code: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SimInstance]: + """ + Asynchronously streams SimInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str status: + :param str iccid: + :param str rate_plan: + :param str e_id: + :param str sim_registration_code: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SimInstance]: + """ + Lists SimInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str status: + :param str iccid: + :param str rate_plan: + :param str e_id: + :param str sim_registration_code: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SimInstance]: + """ + Asynchronously lists SimInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str status: + :param str iccid: + :param str rate_plan: + :param str e_id: + :param str sim_registration_code: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SimPage: + """ + Retrieve a single page of SimInstance records from the API. + Request is executed immediately + + :param status: + :param iccid: + :param rate_plan: + :param e_id: + :param sim_registration_code: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SimInstance + """ + data = values.of( + { + "Status": status, + "Iccid": iccid, + "RatePlan": rate_plan, + "EId": e_id, + "SimRegistrationCode": sim_registration_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SimPage(self._version, response) + + async def page_async( + self, + status: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SimPage: + """ + Asynchronously retrieve a single page of SimInstance records from the API. + Request is executed immediately + + :param status: + :param iccid: + :param rate_plan: + :param e_id: + :param sim_registration_code: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SimInstance + """ + data = values.of( + { + "Status": status, + "Iccid": iccid, + "RatePlan": rate_plan, + "EId": e_id, + "SimRegistrationCode": sim_registration_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SimPage(self._version, response) + + def get_page(self, target_url: str) -> SimPage: + """ + Retrieve a specific page of SimInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SimInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SimPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SimPage: + """ + Asynchronously retrieve a specific page of SimInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SimInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SimPage(self._version, response) + + def get(self, sid: str) -> SimContext: + """ + Constructs a SimContext + + :param sid: + """ + return SimContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SimContext: + """ + Constructs a SimContext + + :param sid: + """ + return SimContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.Wireless.SimList>" diff --git a/twilio/rest/preview/wireless/sim/usage.py b/twilio/rest/preview/wireless/sim/usage.py new file mode 100644 index 0000000000..aff3731b51 --- /dev/null +++ b/twilio/rest/preview/wireless/sim/usage.py @@ -0,0 +1,249 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Preview + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class UsageInstance(InstanceResource): + """ + :ivar sim_sid: + :ivar sim_unique_name: + :ivar account_sid: + :ivar period: + :ivar commands_usage: + :ivar commands_costs: + :ivar data_usage: + :ivar data_costs: + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sim_sid: str): + super().__init__(version) + + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.sim_unique_name: Optional[str] = payload.get("sim_unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.period: Optional[Dict[str, object]] = payload.get("period") + self.commands_usage: Optional[Dict[str, object]] = payload.get("commands_usage") + self.commands_costs: Optional[Dict[str, object]] = payload.get("commands_costs") + self.data_usage: Optional[Dict[str, object]] = payload.get("data_usage") + self.data_costs: Optional[Dict[str, object]] = payload.get("data_costs") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sim_sid": sim_sid, + } + self._context: Optional[UsageContext] = None + + @property + def _proxy(self) -> "UsageContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UsageContext for this UsageInstance + """ + if self._context is None: + self._context = UsageContext( + self._version, + sim_sid=self._solution["sim_sid"], + ) + return self._context + + def fetch( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> "UsageInstance": + """ + Fetch the UsageInstance + + :param end: + :param start: + + :returns: The fetched UsageInstance + """ + return self._proxy.fetch( + end=end, + start=start, + ) + + async def fetch_async( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> "UsageInstance": + """ + Asynchronous coroutine to fetch the UsageInstance + + :param end: + :param start: + + :returns: The fetched UsageInstance + """ + return await self._proxy.fetch_async( + end=end, + start=start, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.Wireless.UsageInstance {}>".format(context) + + +class UsageContext(InstanceContext): + + def __init__(self, version: Version, sim_sid: str): + """ + Initialize the UsageContext + + :param version: Version that contains the resource + :param sim_sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sim_sid": sim_sid, + } + self._uri = "/Sims/{sim_sid}/Usage".format(**self._solution) + + def fetch( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> UsageInstance: + """ + Fetch the UsageInstance + + :param end: + :param start: + + :returns: The fetched UsageInstance + """ + + data = values.of( + { + "End": end, + "Start": start, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return UsageInstance( + self._version, + payload, + sim_sid=self._solution["sim_sid"], + ) + + async def fetch_async( + self, + end: Union[str, object] = values.unset, + start: Union[str, object] = values.unset, + ) -> UsageInstance: + """ + Asynchronous coroutine to fetch the UsageInstance + + :param end: + :param start: + + :returns: The fetched UsageInstance + """ + + data = values.of( + { + "End": end, + "Start": start, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return UsageInstance( + self._version, + payload, + sim_sid=self._solution["sim_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Preview.Wireless.UsageContext {}>".format(context) + + +class UsageList(ListResource): + + def __init__(self, version: Version, sim_sid: str): + """ + Initialize the UsageList + + :param version: Version that contains the resource + :param sim_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sim_sid": sim_sid, + } + + def get(self) -> UsageContext: + """ + Constructs a UsageContext + + """ + return UsageContext(self._version, sim_sid=self._solution["sim_sid"]) + + def __call__(self) -> UsageContext: + """ + Constructs a UsageContext + + """ + return UsageContext(self._version, sim_sid=self._solution["sim_sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Preview.Wireless.UsageList>" diff --git a/twilio/rest/preview_iam/PreviewIamBase.py b/twilio/rest/preview_iam/PreviewIamBase.py new file mode 100644 index 0000000000..22fcbe70b1 --- /dev/null +++ b/twilio/rest/preview_iam/PreviewIamBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.preview_iam.v1 import V1 + + +class PreviewIamBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the PreviewIam Domain + + :returns: Domain for PreviewIam + """ + super().__init__(twilio, "https://preview-iam.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of PreviewIam + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.PreviewIam>" diff --git a/twilio/rest/preview_iam/__init__.py b/twilio/rest/preview_iam/__init__.py new file mode 100644 index 0000000000..9a5bf85b24 --- /dev/null +++ b/twilio/rest/preview_iam/__init__.py @@ -0,0 +1,26 @@ +from twilio.rest.preview_iam.PreviewIamBase import PreviewIamBase + +from twilio.rest.preview_iam.v1.authorize import ( + AuthorizeList, +) +from twilio.rest.preview_iam.v1.token import ( + TokenList, +) +from twilio.rest.preview_iam.versionless.organization import ( + OrganizationList, +) +from twilio.rest.preview_iam.versionless import Versionless + + +class PreviewIam(PreviewIamBase): + @property + def organization(self) -> OrganizationList: + return Versionless(self).organization + + @property + def authorize(self) -> AuthorizeList: + return self.v1.authorize + + @property + def token(self) -> TokenList: + return self.v1.token diff --git a/twilio/rest/preview_iam/v1/__init__.py b/twilio/rest/preview_iam/v1/__init__.py new file mode 100644 index 0000000000..2243277793 --- /dev/null +++ b/twilio/rest/preview_iam/v1/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.preview_iam.v1.authorize import AuthorizeList +from twilio.rest.preview_iam.v1.token import TokenList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of PreviewIam + + :param domain: The Twilio.preview_iam domain + """ + super().__init__(domain, "v1") + self._authorize: Optional[AuthorizeList] = None + self._token: Optional[TokenList] = None + + @property + def authorize(self) -> AuthorizeList: + if self._authorize is None: + self._authorize = AuthorizeList(self) + return self._authorize + + @property + def token(self) -> TokenList: + if self._token is None: + self._token = TokenList(self) + return self._token + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.PreviewIam.V1>" diff --git a/twilio/rest/preview_iam/v1/authorize.py b/twilio/rest/preview_iam/v1/authorize.py new file mode 100644 index 0000000000..4166b4aea2 --- /dev/null +++ b/twilio/rest/preview_iam/v1/authorize.py @@ -0,0 +1,130 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class AuthorizeInstance(InstanceResource): + """ + :ivar redirect_to: The callback URL + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.redirect_to: Optional[str] = payload.get("redirect_to") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.PreviewIam.V1.AuthorizeInstance>" + + +class AuthorizeList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AuthorizeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/authorize" + + def fetch( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> AuthorizeInstance: + """ + Asynchronously fetch the AuthorizeInstance + + :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback + :returns: The fetched AuthorizeInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "response_type": response_type, + "client_id": client_id, + "redirect_uri": redirect_uri, + "scope": scope, + "state": state, + } + ) + + payload = self._version.fetch( + method="GET", uri=self._uri, headers=headers, params=params + ) + + return AuthorizeInstance(self._version, payload) + + async def fetch_async( + self, + response_type: Union[str, object] = values.unset, + client_id: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + state: Union[str, object] = values.unset, + ) -> AuthorizeInstance: + """ + Asynchronously fetch the AuthorizeInstance + + :param response_type: Response Type:param client_id: The Client Identifier:param redirect_uri: The url to which response will be redirected to:param scope: The scope of the access request:param state: An opaque value which can be used to maintain state between the request and callback + :returns: The fetched AuthorizeInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "response_type": response_type, + "client_id": client_id, + "redirect_uri": redirect_uri, + "scope": scope, + "state": state, + } + ) + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers, params=params + ) + + return AuthorizeInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.PreviewIam.V1.AuthorizeList>" diff --git a/twilio/rest/preview_iam/v1/token.py b/twilio/rest/preview_iam/v1/token.py new file mode 100644 index 0000000000..34d9f30080 --- /dev/null +++ b/twilio/rest/preview_iam/v1/token.py @@ -0,0 +1,170 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TokenInstance(InstanceResource): + """ + :ivar access_token: Token which carries the necessary information to access a Twilio resource directly. + :ivar refresh_token: Token which carries the information necessary to get a new access token. + :ivar id_token: Token which carries the information necessary of user profile. + :ivar token_type: Token type + :ivar expires_in: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.access_token: Optional[str] = payload.get("access_token") + self.refresh_token: Optional[str] = payload.get("refresh_token") + self.id_token: Optional[str] = payload.get("id_token") + self.token_type: Optional[str] = payload.get("token_type") + self.expires_in: Optional[int] = payload.get("expires_in") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.PreviewIam.V1.TokenInstance>" + + +class TokenList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TokenList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/token" + + def create( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Create the TokenInstance + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: The created TokenInstance + """ + + data = values.of( + { + "grant_type": grant_type, + "client_id": client_id, + "client_secret": client_secret, + "code": code, + "redirect_uri": redirect_uri, + "audience": audience, + "refresh_token": refresh_token, + "scope": scope, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TokenInstance(self._version, payload) + + async def create_async( + self, + grant_type: str, + client_id: str, + client_secret: Union[str, object] = values.unset, + code: Union[str, object] = values.unset, + redirect_uri: Union[str, object] = values.unset, + audience: Union[str, object] = values.unset, + refresh_token: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + ) -> TokenInstance: + """ + Asynchronously create the TokenInstance + + :param grant_type: Grant type is a credential representing resource owner's authorization which can be used by client to obtain access token. + :param client_id: A 34 character string that uniquely identifies this OAuth App. + :param client_secret: The credential for confidential OAuth App. + :param code: JWT token related to the authorization code grant type. + :param redirect_uri: The redirect uri + :param audience: The targeted audience uri + :param refresh_token: JWT token related to refresh access token. + :param scope: The scope of token + + :returns: The created TokenInstance + """ + + data = values.of( + { + "grant_type": grant_type, + "client_id": client_id, + "client_secret": client_secret, + "code": code, + "redirect_uri": redirect_uri, + "audience": audience, + "refresh_token": refresh_token, + "scope": scope, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TokenInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.PreviewIam.V1.TokenList>" diff --git a/twilio/rest/preview_iam/versionless/__init__.py b/twilio/rest/preview_iam/versionless/__init__.py new file mode 100644 index 0000000000..7d6d210f14 --- /dev/null +++ b/twilio/rest/preview_iam/versionless/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.preview_iam.versionless.organization import OrganizationList + + +class Versionless(Version): + + def __init__(self, domain: Domain): + """ + Initialize the Versionless version of PreviewIam + + :param domain: The Twilio.preview_iam domain + """ + super().__init__(domain, "Organizations") + self._organization: Optional[OrganizationList] = None + + @property + def organization(self) -> OrganizationList: + if self._organization is None: + self._organization = OrganizationList(self) + return self._organization + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.PreviewIam.Versionless>" diff --git a/twilio/rest/preview_iam/versionless/organization/__init__.py b/twilio/rest/preview_iam/versionless/organization/__init__.py new file mode 100644 index 0000000000..ce6e70e978 --- /dev/null +++ b/twilio/rest/preview_iam/versionless/organization/__init__.py @@ -0,0 +1,128 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.instance_context import InstanceContext + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.preview_iam.versionless.organization.account import AccountList +from twilio.rest.preview_iam.versionless.organization.role_assignment import ( + RoleAssignmentList, +) +from twilio.rest.preview_iam.versionless.organization.user import UserList + + +class OrganizationContext(InstanceContext): + + def __init__(self, version: Version, organization_sid: str): + """ + Initialize the OrganizationContext + + :param version: Version that contains the resource + :param organization_sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + } + self._uri = "/{organization_sid}".format(**self._solution) + + self._accounts: Optional[AccountList] = None + self._role_assignments: Optional[RoleAssignmentList] = None + self._users: Optional[UserList] = None + + @property + def accounts(self) -> AccountList: + """ + Access the accounts + """ + if self._accounts is None: + self._accounts = AccountList( + self._version, + self._solution["organization_sid"], + ) + return self._accounts + + @property + def role_assignments(self) -> RoleAssignmentList: + """ + Access the role_assignments + """ + if self._role_assignments is None: + self._role_assignments = RoleAssignmentList( + self._version, + self._solution["organization_sid"], + ) + return self._role_assignments + + @property + def users(self) -> UserList: + """ + Access the users + """ + if self._users is None: + self._users = UserList( + self._version, + self._solution["organization_sid"], + ) + return self._users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.PreviewIam.Versionless.OrganizationContext {}>".format(context) + + +class OrganizationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OrganizationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, organization_sid: str) -> OrganizationContext: + """ + Constructs a OrganizationContext + + :param organization_sid: + """ + return OrganizationContext(self._version, organization_sid=organization_sid) + + def __call__(self, organization_sid: str) -> OrganizationContext: + """ + Constructs a OrganizationContext + + :param organization_sid: + """ + return OrganizationContext(self._version, organization_sid=organization_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.PreviewIam.Versionless.OrganizationList>" diff --git a/twilio/rest/preview_iam/versionless/organization/account.py b/twilio/rest/preview_iam/versionless/organization/account.py new file mode 100644 index 0000000000..f1c8019860 --- /dev/null +++ b/twilio/rest/preview_iam/versionless/organization/account.py @@ -0,0 +1,438 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AccountInstance(InstanceResource): + """ + :ivar account_sid: Twilio account sid + :ivar friendly_name: Account friendly name + :ivar status: Account status + :ivar owner_sid: Twilio account sid + :ivar date_created: The date and time when the account was created in the system + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + organization_sid: str, + account_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional[str] = payload.get("status") + self.owner_sid: Optional[str] = payload.get("owner_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + + self._solution = { + "organization_sid": organization_sid, + "account_sid": account_sid or self.account_sid, + } + self._context: Optional[AccountContext] = None + + @property + def _proxy(self) -> "AccountContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AccountContext for this AccountInstance + """ + if self._context is None: + self._context = AccountContext( + self._version, + organization_sid=self._solution["organization_sid"], + account_sid=self._solution["account_sid"], + ) + return self._context + + def fetch(self) -> "AccountInstance": + """ + Fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AccountInstance": + """ + Asynchronous coroutine to fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.PreviewIam.Versionless.AccountInstance {}>".format(context) + + +class AccountContext(InstanceContext): + + def __init__(self, version: Version, organization_sid: str, account_sid: str): + """ + Initialize the AccountContext + + :param version: Version that contains the resource + :param organization_sid: + :param account_sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + "account_sid": account_sid, + } + self._uri = "/{organization_sid}/Accounts/{account_sid}".format( + **self._solution + ) + + def fetch(self) -> AccountInstance: + """ + Fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AccountInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + account_sid=self._solution["account_sid"], + ) + + async def fetch_async(self) -> AccountInstance: + """ + Asynchronous coroutine to fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AccountInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + account_sid=self._solution["account_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.PreviewIam.Versionless.AccountContext {}>".format(context) + + +class AccountPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AccountInstance: + """ + Build an instance of AccountInstance + + :param payload: Payload response from the API + """ + return AccountInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.PreviewIam.Versionless.AccountPage>" + + +class AccountList(ListResource): + + def __init__(self, version: Version, organization_sid: str): + """ + Initialize the AccountList + + :param version: Version that contains the resource + :param organization_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + } + self._uri = "/{organization_sid}/Accounts".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AccountInstance]: + """ + Streams AccountInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AccountInstance]: + """ + Asynchronously streams AccountInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AccountInstance]: + """ + Lists AccountInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AccountInstance]: + """ + Asynchronously lists AccountInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AccountPage: + """ + Retrieve a single page of AccountInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AccountInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AccountPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AccountPage: + """ + Asynchronously retrieve a single page of AccountInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AccountInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AccountPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AccountPage: + """ + Retrieve a specific page of AccountInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AccountInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AccountPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AccountPage: + """ + Asynchronously retrieve a specific page of AccountInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AccountInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AccountPage(self._version, response, self._solution) + + def get(self, account_sid: str) -> AccountContext: + """ + Constructs a AccountContext + + :param account_sid: + """ + return AccountContext( + self._version, + organization_sid=self._solution["organization_sid"], + account_sid=account_sid, + ) + + def __call__(self, account_sid: str) -> AccountContext: + """ + Constructs a AccountContext + + :param account_sid: + """ + return AccountContext( + self._version, + organization_sid=self._solution["organization_sid"], + account_sid=account_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.PreviewIam.Versionless.AccountList>" diff --git a/twilio/rest/preview_iam/versionless/organization/role_assignment.py b/twilio/rest/preview_iam/versionless/organization/role_assignment.py new file mode 100644 index 0000000000..9d356f2c7c --- /dev/null +++ b/twilio/rest/preview_iam/versionless/organization/role_assignment.py @@ -0,0 +1,574 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RoleAssignmentInstance(InstanceResource): + + class PublicApiCreateRoleAssignmentRequest(object): + """ + :ivar role_sid: Twilio Role Sid representing assigned role + :ivar scope: Twilio Sid representing scope of this assignment + :ivar identity: Twilio Sid representing identity of this assignment + """ + + def __init__(self, payload: Dict[str, Any]): + + self.role_sid: Optional[str] = payload.get("role_sid") + self.scope: Optional[str] = payload.get("scope") + self.identity: Optional[str] = payload.get("identity") + + def to_dict(self): + return { + "role_sid": self.role_sid, + "scope": self.scope, + "identity": self.identity, + } + + """ + :ivar sid: Twilio Role Assignment Sid representing this role assignment + :ivar role_sid: Twilio Role Sid representing assigned role + :ivar scope: Twilio Sid representing identity of this assignment + :ivar identity: Twilio Sid representing scope of this assignment + :ivar code: Twilio-specific error code + :ivar message: Error message + :ivar more_info: Link to Error Code References + :ivar status: HTTP response status code + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + organization_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.role_sid: Optional[str] = payload.get("role_sid") + self.scope: Optional[str] = payload.get("scope") + self.identity: Optional[str] = payload.get("identity") + self.code: Optional[int] = payload.get("code") + self.message: Optional[str] = payload.get("message") + self.more_info: Optional[str] = payload.get("moreInfo") + self.status: Optional[int] = payload.get("status") + + self._solution = { + "organization_sid": organization_sid, + "sid": sid or self.sid, + } + self._context: Optional[RoleAssignmentContext] = None + + @property + def _proxy(self) -> "RoleAssignmentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoleAssignmentContext for this RoleAssignmentInstance + """ + if self._context is None: + self._context = RoleAssignmentContext( + self._version, + organization_sid=self._solution["organization_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RoleAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.PreviewIam.Versionless.RoleAssignmentInstance {}>".format( + context + ) + + +class RoleAssignmentContext(InstanceContext): + + class PublicApiCreateRoleAssignmentRequest(object): + """ + :ivar role_sid: Twilio Role Sid representing assigned role + :ivar scope: Twilio Sid representing scope of this assignment + :ivar identity: Twilio Sid representing identity of this assignment + """ + + def __init__(self, payload: Dict[str, Any]): + + self.role_sid: Optional[str] = payload.get("role_sid") + self.scope: Optional[str] = payload.get("scope") + self.identity: Optional[str] = payload.get("identity") + + def to_dict(self): + return { + "role_sid": self.role_sid, + "scope": self.scope, + "identity": self.identity, + } + + def __init__(self, version: Version, organization_sid: str, sid: str): + """ + Initialize the RoleAssignmentContext + + :param version: Version that contains the resource + :param organization_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + "sid": sid, + } + self._uri = "/{organization_sid}/RoleAssignments/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RoleAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.PreviewIam.Versionless.RoleAssignmentContext {}>".format( + context + ) + + +class RoleAssignmentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoleAssignmentInstance: + """ + Build an instance of RoleAssignmentInstance + + :param payload: Payload response from the API + """ + return RoleAssignmentInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.PreviewIam.Versionless.RoleAssignmentPage>" + + +class RoleAssignmentList(ListResource): + + class PublicApiCreateRoleAssignmentRequest(object): + """ + :ivar role_sid: Twilio Role Sid representing assigned role + :ivar scope: Twilio Sid representing scope of this assignment + :ivar identity: Twilio Sid representing identity of this assignment + """ + + def __init__(self, payload: Dict[str, Any]): + + self.role_sid: Optional[str] = payload.get("role_sid") + self.scope: Optional[str] = payload.get("scope") + self.identity: Optional[str] = payload.get("identity") + + def to_dict(self): + return { + "role_sid": self.role_sid, + "scope": self.scope, + "identity": self.identity, + } + + def __init__(self, version: Version, organization_sid: str): + """ + Initialize the RoleAssignmentList + + :param version: Version that contains the resource + :param organization_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + } + self._uri = "/{organization_sid}/RoleAssignments".format(**self._solution) + + def create( + self, + public_api_create_role_assignment_request: PublicApiCreateRoleAssignmentRequest, + ) -> RoleAssignmentInstance: + """ + Create the RoleAssignmentInstance + + :param public_api_create_role_assignment_request: + + :returns: The created RoleAssignmentInstance + """ + data = public_api_create_role_assignment_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleAssignmentInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + async def create_async( + self, + public_api_create_role_assignment_request: PublicApiCreateRoleAssignmentRequest, + ) -> RoleAssignmentInstance: + """ + Asynchronously create the RoleAssignmentInstance + + :param public_api_create_role_assignment_request: + + :returns: The created RoleAssignmentInstance + """ + data = public_api_create_role_assignment_request.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoleAssignmentInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + def stream( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoleAssignmentInstance]: + """ + Streams RoleAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str identity: + :param str scope: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(identity=identity, scope=scope, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoleAssignmentInstance]: + """ + Asynchronously streams RoleAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str identity: + :param str scope: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + identity=identity, scope=scope, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleAssignmentInstance]: + """ + Lists RoleAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str identity: + :param str scope: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + identity=identity, + scope=scope, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoleAssignmentInstance]: + """ + Asynchronously lists RoleAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str identity: + :param str scope: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + identity=identity, + scope=scope, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RoleAssignmentPage: + """ + Retrieve a single page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :param identity: + :param scope: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleAssignmentInstance + """ + data = values.of( + { + "Identity": identity, + "Scope": scope, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RoleAssignmentPage(self._version, response, self._solution) + + async def page_async( + self, + identity: Union[str, object] = values.unset, + scope: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RoleAssignmentPage: + """ + Asynchronously retrieve a single page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :param identity: + :param scope: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoleAssignmentInstance + """ + data = values.of( + { + "Identity": identity, + "Scope": scope, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RoleAssignmentPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RoleAssignmentPage: + """ + Retrieve a specific page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleAssignmentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RoleAssignmentPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RoleAssignmentPage: + """ + Asynchronously retrieve a specific page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleAssignmentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RoleAssignmentPage(self._version, response, self._solution) + + def get(self, sid: str) -> RoleAssignmentContext: + """ + Constructs a RoleAssignmentContext + + :param sid: + """ + return RoleAssignmentContext( + self._version, organization_sid=self._solution["organization_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RoleAssignmentContext: + """ + Constructs a RoleAssignmentContext + + :param sid: + """ + return RoleAssignmentContext( + self._version, organization_sid=self._solution["organization_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.PreviewIam.Versionless.RoleAssignmentList>" diff --git a/twilio/rest/preview_iam/versionless/organization/user.py b/twilio/rest/preview_iam/versionless/organization/user.py new file mode 100644 index 0000000000..166f76b421 --- /dev/null +++ b/twilio/rest/preview_iam/versionless/organization/user.py @@ -0,0 +1,1050 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UserInstance(InstanceResource): + + class ScimEmailAddress(object): + """ + :ivar primary: Indicates if this email address is the primary one + :ivar value: The actual email address value + :ivar type: The type of email address (e.g., work, home, etc.) + """ + + def __init__(self, payload: Dict[str, Any]): + + self.primary: Optional[bool] = payload.get("primary") + self.value: Optional[str] = payload.get("value") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "primary": self.primary, + "value": self.value, + "type": self.type, + } + + class ScimMeta(object): + """ + :ivar resource_type: Indicates the type of the resource + :ivar created: The date and time when the resource was created in the system + :ivar last_modified: The date and time when the resource was last modified + :ivar version: A version identifier for the resource. This can be used to manage resource versioning and concurrency control. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.resource_type: Optional[str] = payload.get("resource_type") + self.created: Optional[datetime] = payload.get("created") + self.last_modified: Optional[datetime] = payload.get("last_modified") + self.version: Optional[str] = payload.get("version") + + def to_dict(self): + return { + "resource_type": self.resource_type, + "created": self.created, + "last_modified": self.last_modified, + "version": self.version, + } + + class ScimName(object): + """ + :ivar given_name: The user's first or given name + :ivar family_name: The user's last or family name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.given_name: Optional[str] = payload.get("given_name") + self.family_name: Optional[str] = payload.get("family_name") + + def to_dict(self): + return { + "given_name": self.given_name, + "family_name": self.family_name, + } + + class ScimUser(object): + """ + :ivar id: Unique Twilio user sid + :ivar external_id: External unique resource id defined by provisioning client + :ivar user_name: Unique username, MUST be same as primary email address + :ivar display_name: User friendly display name + :ivar name: + :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + :ivar active: Indicates whether the user is active + :ivar locale: User's locale + :ivar timezone: User's time zone + :ivar schemas: An array of URIs that indicate the schemas supported for this user resource + :ivar meta: + :ivar detail: A human-readable description of the error + :ivar scim_type: A scimType error code as defined in RFC7644 + :ivar status: Http status code + :ivar code: Twilio-specific error code + :ivar more_info: Link to Error Code References + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.external_id: Optional[str] = payload.get("external_id") + self.user_name: Optional[str] = payload.get("user_name") + self.display_name: Optional[str] = payload.get("display_name") + self.name: Optional[UserList.ScimName] = payload.get("name") + self.emails: Optional[List[UserList.ScimEmailAddress]] = payload.get( + "emails" + ) + self.active: Optional[bool] = payload.get("active") + self.locale: Optional[str] = payload.get("locale") + self.timezone: Optional[str] = payload.get("timezone") + self.schemas: Optional[List[str]] = payload.get("schemas") + self.meta: Optional[UserList.ScimMeta] = payload.get("meta") + self.detail: Optional[str] = payload.get("detail") + self.scim_type: Optional[str] = payload.get("scim_type") + self.status: Optional[str] = payload.get("status") + self.code: Optional[int] = payload.get("code") + self.more_info: Optional[str] = payload.get("more_info") + + def to_dict(self): + return { + "id": self.id, + "externalId": self.external_id, + "userName": self.user_name, + "displayName": self.display_name, + "name": self.name.to_dict() if self.name is not None else None, + "emails": ( + [emails.to_dict() for emails in self.emails] + if self.emails is not None + else None + ), + "active": self.active, + "locale": self.locale, + "timezone": self.timezone, + "schemas": self.schemas, + "meta": self.meta.to_dict() if self.meta is not None else None, + "detail": self.detail, + "scimType": self.scim_type, + "status": self.status, + "code": self.code, + "moreInfo": self.more_info, + } + + """ + :ivar id: Unique Twilio user sid + :ivar external_id: External unique resource id defined by provisioning client + :ivar user_name: Unique username, MUST be same as primary email address + :ivar display_name: User friendly display name + :ivar name: + :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + :ivar active: Indicates whether the user is active + :ivar locale: User's locale + :ivar timezone: User's time zone + :ivar schemas: An array of URIs that indicate the schemas supported for this user resource + :ivar meta: + :ivar detail: A human-readable description of the error + :ivar scim_type: A scimType error code as defined in RFC7644 + :ivar status: Http status code + :ivar code: Twilio-specific error code + :ivar more_info: Link to Error Code References + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + organization_sid: str, + id: Optional[str] = None, + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + self.external_id: Optional[str] = payload.get("externalId") + self.user_name: Optional[str] = payload.get("userName") + self.display_name: Optional[str] = payload.get("displayName") + self.name: Optional[UserList.str] = payload.get("name") + self.emails: Optional[List[UserList.str]] = payload.get("emails") + self.active: Optional[bool] = payload.get("active") + self.locale: Optional[str] = payload.get("locale") + self.timezone: Optional[str] = payload.get("timezone") + self.schemas: Optional[List[str]] = payload.get("schemas") + self.meta: Optional[UserList.str] = payload.get("meta") + self.detail: Optional[str] = payload.get("detail") + self.scim_type: Optional[str] = payload.get("scimType") + self.status: Optional[str] = payload.get("status") + self.code: Optional[int] = payload.get("code") + self.more_info: Optional[str] = payload.get("moreInfo") + + self._solution = { + "organization_sid": organization_sid, + "id": id or self.id, + } + self._context: Optional[UserContext] = None + + @property + def _proxy(self) -> "UserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "UserInstance": + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> "UserInstance": + """ + Update the UserInstance + + :param scim_user: + :param if_match: + + :returns: The updated UserInstance + """ + return self._proxy.update( + scim_user=scim_user, + if_match=if_match, + ) + + async def update_async( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> "UserInstance": + """ + Asynchronous coroutine to update the UserInstance + + :param scim_user: + :param if_match: + + :returns: The updated UserInstance + """ + return await self._proxy.update_async( + scim_user=scim_user, + if_match=if_match, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.PreviewIam.Versionless.UserInstance {}>".format(context) + + +class UserContext(InstanceContext): + + class ScimEmailAddress(object): + """ + :ivar primary: Indicates if this email address is the primary one + :ivar value: The actual email address value + :ivar type: The type of email address (e.g., work, home, etc.) + """ + + def __init__(self, payload: Dict[str, Any]): + + self.primary: Optional[bool] = payload.get("primary") + self.value: Optional[str] = payload.get("value") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "primary": self.primary, + "value": self.value, + "type": self.type, + } + + class ScimMeta(object): + """ + :ivar resource_type: Indicates the type of the resource + :ivar created: The date and time when the resource was created in the system + :ivar last_modified: The date and time when the resource was last modified + :ivar version: A version identifier for the resource. This can be used to manage resource versioning and concurrency control. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.resource_type: Optional[str] = payload.get("resource_type") + self.created: Optional[datetime] = payload.get("created") + self.last_modified: Optional[datetime] = payload.get("last_modified") + self.version: Optional[str] = payload.get("version") + + def to_dict(self): + return { + "resource_type": self.resource_type, + "created": self.created, + "last_modified": self.last_modified, + "version": self.version, + } + + class ScimName(object): + """ + :ivar given_name: The user's first or given name + :ivar family_name: The user's last or family name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.given_name: Optional[str] = payload.get("given_name") + self.family_name: Optional[str] = payload.get("family_name") + + def to_dict(self): + return { + "given_name": self.given_name, + "family_name": self.family_name, + } + + class ScimUser(object): + """ + :ivar id: Unique Twilio user sid + :ivar external_id: External unique resource id defined by provisioning client + :ivar user_name: Unique username, MUST be same as primary email address + :ivar display_name: User friendly display name + :ivar name: + :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + :ivar active: Indicates whether the user is active + :ivar locale: User's locale + :ivar timezone: User's time zone + :ivar schemas: An array of URIs that indicate the schemas supported for this user resource + :ivar meta: + :ivar detail: A human-readable description of the error + :ivar scim_type: A scimType error code as defined in RFC7644 + :ivar status: Http status code + :ivar code: Twilio-specific error code + :ivar more_info: Link to Error Code References + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.external_id: Optional[str] = payload.get("external_id") + self.user_name: Optional[str] = payload.get("user_name") + self.display_name: Optional[str] = payload.get("display_name") + self.name: Optional[UserList.ScimName] = payload.get("name") + self.emails: Optional[List[UserList.ScimEmailAddress]] = payload.get( + "emails" + ) + self.active: Optional[bool] = payload.get("active") + self.locale: Optional[str] = payload.get("locale") + self.timezone: Optional[str] = payload.get("timezone") + self.schemas: Optional[List[str]] = payload.get("schemas") + self.meta: Optional[UserList.ScimMeta] = payload.get("meta") + self.detail: Optional[str] = payload.get("detail") + self.scim_type: Optional[str] = payload.get("scim_type") + self.status: Optional[str] = payload.get("status") + self.code: Optional[int] = payload.get("code") + self.more_info: Optional[str] = payload.get("more_info") + + def to_dict(self): + return { + "id": self.id, + "externalId": self.external_id, + "userName": self.user_name, + "displayName": self.display_name, + "name": self.name.to_dict() if self.name is not None else None, + "emails": ( + [emails.to_dict() for emails in self.emails] + if self.emails is not None + else None + ), + "active": self.active, + "locale": self.locale, + "timezone": self.timezone, + "schemas": self.schemas, + "meta": self.meta.to_dict() if self.meta is not None else None, + "detail": self.detail, + "scimType": self.scim_type, + "status": self.status, + "code": self.code, + "moreInfo": self.more_info, + } + + def __init__(self, version: Version, organization_sid: str, id: str): + """ + Initialize the UserContext + + :param version: Version that contains the resource + :param organization_sid: + :param id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + "id": id, + } + self._uri = "/{organization_sid}/scim/Users/{id}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> UserInstance: + """ + Fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + async def fetch_async(self) -> UserInstance: + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched UserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + def update( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> UserInstance: + """ + Update the UserInstance + + :param scim_user: + :param if_match: + + :returns: The updated UserInstance + """ + data = scim_user.to_dict() + + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/json" + + headers["Content-Type"] = "application/scim+json" + + headers["Accept"] = "application/scim+json" + + payload = self._version.update( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + async def update_async( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> UserInstance: + """ + Asynchronous coroutine to update the UserInstance + + :param scim_user: + :param if_match: + + :returns: The updated UserInstance + """ + data = scim_user.to_dict() + + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/json" + + headers["Content-Type"] = "application/scim+json" + + headers["Accept"] = "application/scim+json" + + payload = await self._version.update_async( + method="PUT", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.PreviewIam.Versionless.UserContext {}>".format(context) + + +class UserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UserInstance: + """ + Build an instance of UserInstance + + :param payload: Payload response from the API + """ + return UserInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.PreviewIam.Versionless.UserPage>" + + +class UserList(ListResource): + + class ScimEmailAddress(object): + """ + :ivar primary: Indicates if this email address is the primary one + :ivar value: The actual email address value + :ivar type: The type of email address (e.g., work, home, etc.) + """ + + def __init__(self, payload: Dict[str, Any]): + + self.primary: Optional[bool] = payload.get("primary") + self.value: Optional[str] = payload.get("value") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "primary": self.primary, + "value": self.value, + "type": self.type, + } + + class ScimMeta(object): + """ + :ivar resource_type: Indicates the type of the resource + :ivar created: The date and time when the resource was created in the system + :ivar last_modified: The date and time when the resource was last modified + :ivar version: A version identifier for the resource. This can be used to manage resource versioning and concurrency control. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.resource_type: Optional[str] = payload.get("resource_type") + self.created: Optional[datetime] = payload.get("created") + self.last_modified: Optional[datetime] = payload.get("last_modified") + self.version: Optional[str] = payload.get("version") + + def to_dict(self): + return { + "resource_type": self.resource_type, + "created": self.created, + "last_modified": self.last_modified, + "version": self.version, + } + + class ScimName(object): + """ + :ivar given_name: The user's first or given name + :ivar family_name: The user's last or family name + """ + + def __init__(self, payload: Dict[str, Any]): + + self.given_name: Optional[str] = payload.get("given_name") + self.family_name: Optional[str] = payload.get("family_name") + + def to_dict(self): + return { + "given_name": self.given_name, + "family_name": self.family_name, + } + + class ScimUser(object): + """ + :ivar id: Unique Twilio user sid + :ivar external_id: External unique resource id defined by provisioning client + :ivar user_name: Unique username, MUST be same as primary email address + :ivar display_name: User friendly display name + :ivar name: + :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + :ivar active: Indicates whether the user is active + :ivar locale: User's locale + :ivar timezone: User's time zone + :ivar schemas: An array of URIs that indicate the schemas supported for this user resource + :ivar meta: + :ivar detail: A human-readable description of the error + :ivar scim_type: A scimType error code as defined in RFC7644 + :ivar status: Http status code + :ivar code: Twilio-specific error code + :ivar more_info: Link to Error Code References + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.external_id: Optional[str] = payload.get("external_id") + self.user_name: Optional[str] = payload.get("user_name") + self.display_name: Optional[str] = payload.get("display_name") + self.name: Optional[UserList.ScimName] = payload.get("name") + self.emails: Optional[List[UserList.ScimEmailAddress]] = payload.get( + "emails" + ) + self.active: Optional[bool] = payload.get("active") + self.locale: Optional[str] = payload.get("locale") + self.timezone: Optional[str] = payload.get("timezone") + self.schemas: Optional[List[str]] = payload.get("schemas") + self.meta: Optional[UserList.ScimMeta] = payload.get("meta") + self.detail: Optional[str] = payload.get("detail") + self.scim_type: Optional[str] = payload.get("scim_type") + self.status: Optional[str] = payload.get("status") + self.code: Optional[int] = payload.get("code") + self.more_info: Optional[str] = payload.get("more_info") + + def to_dict(self): + return { + "id": self.id, + "externalId": self.external_id, + "userName": self.user_name, + "displayName": self.display_name, + "name": self.name.to_dict() if self.name is not None else None, + "emails": ( + [emails.to_dict() for emails in self.emails] + if self.emails is not None + else None + ), + "active": self.active, + "locale": self.locale, + "timezone": self.timezone, + "schemas": self.schemas, + "meta": self.meta.to_dict() if self.meta is not None else None, + "detail": self.detail, + "scimType": self.scim_type, + "status": self.status, + "code": self.code, + "moreInfo": self.more_info, + } + + def __init__(self, version: Version, organization_sid: str): + """ + Initialize the UserList + + :param version: Version that contains the resource + :param organization_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + } + self._uri = "/{organization_sid}/scim/Users".format(**self._solution) + + def create(self, scim_user: ScimUser) -> UserInstance: + """ + Create the UserInstance + + :param scim_user: + + :returns: The created UserInstance + """ + data = scim_user.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Content-Type"] = "application/scim+json" + + headers["Accept"] = "application/scim+json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + async def create_async(self, scim_user: ScimUser) -> UserInstance: + """ + Asynchronously create the UserInstance + + :param scim_user: + + :returns: The created UserInstance + """ + data = scim_user.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Content-Type"] = "application/scim+json" + + headers["Accept"] = "application/scim+json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return UserInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + def stream( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserInstance]: + """ + Streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str filter: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(filter=filter, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserInstance]: + """ + Asynchronously streams UserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str filter: + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(filter=filter, page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str filter: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + filter=filter, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Asynchronously lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str filter: + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + filter=filter, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + filter: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param filter: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "filter": filter, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/scim+json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + async def page_async( + self, + filter: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :param filter: + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UserInstance + """ + data = values.of( + { + "filter": filter, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/scim+json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UserPage: + """ + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UserPage: + """ + Asynchronously retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserPage(self._version, response, self._solution) + + def get(self, id: str) -> UserContext: + """ + Constructs a UserContext + + :param id: + """ + return UserContext( + self._version, organization_sid=self._solution["organization_sid"], id=id + ) + + def __call__(self, id: str) -> UserContext: + """ + Constructs a UserContext + + :param id: + """ + return UserContext( + self._version, organization_sid=self._solution["organization_sid"], id=id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.PreviewIam.Versionless.UserList>" diff --git a/twilio/rest/pricing/PricingBase.py b/twilio/rest/pricing/PricingBase.py new file mode 100644 index 0000000000..cf624e1867 --- /dev/null +++ b/twilio/rest/pricing/PricingBase.py @@ -0,0 +1,55 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.pricing.v1 import V1 +from twilio.rest.pricing.v2 import V2 + + +class PricingBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Pricing Domain + + :returns: Domain for Pricing + """ + super().__init__(twilio, "https://pricing.twilio.com") + self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Pricing + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Pricing + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Pricing>" diff --git a/twilio/rest/pricing/__init__.py b/twilio/rest/pricing/__init__.py new file mode 100644 index 0000000000..91da8751d9 --- /dev/null +++ b/twilio/rest/pricing/__init__.py @@ -0,0 +1,55 @@ +from warnings import warn + +from twilio.rest.pricing.PricingBase import PricingBase +from twilio.rest.pricing.v1.messaging import MessagingList +from twilio.rest.pricing.v1.phone_number import PhoneNumberList +from twilio.rest.pricing.v2.country import CountryList +from twilio.rest.pricing.v2.number import NumberList +from twilio.rest.pricing.v2.voice import VoiceList + + +class Pricing(PricingBase): + @property + def messaging(self) -> MessagingList: + warn( + "messaging is deprecated. Use v1.messaging instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.messaging + + @property + def phone_numbers(self) -> PhoneNumberList: + warn( + "phone_numbers is deprecated. Use v1.phone_numbers instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.phone_numbers + + @property + def voice(self) -> VoiceList: + warn( + "voice is deprecated. Use v2.voice instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.voice + + @property + def countries(self) -> CountryList: + warn( + "countries is deprecated. Use v2.countries instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.countries + + @property + def numbers(self) -> NumberList: + warn( + "numbers is deprecated. Use v2.numbers instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.numbers diff --git a/twilio/rest/pricing/v1/__init__.py b/twilio/rest/pricing/v1/__init__.py new file mode 100644 index 0000000000..ba8b65885d --- /dev/null +++ b/twilio/rest/pricing/v1/__init__.py @@ -0,0 +1,59 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.pricing.v1.messaging import MessagingList +from twilio.rest.pricing.v1.phone_number import PhoneNumberList +from twilio.rest.pricing.v1.voice import VoiceList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Pricing + + :param domain: The Twilio.pricing domain + """ + super().__init__(domain, "v1") + self._messaging: Optional[MessagingList] = None + self._phone_numbers: Optional[PhoneNumberList] = None + self._voice: Optional[VoiceList] = None + + @property + def messaging(self) -> MessagingList: + if self._messaging is None: + self._messaging = MessagingList(self) + return self._messaging + + @property + def phone_numbers(self) -> PhoneNumberList: + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList(self) + return self._phone_numbers + + @property + def voice(self) -> VoiceList: + if self._voice is None: + self._voice = VoiceList(self) + return self._voice + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Pricing.V1>" diff --git a/twilio/rest/pricing/v1/messaging/__init__.py b/twilio/rest/pricing/v1/messaging/__init__.py new file mode 100644 index 0000000000..df5c148b81 --- /dev/null +++ b/twilio/rest/pricing/v1/messaging/__init__.py @@ -0,0 +1,54 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.pricing.v1.messaging.country import CountryList + + +class MessagingList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the MessagingList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Messaging" + + self._countries: Optional[CountryList] = None + + @property + def countries(self) -> CountryList: + """ + Access the countries + """ + if self._countries is None: + self._countries = CountryList(self._version) + return self._countries + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Pricing.V1.MessagingList>" diff --git a/twilio/rest/pricing/v1/messaging/country.py b/twilio/rest/pricing/v1/messaging/country.py new file mode 100644 index 0000000000..49360cd85c --- /dev/null +++ b/twilio/rest/pricing/v1/messaging/country.py @@ -0,0 +1,415 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CountryInstance(InstanceResource): + """ + :ivar country: The name of the country. + :ivar iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + :ivar outbound_sms_prices: The list of [OutboundSMSPrice](https://www.twilio.com/docs/sms/api/pricing#outbound-sms-price) records that represent the price to send a message for each MCC/MNC applicable in this country. + :ivar inbound_sms_prices: The list of [InboundPrice](https://www.twilio.com/docs/sms/api/pricing#inbound-price) records that describe the price to receive an inbound SMS to the different Twilio phone number types supported in this country + :ivar price_unit: The currency in which prices are measured, specified in [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + iso_country: Optional[str] = None, + ): + super().__init__(version) + + self.country: Optional[str] = payload.get("country") + self.iso_country: Optional[str] = payload.get("iso_country") + self.outbound_sms_prices: Optional[List[str]] = payload.get( + "outbound_sms_prices" + ) + self.inbound_sms_prices: Optional[List[str]] = payload.get("inbound_sms_prices") + self.price_unit: Optional[str] = payload.get("price_unit") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "iso_country": iso_country or self.iso_country, + } + self._context: Optional[CountryContext] = None + + @property + def _proxy(self) -> "CountryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CountryContext for this CountryInstance + """ + if self._context is None: + self._context = CountryContext( + self._version, + iso_country=self._solution["iso_country"], + ) + return self._context + + def fetch(self) -> "CountryInstance": + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CountryInstance": + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Pricing.V1.CountryInstance {}>".format(context) + + +class CountryContext(InstanceContext): + + def __init__(self, version: Version, iso_country: str): + """ + Initialize the CountryContext + + :param version: Version that contains the resource + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "iso_country": iso_country, + } + self._uri = "/Messaging/Countries/{iso_country}".format(**self._solution) + + def fetch(self) -> CountryInstance: + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + async def fetch_async(self) -> CountryInstance: + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Pricing.V1.CountryContext {}>".format(context) + + +class CountryPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: + """ + Build an instance of CountryInstance + + :param payload: Payload response from the API + """ + return CountryInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Pricing.V1.CountryPage>" + + +class CountryList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CountryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Messaging/Countries" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: + """ + Streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CountryInstance]: + """ + Asynchronously streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Asynchronously lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Asynchronously retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + def get_page(self, target_url: str) -> CountryPage: + """ + Retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CountryPage: + """ + Asynchronously retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CountryPage(self._version, response) + + def get(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __call__(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Pricing.V1.CountryList>" diff --git a/twilio/rest/pricing/v1/phone_number/__init__.py b/twilio/rest/pricing/v1/phone_number/__init__.py new file mode 100644 index 0000000000..429ce9b14c --- /dev/null +++ b/twilio/rest/pricing/v1/phone_number/__init__.py @@ -0,0 +1,54 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.pricing.v1.phone_number.country import CountryList + + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PhoneNumberList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/PhoneNumbers" + + self._countries: Optional[CountryList] = None + + @property + def countries(self) -> CountryList: + """ + Access the countries + """ + if self._countries is None: + self._countries = CountryList(self._version) + return self._countries + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Pricing.V1.PhoneNumberList>" diff --git a/twilio/rest/pricing/v1/phone_number/country.py b/twilio/rest/pricing/v1/phone_number/country.py new file mode 100644 index 0000000000..2d11cd1c3e --- /dev/null +++ b/twilio/rest/pricing/v1/phone_number/country.py @@ -0,0 +1,413 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CountryInstance(InstanceResource): + """ + :ivar country: The name of the country. + :ivar iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + :ivar phone_number_prices: The list of [PhoneNumberPrice](https://www.twilio.com/docs/phone-numbers/pricing#phone-number-price) records. + :ivar price_unit: The currency in which prices are measured, specified in [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + iso_country: Optional[str] = None, + ): + super().__init__(version) + + self.country: Optional[str] = payload.get("country") + self.iso_country: Optional[str] = payload.get("iso_country") + self.phone_number_prices: Optional[List[str]] = payload.get( + "phone_number_prices" + ) + self.price_unit: Optional[str] = payload.get("price_unit") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "iso_country": iso_country or self.iso_country, + } + self._context: Optional[CountryContext] = None + + @property + def _proxy(self) -> "CountryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CountryContext for this CountryInstance + """ + if self._context is None: + self._context = CountryContext( + self._version, + iso_country=self._solution["iso_country"], + ) + return self._context + + def fetch(self) -> "CountryInstance": + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CountryInstance": + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Pricing.V1.CountryInstance {}>".format(context) + + +class CountryContext(InstanceContext): + + def __init__(self, version: Version, iso_country: str): + """ + Initialize the CountryContext + + :param version: Version that contains the resource + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "iso_country": iso_country, + } + self._uri = "/PhoneNumbers/Countries/{iso_country}".format(**self._solution) + + def fetch(self) -> CountryInstance: + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + async def fetch_async(self) -> CountryInstance: + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Pricing.V1.CountryContext {}>".format(context) + + +class CountryPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: + """ + Build an instance of CountryInstance + + :param payload: Payload response from the API + """ + return CountryInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Pricing.V1.CountryPage>" + + +class CountryList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CountryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/PhoneNumbers/Countries" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: + """ + Streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CountryInstance]: + """ + Asynchronously streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Asynchronously lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Asynchronously retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + def get_page(self, target_url: str) -> CountryPage: + """ + Retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CountryPage: + """ + Asynchronously retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CountryPage(self._version, response) + + def get(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __call__(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Pricing.V1.CountryList>" diff --git a/twilio/rest/pricing/v1/voice/__init__.py b/twilio/rest/pricing/v1/voice/__init__.py new file mode 100644 index 0000000000..a801a30089 --- /dev/null +++ b/twilio/rest/pricing/v1/voice/__init__.py @@ -0,0 +1,65 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.pricing.v1.voice.country import CountryList +from twilio.rest.pricing.v1.voice.number import NumberList + + +class VoiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the VoiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Voice" + + self._countries: Optional[CountryList] = None + self._numbers: Optional[NumberList] = None + + @property + def countries(self) -> CountryList: + """ + Access the countries + """ + if self._countries is None: + self._countries = CountryList(self._version) + return self._countries + + @property + def numbers(self) -> NumberList: + """ + Access the numbers + """ + if self._numbers is None: + self._numbers = NumberList(self._version) + return self._numbers + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Pricing.V1.VoiceList>" diff --git a/twilio/rest/pricing/v1/voice/country.py b/twilio/rest/pricing/v1/voice/country.py new file mode 100644 index 0000000000..7fb0da883a --- /dev/null +++ b/twilio/rest/pricing/v1/voice/country.py @@ -0,0 +1,417 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CountryInstance(InstanceResource): + """ + :ivar country: The name of the country. + :ivar iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + :ivar outbound_prefix_prices: The list of OutboundPrefixPrice records, which include a list of the `prefixes`, the `friendly_name`, `base_price`, and the `current_price` for those prefixes. + :ivar inbound_call_prices: The list of [InboundCallPrice](https://www.twilio.com/docs/voice/pricing#inbound-call-price) records. + :ivar price_unit: The currency in which prices are measured, specified in [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + iso_country: Optional[str] = None, + ): + super().__init__(version) + + self.country: Optional[str] = payload.get("country") + self.iso_country: Optional[str] = payload.get("iso_country") + self.outbound_prefix_prices: Optional[List[str]] = payload.get( + "outbound_prefix_prices" + ) + self.inbound_call_prices: Optional[List[str]] = payload.get( + "inbound_call_prices" + ) + self.price_unit: Optional[str] = payload.get("price_unit") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "iso_country": iso_country or self.iso_country, + } + self._context: Optional[CountryContext] = None + + @property + def _proxy(self) -> "CountryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CountryContext for this CountryInstance + """ + if self._context is None: + self._context = CountryContext( + self._version, + iso_country=self._solution["iso_country"], + ) + return self._context + + def fetch(self) -> "CountryInstance": + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CountryInstance": + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Pricing.V1.CountryInstance {}>".format(context) + + +class CountryContext(InstanceContext): + + def __init__(self, version: Version, iso_country: str): + """ + Initialize the CountryContext + + :param version: Version that contains the resource + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "iso_country": iso_country, + } + self._uri = "/Voice/Countries/{iso_country}".format(**self._solution) + + def fetch(self) -> CountryInstance: + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + async def fetch_async(self) -> CountryInstance: + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Pricing.V1.CountryContext {}>".format(context) + + +class CountryPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: + """ + Build an instance of CountryInstance + + :param payload: Payload response from the API + """ + return CountryInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Pricing.V1.CountryPage>" + + +class CountryList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CountryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Voice/Countries" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: + """ + Streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CountryInstance]: + """ + Asynchronously streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Asynchronously lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Asynchronously retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + def get_page(self, target_url: str) -> CountryPage: + """ + Retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CountryPage: + """ + Asynchronously retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CountryPage(self._version, response) + + def get(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __call__(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Pricing.V1.CountryList>" diff --git a/twilio/rest/pricing/v1/voice/number.py b/twilio/rest/pricing/v1/voice/number.py new file mode 100644 index 0000000000..5bff8cd5d6 --- /dev/null +++ b/twilio/rest/pricing/v1/voice/number.py @@ -0,0 +1,197 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NumberInstance(InstanceResource): + """ + :ivar number: The phone number. + :ivar country: The name of the country. + :ivar iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + :ivar outbound_call_price: + :ivar inbound_call_price: + :ivar price_unit: The currency in which prices are measured, specified in [ISO 4127](http://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], number: Optional[str] = None + ): + super().__init__(version) + + self.number: Optional[str] = payload.get("number") + self.country: Optional[str] = payload.get("country") + self.iso_country: Optional[str] = payload.get("iso_country") + self.outbound_call_price: Optional[str] = payload.get("outbound_call_price") + self.inbound_call_price: Optional[str] = payload.get("inbound_call_price") + self.price_unit: Optional[str] = payload.get("price_unit") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "number": number or self.number, + } + self._context: Optional[NumberContext] = None + + @property + def _proxy(self) -> "NumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NumberContext for this NumberInstance + """ + if self._context is None: + self._context = NumberContext( + self._version, + number=self._solution["number"], + ) + return self._context + + def fetch(self) -> "NumberInstance": + """ + Fetch the NumberInstance + + + :returns: The fetched NumberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "NumberInstance": + """ + Asynchronous coroutine to fetch the NumberInstance + + + :returns: The fetched NumberInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Pricing.V1.NumberInstance {}>".format(context) + + +class NumberContext(InstanceContext): + + def __init__(self, version: Version, number: str): + """ + Initialize the NumberContext + + :param version: Version that contains the resource + :param number: The phone number to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "number": number, + } + self._uri = "/Voice/Numbers/{number}".format(**self._solution) + + def fetch(self) -> NumberInstance: + """ + Fetch the NumberInstance + + + :returns: The fetched NumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return NumberInstance( + self._version, + payload, + number=self._solution["number"], + ) + + async def fetch_async(self) -> NumberInstance: + """ + Asynchronous coroutine to fetch the NumberInstance + + + :returns: The fetched NumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return NumberInstance( + self._version, + payload, + number=self._solution["number"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Pricing.V1.NumberContext {}>".format(context) + + +class NumberList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the NumberList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, number: str) -> NumberContext: + """ + Constructs a NumberContext + + :param number: The phone number to fetch. + """ + return NumberContext(self._version, number=number) + + def __call__(self, number: str) -> NumberContext: + """ + Constructs a NumberContext + + :param number: The phone number to fetch. + """ + return NumberContext(self._version, number=number) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Pricing.V1.NumberList>" diff --git a/twilio/rest/pricing/v2/__init__.py b/twilio/rest/pricing/v2/__init__.py new file mode 100644 index 0000000000..d0fd67f737 --- /dev/null +++ b/twilio/rest/pricing/v2/__init__.py @@ -0,0 +1,59 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.pricing.v2.country import CountryList +from twilio.rest.pricing.v2.number import NumberList +from twilio.rest.pricing.v2.voice import VoiceList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Pricing + + :param domain: The Twilio.pricing domain + """ + super().__init__(domain, "v2") + self._countries: Optional[CountryList] = None + self._numbers: Optional[NumberList] = None + self._voice: Optional[VoiceList] = None + + @property + def countries(self) -> CountryList: + if self._countries is None: + self._countries = CountryList(self) + return self._countries + + @property + def numbers(self) -> NumberList: + if self._numbers is None: + self._numbers = NumberList(self) + return self._numbers + + @property + def voice(self) -> VoiceList: + if self._voice is None: + self._voice = VoiceList(self) + return self._voice + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Pricing.V2>" diff --git a/twilio/rest/pricing/v2/country.py b/twilio/rest/pricing/v2/country.py new file mode 100644 index 0000000000..30672235a8 --- /dev/null +++ b/twilio/rest/pricing/v2/country.py @@ -0,0 +1,417 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CountryInstance(InstanceResource): + """ + :ivar country: The name of the country. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + :ivar terminating_prefix_prices: The list of [TerminatingPrefixPrice](https://www.twilio.com/docs/voice/pricing#outbound-prefix-price-with-origin) records. + :ivar originating_call_prices: The list of [OriginatingCallPrice](https://www.twilio.com/docs/voice/pricing#inbound-call-price) records. + :ivar price_unit: The currency in which prices are measured, specified in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + iso_country: Optional[str] = None, + ): + super().__init__(version) + + self.country: Optional[str] = payload.get("country") + self.iso_country: Optional[str] = payload.get("iso_country") + self.terminating_prefix_prices: Optional[List[str]] = payload.get( + "terminating_prefix_prices" + ) + self.originating_call_prices: Optional[List[str]] = payload.get( + "originating_call_prices" + ) + self.price_unit: Optional[str] = payload.get("price_unit") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "iso_country": iso_country or self.iso_country, + } + self._context: Optional[CountryContext] = None + + @property + def _proxy(self) -> "CountryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CountryContext for this CountryInstance + """ + if self._context is None: + self._context = CountryContext( + self._version, + iso_country=self._solution["iso_country"], + ) + return self._context + + def fetch(self) -> "CountryInstance": + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CountryInstance": + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Pricing.V2.CountryInstance {}>".format(context) + + +class CountryContext(InstanceContext): + + def __init__(self, version: Version, iso_country: str): + """ + Initialize the CountryContext + + :param version: Version that contains the resource + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the origin-based voice pricing information to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "iso_country": iso_country, + } + self._uri = "/Trunking/Countries/{iso_country}".format(**self._solution) + + def fetch(self) -> CountryInstance: + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + async def fetch_async(self) -> CountryInstance: + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Pricing.V2.CountryContext {}>".format(context) + + +class CountryPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: + """ + Build an instance of CountryInstance + + :param payload: Payload response from the API + """ + return CountryInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Pricing.V2.CountryPage>" + + +class CountryList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CountryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Trunking/Countries" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: + """ + Streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CountryInstance]: + """ + Asynchronously streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Asynchronously lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Asynchronously retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + def get_page(self, target_url: str) -> CountryPage: + """ + Retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CountryPage: + """ + Asynchronously retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CountryPage(self._version, response) + + def get(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the origin-based voice pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __call__(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the origin-based voice pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Pricing.V2.CountryList>" diff --git a/twilio/rest/pricing/v2/number.py b/twilio/rest/pricing/v2/number.py new file mode 100644 index 0000000000..1dead39347 --- /dev/null +++ b/twilio/rest/pricing/v2/number.py @@ -0,0 +1,236 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NumberInstance(InstanceResource): + """ + :ivar destination_number: The destination phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar origination_number: The origination phone number in [[E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar country: The name of the country. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :ivar terminating_prefix_prices: + :ivar originating_call_price: + :ivar price_unit: The currency in which prices are measured, specified in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + destination_number: Optional[str] = None, + ): + super().__init__(version) + + self.destination_number: Optional[str] = payload.get("destination_number") + self.origination_number: Optional[str] = payload.get("origination_number") + self.country: Optional[str] = payload.get("country") + self.iso_country: Optional[str] = payload.get("iso_country") + self.terminating_prefix_prices: Optional[List[str]] = payload.get( + "terminating_prefix_prices" + ) + self.originating_call_price: Optional[str] = payload.get( + "originating_call_price" + ) + self.price_unit: Optional[str] = payload.get("price_unit") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "destination_number": destination_number or self.destination_number, + } + self._context: Optional[NumberContext] = None + + @property + def _proxy(self) -> "NumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NumberContext for this NumberInstance + """ + if self._context is None: + self._context = NumberContext( + self._version, + destination_number=self._solution["destination_number"], + ) + return self._context + + def fetch( + self, origination_number: Union[str, object] = values.unset + ) -> "NumberInstance": + """ + Fetch the NumberInstance + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: The fetched NumberInstance + """ + return self._proxy.fetch( + origination_number=origination_number, + ) + + async def fetch_async( + self, origination_number: Union[str, object] = values.unset + ) -> "NumberInstance": + """ + Asynchronous coroutine to fetch the NumberInstance + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: The fetched NumberInstance + """ + return await self._proxy.fetch_async( + origination_number=origination_number, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Pricing.V2.NumberInstance {}>".format(context) + + +class NumberContext(InstanceContext): + + def __init__(self, version: Version, destination_number: str): + """ + Initialize the NumberContext + + :param version: Version that contains the resource + :param destination_number: The destination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "destination_number": destination_number, + } + self._uri = "/Trunking/Numbers/{destination_number}".format(**self._solution) + + def fetch( + self, origination_number: Union[str, object] = values.unset + ) -> NumberInstance: + """ + Fetch the NumberInstance + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: The fetched NumberInstance + """ + + data = values.of( + { + "OriginationNumber": origination_number, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) + + async def fetch_async( + self, origination_number: Union[str, object] = values.unset + ) -> NumberInstance: + """ + Asynchronous coroutine to fetch the NumberInstance + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: The fetched NumberInstance + """ + + data = values.of( + { + "OriginationNumber": origination_number, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Pricing.V2.NumberContext {}>".format(context) + + +class NumberList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the NumberList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, destination_number: str) -> NumberContext: + """ + Constructs a NumberContext + + :param destination_number: The destination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + """ + return NumberContext(self._version, destination_number=destination_number) + + def __call__(self, destination_number: str) -> NumberContext: + """ + Constructs a NumberContext + + :param destination_number: The destination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + """ + return NumberContext(self._version, destination_number=destination_number) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Pricing.V2.NumberList>" diff --git a/twilio/rest/pricing/v2/voice/__init__.py b/twilio/rest/pricing/v2/voice/__init__.py new file mode 100644 index 0000000000..1ebbcbb644 --- /dev/null +++ b/twilio/rest/pricing/v2/voice/__init__.py @@ -0,0 +1,65 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.pricing.v2.voice.country import CountryList +from twilio.rest.pricing.v2.voice.number import NumberList + + +class VoiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the VoiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Voice" + + self._countries: Optional[CountryList] = None + self._numbers: Optional[NumberList] = None + + @property + def countries(self) -> CountryList: + """ + Access the countries + """ + if self._countries is None: + self._countries = CountryList(self._version) + return self._countries + + @property + def numbers(self) -> NumberList: + """ + Access the numbers + """ + if self._numbers is None: + self._numbers = NumberList(self._version) + return self._numbers + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Pricing.V2.VoiceList>" diff --git a/twilio/rest/pricing/v2/voice/country.py b/twilio/rest/pricing/v2/voice/country.py new file mode 100644 index 0000000000..997f368462 --- /dev/null +++ b/twilio/rest/pricing/v2/voice/country.py @@ -0,0 +1,417 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CountryInstance(InstanceResource): + """ + :ivar country: The name of the country. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + :ivar outbound_prefix_prices: The list of [OutboundPrefixPriceWithOrigin](https://www.twilio.com/docs/voice/pricing#outbound-prefix-price-with-origin) records. + :ivar inbound_call_prices: The list of [InboundCallPrice](https://www.twilio.com/docs/voice/pricing#inbound-call-price) records. + :ivar price_unit: The currency in which prices are measured, specified in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + iso_country: Optional[str] = None, + ): + super().__init__(version) + + self.country: Optional[str] = payload.get("country") + self.iso_country: Optional[str] = payload.get("iso_country") + self.outbound_prefix_prices: Optional[List[str]] = payload.get( + "outbound_prefix_prices" + ) + self.inbound_call_prices: Optional[List[str]] = payload.get( + "inbound_call_prices" + ) + self.price_unit: Optional[str] = payload.get("price_unit") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "iso_country": iso_country or self.iso_country, + } + self._context: Optional[CountryContext] = None + + @property + def _proxy(self) -> "CountryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CountryContext for this CountryInstance + """ + if self._context is None: + self._context = CountryContext( + self._version, + iso_country=self._solution["iso_country"], + ) + return self._context + + def fetch(self) -> "CountryInstance": + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CountryInstance": + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Pricing.V2.CountryInstance {}>".format(context) + + +class CountryContext(InstanceContext): + + def __init__(self, version: Version, iso_country: str): + """ + Initialize the CountryContext + + :param version: Version that contains the resource + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the origin-based voice pricing information to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "iso_country": iso_country, + } + self._uri = "/Voice/Countries/{iso_country}".format(**self._solution) + + def fetch(self) -> CountryInstance: + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + async def fetch_async(self) -> CountryInstance: + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Pricing.V2.CountryContext {}>".format(context) + + +class CountryPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: + """ + Build an instance of CountryInstance + + :param payload: Payload response from the API + """ + return CountryInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Pricing.V2.CountryPage>" + + +class CountryList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CountryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Voice/Countries" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: + """ + Streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CountryInstance]: + """ + Asynchronously streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Asynchronously lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Asynchronously retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + def get_page(self, target_url: str) -> CountryPage: + """ + Retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CountryPage: + """ + Asynchronously retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CountryPage(self._version, response) + + def get(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the origin-based voice pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __call__(self, iso_country: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the origin-based voice pricing information to fetch. + """ + return CountryContext(self._version, iso_country=iso_country) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Pricing.V2.CountryList>" diff --git a/twilio/rest/pricing/v2/voice/number.py b/twilio/rest/pricing/v2/voice/number.py new file mode 100644 index 0000000000..97a3a526ff --- /dev/null +++ b/twilio/rest/pricing/v2/voice/number.py @@ -0,0 +1,234 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Pricing + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NumberInstance(InstanceResource): + """ + :ivar destination_number: The destination phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar origination_number: The origination phone number in [[E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar country: The name of the country. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :ivar outbound_call_prices: The list of [OutboundCallPriceWithOrigin](https://www.twilio.com/docs/voice/pricing#outbound-call-price-with-origin) records. + :ivar inbound_call_price: + :ivar price_unit: The currency in which prices are measured, specified in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + destination_number: Optional[str] = None, + ): + super().__init__(version) + + self.destination_number: Optional[str] = payload.get("destination_number") + self.origination_number: Optional[str] = payload.get("origination_number") + self.country: Optional[str] = payload.get("country") + self.iso_country: Optional[str] = payload.get("iso_country") + self.outbound_call_prices: Optional[List[str]] = payload.get( + "outbound_call_prices" + ) + self.inbound_call_price: Optional[str] = payload.get("inbound_call_price") + self.price_unit: Optional[str] = payload.get("price_unit") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "destination_number": destination_number or self.destination_number, + } + self._context: Optional[NumberContext] = None + + @property + def _proxy(self) -> "NumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NumberContext for this NumberInstance + """ + if self._context is None: + self._context = NumberContext( + self._version, + destination_number=self._solution["destination_number"], + ) + return self._context + + def fetch( + self, origination_number: Union[str, object] = values.unset + ) -> "NumberInstance": + """ + Fetch the NumberInstance + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: The fetched NumberInstance + """ + return self._proxy.fetch( + origination_number=origination_number, + ) + + async def fetch_async( + self, origination_number: Union[str, object] = values.unset + ) -> "NumberInstance": + """ + Asynchronous coroutine to fetch the NumberInstance + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: The fetched NumberInstance + """ + return await self._proxy.fetch_async( + origination_number=origination_number, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Pricing.V2.NumberInstance {}>".format(context) + + +class NumberContext(InstanceContext): + + def __init__(self, version: Version, destination_number: str): + """ + Initialize the NumberContext + + :param version: Version that contains the resource + :param destination_number: The destination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "destination_number": destination_number, + } + self._uri = "/Voice/Numbers/{destination_number}".format(**self._solution) + + def fetch( + self, origination_number: Union[str, object] = values.unset + ) -> NumberInstance: + """ + Fetch the NumberInstance + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: The fetched NumberInstance + """ + + data = values.of( + { + "OriginationNumber": origination_number, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) + + async def fetch_async( + self, origination_number: Union[str, object] = values.unset + ) -> NumberInstance: + """ + Asynchronous coroutine to fetch the NumberInstance + + :param origination_number: The origination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + + :returns: The fetched NumberInstance + """ + + data = values.of( + { + "OriginationNumber": origination_number, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Pricing.V2.NumberContext {}>".format(context) + + +class NumberList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the NumberList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, destination_number: str) -> NumberContext: + """ + Constructs a NumberContext + + :param destination_number: The destination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + """ + return NumberContext(self._version, destination_number=destination_number) + + def __call__(self, destination_number: str) -> NumberContext: + """ + Constructs a NumberContext + + :param destination_number: The destination phone number, in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, for which to fetch the origin-based voice pricing information. E.164 format consists of a + followed by the country code and subscriber number. + """ + return NumberContext(self._version, destination_number=destination_number) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Pricing.V2.NumberList>" diff --git a/twilio/rest/proxy/ProxyBase.py b/twilio/rest/proxy/ProxyBase.py new file mode 100644 index 0000000000..da1baec178 --- /dev/null +++ b/twilio/rest/proxy/ProxyBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.proxy.v1 import V1 + + +class ProxyBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Proxy Domain + + :returns: Domain for Proxy + """ + super().__init__(twilio, "https://proxy.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Proxy + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Proxy>" diff --git a/twilio/rest/proxy/__init__.py b/twilio/rest/proxy/__init__.py new file mode 100644 index 0000000000..aec2a3d1af --- /dev/null +++ b/twilio/rest/proxy/__init__.py @@ -0,0 +1,15 @@ +from warnings import warn + +from twilio.rest.proxy.ProxyBase import ProxyBase +from twilio.rest.proxy.v1.service import ServiceList + + +class Proxy(ProxyBase): + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v1.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.services diff --git a/twilio/rest/proxy/v1/__init__.py b/twilio/rest/proxy/v1/__init__.py new file mode 100644 index 0000000000..83737dc0fb --- /dev/null +++ b/twilio/rest/proxy/v1/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Proxy + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.proxy.v1.service import ServiceList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Proxy + + :param domain: The Twilio.proxy domain + """ + super().__init__(domain, "v1") + self._services: Optional[ServiceList] = None + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Proxy.V1>" diff --git a/twilio/rest/proxy/v1/service/__init__.py b/twilio/rest/proxy/v1/service/__init__.py new file mode 100644 index 0000000000..ff1e7ed7d7 --- /dev/null +++ b/twilio/rest/proxy/v1/service/__init__.py @@ -0,0 +1,844 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Proxy + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.proxy.v1.service.phone_number import PhoneNumberList +from twilio.rest.proxy.v1.service.session import SessionList +from twilio.rest.proxy.v1.service.short_code import ShortCodeList + + +class ServiceInstance(InstanceResource): + + class GeoMatchLevel(object): + AREA_CODE = "area-code" + OVERLAY = "overlay" + RADIUS = "radius" + COUNTRY = "country" + + class NumberSelectionBehavior(object): + AVOID_STICKY = "avoid-sticky" + PREFER_STICKY = "prefer-sticky" + + """ + :ivar sid: The unique string that we created to identify the Service resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. Supports UTF-8 characters. **This value should not have PII.** + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + :ivar chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + :ivar callback_url: The URL we call when the interaction status changes. + :ivar default_ttl: The default `ttl` value for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :ivar number_selection_behavior: + :ivar geo_match_level: + :ivar intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :ivar out_of_session_callback_url: The URL we call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. + :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + :ivar url: The absolute URL of the Service resource. + :ivar links: The URLs of resources related to the Service. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_instance_sid: Optional[str] = payload.get("chat_instance_sid") + self.callback_url: Optional[str] = payload.get("callback_url") + self.default_ttl: Optional[int] = deserialize.integer( + payload.get("default_ttl") + ) + self.number_selection_behavior: Optional[ + "ServiceInstance.NumberSelectionBehavior" + ] = payload.get("number_selection_behavior") + self.geo_match_level: Optional["ServiceInstance.GeoMatchLevel"] = payload.get( + "geo_match_level" + ) + self.intercept_callback_url: Optional[str] = payload.get( + "intercept_callback_url" + ) + self.out_of_session_callback_url: Optional[str] = payload.get( + "out_of_session_callback_url" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + unique_name: Union[str, object] = values.unset, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + unique_name=unique_name, + default_ttl=default_ttl, + callback_url=callback_url, + geo_match_level=geo_match_level, + number_selection_behavior=number_selection_behavior, + intercept_callback_url=intercept_callback_url, + out_of_session_callback_url=out_of_session_callback_url, + chat_instance_sid=chat_instance_sid, + ) + + @property + def phone_numbers(self) -> PhoneNumberList: + """ + Access the phone_numbers + """ + return self._proxy.phone_numbers + + @property + def sessions(self) -> SessionList: + """ + Access the sessions + """ + return self._proxy.sessions + + @property + def short_codes(self) -> ShortCodeList: + """ + Access the short_codes + """ + return self._proxy.short_codes + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Proxy.V1.ServiceInstance {}>".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._phone_numbers: Optional[PhoneNumberList] = None + self._sessions: Optional[SessionList] = None + self._short_codes: Optional[ShortCodeList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + unique_name: Union[str, object] = values.unset, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "DefaultTtl": default_ttl, + "CallbackUrl": callback_url, + "GeoMatchLevel": geo_match_level, + "NumberSelectionBehavior": number_selection_behavior, + "InterceptCallbackUrl": intercept_callback_url, + "OutOfSessionCallbackUrl": out_of_session_callback_url, + "ChatInstanceSid": chat_instance_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "DefaultTtl": default_ttl, + "CallbackUrl": callback_url, + "GeoMatchLevel": geo_match_level, + "NumberSelectionBehavior": number_selection_behavior, + "InterceptCallbackUrl": intercept_callback_url, + "OutOfSessionCallbackUrl": out_of_session_callback_url, + "ChatInstanceSid": chat_instance_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def phone_numbers(self) -> PhoneNumberList: + """ + Access the phone_numbers + """ + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList( + self._version, + self._solution["sid"], + ) + return self._phone_numbers + + @property + def sessions(self) -> SessionList: + """ + Access the sessions + """ + if self._sessions is None: + self._sessions = SessionList( + self._version, + self._solution["sid"], + ) + return self._sessions + + @property + def short_codes(self) -> ShortCodeList: + """ + Access the short_codes + """ + if self._short_codes is None: + self._short_codes = ShortCodeList( + self._version, + self._solution["sid"], + ) + return self._short_codes + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Proxy.V1.ServiceContext {}>".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Proxy.V1.ServicePage>" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create( + self, + unique_name: str, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "DefaultTtl": default_ttl, + "CallbackUrl": callback_url, + "GeoMatchLevel": geo_match_level, + "NumberSelectionBehavior": number_selection_behavior, + "InterceptCallbackUrl": intercept_callback_url, + "OutOfSessionCallbackUrl": out_of_session_callback_url, + "ChatInstanceSid": chat_instance_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async( + self, + unique_name: str, + default_ttl: Union[int, object] = values.unset, + callback_url: Union[str, object] = values.unset, + geo_match_level: Union["ServiceInstance.GeoMatchLevel", object] = values.unset, + number_selection_behavior: Union[ + "ServiceInstance.NumberSelectionBehavior", object + ] = values.unset, + intercept_callback_url: Union[str, object] = values.unset, + out_of_session_callback_url: Union[str, object] = values.unset, + chat_instance_sid: Union[str, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param default_ttl: The default `ttl` value to set for Sessions created in the Service. The TTL (time to live) is measured in seconds after the Session's last create or last Interaction. The default value of `0` indicates an unlimited Session length. You can override a Session's default TTL value by setting its `ttl` value. + :param callback_url: The URL we should call when the interaction status changes. + :param geo_match_level: + :param number_selection_behavior: + :param intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. + :param out_of_session_callback_url: The URL we should call when an inbound call or SMS action occurs on a closed or non-existent Session. If your server (or a Twilio [function](https://www.twilio.com/en-us/serverless/functions)) responds with valid [TwiML](https://www.twilio.com/docs/voice/twiml), we will process it. This means it is possible, for example, to play a message for a call, send an automated text message response, or redirect a call to another Phone Number. See [Out-of-Session Callback Response Guide](https://www.twilio.com/docs/proxy/out-session-callback-response-guide) for more information. + :param chat_instance_sid: The SID of the Chat Service Instance managed by Proxy Service. The Chat Service enables Proxy to forward SMS and channel messages to this chat instance. This is a one-to-one relationship. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "DefaultTtl": default_ttl, + "CallbackUrl": callback_url, + "GeoMatchLevel": geo_match_level, + "NumberSelectionBehavior": number_selection_behavior, + "InterceptCallbackUrl": intercept_callback_url, + "OutOfSessionCallbackUrl": out_of_session_callback_url, + "ChatInstanceSid": chat_instance_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Proxy.V1.ServiceList>" diff --git a/twilio/rest/proxy/v1/service/phone_number.py b/twilio/rest/proxy/v1/service/phone_number.py new file mode 100644 index 0000000000..3c8517cedd --- /dev/null +++ b/twilio/rest/proxy/v1/service/phone_number.py @@ -0,0 +1,662 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Proxy + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PhoneNumberInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the PhoneNumber resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the PhoneNumber resource. + :ivar service_sid: The SID of the PhoneNumber resource's parent [Service](https://www.twilio.com/docs/proxy/api/service) resource. + :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. + :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar iso_country: The ISO Country Code for the phone number. + :ivar capabilities: + :ivar url: The absolute URL of the PhoneNumber resource. + :ivar is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + :ivar in_use: The number of open session assigned to the number. See the [How many Phone Numbers do I need?](https://www.twilio.com/docs/proxy/phone-numbers-needed) guide for more information. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.phone_number: Optional[str] = payload.get("phone_number") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.iso_country: Optional[str] = payload.get("iso_country") + self.capabilities: Optional[str] = payload.get("capabilities") + self.url: Optional[str] = payload.get("url") + self.is_reserved: Optional[bool] = payload.get("is_reserved") + self.in_use: Optional[int] = deserialize.integer(payload.get("in_use")) + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[PhoneNumberContext] = None + + @property + def _proxy(self) -> "PhoneNumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PhoneNumberContext for this PhoneNumberInstance + """ + if self._context is None: + self._context = PhoneNumberContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "PhoneNumberInstance": + """ + Fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + return await self._proxy.fetch_async() + + def update( + self, is_reserved: Union[bool, object] = values.unset + ) -> "PhoneNumberInstance": + """ + Update the PhoneNumberInstance + + :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated PhoneNumberInstance + """ + return self._proxy.update( + is_reserved=is_reserved, + ) + + async def update_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to update the PhoneNumberInstance + + :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated PhoneNumberInstance + """ + return await self._proxy.update_async( + is_reserved=is_reserved, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Proxy.V1.PhoneNumberInstance {}>".format(context) + + +class PhoneNumberContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the PhoneNumberContext + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the PhoneNumber resource to update. + :param sid: The Twilio-provided string that uniquely identifies the PhoneNumber resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/PhoneNumbers/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, is_reserved: Union[bool, object] = values.unset + ) -> PhoneNumberInstance: + """ + Update the PhoneNumberInstance + + :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated PhoneNumberInstance + """ + + data = values.of( + { + "IsReserved": serialize.boolean_to_string(is_reserved), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> PhoneNumberInstance: + """ + Asynchronous coroutine to update the PhoneNumberInstance + + :param is_reserved: Whether the phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated PhoneNumberInstance + """ + + data = values.of( + { + "IsReserved": serialize.boolean_to_string(is_reserved), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Proxy.V1.PhoneNumberContext {}>".format(context) + + +class PhoneNumberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: + """ + Build an instance of PhoneNumberInstance + + :param payload: Payload response from the API + """ + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Proxy.V1.PhoneNumberPage>" + + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the PhoneNumberList + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the PhoneNumber resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/PhoneNumbers".format(**self._solution) + + def create( + self, + sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + is_reserved: Union[bool, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Create the PhoneNumberInstance + + :param sid: The SID of a Twilio [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the Twilio Number you would like to assign to your Proxy Service. + :param phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param is_reserved: Whether the new phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The created PhoneNumberInstance + """ + + data = values.of( + { + "Sid": sid, + "PhoneNumber": phone_number, + "IsReserved": serialize.boolean_to_string(is_reserved), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + is_reserved: Union[bool, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Asynchronously create the PhoneNumberInstance + + :param sid: The SID of a Twilio [IncomingPhoneNumber](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) resource that represents the Twilio Number you would like to assign to your Proxy Service. + :param phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format. E.164 phone numbers consist of a + followed by the country code and subscriber number without punctuation characters. For example, +14155551234. + :param is_reserved: Whether the new phone number should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The created PhoneNumberInstance + """ + + data = values.of( + { + "Sid": sid, + "PhoneNumber": phone_number, + "IsReserved": serialize.boolean_to_string(is_reserved), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PhoneNumberInstance]: + """ + Streams PhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PhoneNumberInstance]: + """ + Asynchronously streams PhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PhoneNumberInstance]: + """ + Lists PhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PhoneNumberInstance]: + """ + Asynchronously lists PhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PhoneNumberPage: + """ + Retrieve a single page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PhoneNumberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PhoneNumberPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PhoneNumberPage: + """ + Asynchronously retrieve a single page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PhoneNumberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PhoneNumberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> PhoneNumberPage: + """ + Retrieve a specific page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PhoneNumberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PhoneNumberPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> PhoneNumberPage: + """ + Asynchronously retrieve a specific page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PhoneNumberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PhoneNumberPage(self._version, response, self._solution) + + def get(self, sid: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param sid: The Twilio-provided string that uniquely identifies the PhoneNumber resource to update. + """ + return PhoneNumberContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param sid: The Twilio-provided string that uniquely identifies the PhoneNumber resource to update. + """ + return PhoneNumberContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Proxy.V1.PhoneNumberList>" diff --git a/twilio/rest/proxy/v1/service/session/__init__.py b/twilio/rest/proxy/v1/service/session/__init__.py new file mode 100644 index 0000000000..839db075c3 --- /dev/null +++ b/twilio/rest/proxy/v1/service/session/__init__.py @@ -0,0 +1,784 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Proxy + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.proxy.v1.service.session.interaction import InteractionList +from twilio.rest.proxy.v1.service.session.participant import ParticipantList + + +class SessionInstance(InstanceResource): + + class Mode(object): + MESSAGE_ONLY = "message-only" + VOICE_ONLY = "voice-only" + VOICE_AND_MESSAGE = "voice-and-message" + + class Status(object): + OPEN = "open" + IN_PROGRESS = "in-progress" + CLOSED = "closed" + FAILED = "failed" + UNKNOWN = "unknown" + + """ + :ivar sid: The unique string that we created to identify the Session resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/proxy/api/service) the session is associated with. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Session resource. + :ivar date_started: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session started. + :ivar date_ended: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session ended. + :ivar date_last_interaction: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session last had an interaction. + :ivar date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :ivar unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. Supports UTF-8 characters. **This value should not have PII.** + :ivar status: + :ivar closed_reason: The reason the Session ended. + :ivar ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :ivar mode: + :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. + :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + :ivar url: The absolute URL of the Session resource. + :ivar links: The URLs of resources related to the Session. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_started: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_started") + ) + self.date_ended: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_ended") + ) + self.date_last_interaction: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_last_interaction") + ) + self.date_expiry: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expiry") + ) + self.unique_name: Optional[str] = payload.get("unique_name") + self.status: Optional["SessionInstance.Status"] = payload.get("status") + self.closed_reason: Optional[str] = payload.get("closed_reason") + self.ttl: Optional[int] = deserialize.integer(payload.get("ttl")) + self.mode: Optional["SessionInstance.Mode"] = payload.get("mode") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[SessionContext] = None + + @property + def _proxy(self) -> "SessionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SessionContext for this SessionInstance + """ + if self._context is None: + self._context = SessionContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SessionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SessionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SessionInstance": + """ + Fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SessionInstance": + """ + Asynchronous coroutine to fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> "SessionInstance": + """ + Update the SessionInstance + + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param status: + + :returns: The updated SessionInstance + """ + return self._proxy.update( + date_expiry=date_expiry, + ttl=ttl, + status=status, + ) + + async def update_async( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> "SessionInstance": + """ + Asynchronous coroutine to update the SessionInstance + + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param status: + + :returns: The updated SessionInstance + """ + return await self._proxy.update_async( + date_expiry=date_expiry, + ttl=ttl, + status=status, + ) + + @property + def interactions(self) -> InteractionList: + """ + Access the interactions + """ + return self._proxy.interactions + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + return self._proxy.participants + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Proxy.V1.SessionInstance {}>".format(context) + + +class SessionContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the SessionContext + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to update. + :param sid: The Twilio-provided string that uniquely identifies the Session resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Sessions/{sid}".format(**self._solution) + + self._interactions: Optional[InteractionList] = None + self._participants: Optional[ParticipantList] = None + + def delete(self) -> bool: + """ + Deletes the SessionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SessionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SessionInstance: + """ + Fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SessionInstance: + """ + Asynchronous coroutine to fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> SessionInstance: + """ + Update the SessionInstance + + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param status: + + :returns: The updated SessionInstance + """ + + data = values.of( + { + "DateExpiry": serialize.iso8601_datetime(date_expiry), + "Ttl": ttl, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + ) -> SessionInstance: + """ + Asynchronous coroutine to update the SessionInstance + + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param status: + + :returns: The updated SessionInstance + """ + + data = values.of( + { + "DateExpiry": serialize.iso8601_datetime(date_expiry), + "Ttl": ttl, + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def interactions(self) -> InteractionList: + """ + Access the interactions + """ + if self._interactions is None: + self._interactions = InteractionList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._interactions + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + if self._participants is None: + self._participants = ParticipantList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._participants + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Proxy.V1.SessionContext {}>".format(context) + + +class SessionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SessionInstance: + """ + Build an instance of SessionInstance + + :param payload: Payload response from the API + """ + return SessionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Proxy.V1.SessionPage>" + + +class SessionList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the SessionList + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Sessions".format(**self._solution) + + def create( + self, + unique_name: Union[str, object] = values.unset, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + mode: Union["SessionInstance.Mode", object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + participants: Union[List[object], object] = values.unset, + ) -> SessionInstance: + """ + Create the SessionInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param mode: + :param status: + :param participants: The Participant objects to include in the new session. + + :returns: The created SessionInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "DateExpiry": serialize.iso8601_datetime(date_expiry), + "Ttl": ttl, + "Mode": mode, + "Status": status, + "Participants": serialize.map( + participants, lambda e: serialize.object(e) + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SessionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + date_expiry: Union[datetime, object] = values.unset, + ttl: Union[int, object] = values.unset, + mode: Union["SessionInstance.Mode", object] = values.unset, + status: Union["SessionInstance.Status", object] = values.unset, + participants: Union[List[object], object] = values.unset, + ) -> SessionInstance: + """ + Asynchronously create the SessionInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be 191 characters or fewer in length and be unique. **This value should not have PII.** + :param date_expiry: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Session should expire. If this is value is present, it overrides the `ttl` value. + :param ttl: The time, in seconds, when the session will expire. The time is measured from the last Session create or the Session's last Interaction. + :param mode: + :param status: + :param participants: The Participant objects to include in the new session. + + :returns: The created SessionInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "DateExpiry": serialize.iso8601_datetime(date_expiry), + "Ttl": ttl, + "Mode": mode, + "Status": status, + "Participants": serialize.map( + participants, lambda e: serialize.object(e) + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SessionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SessionInstance]: + """ + Streams SessionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SessionInstance]: + """ + Asynchronously streams SessionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SessionInstance]: + """ + Lists SessionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SessionInstance]: + """ + Asynchronously lists SessionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SessionPage: + """ + Retrieve a single page of SessionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SessionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SessionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SessionPage: + """ + Asynchronously retrieve a single page of SessionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SessionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SessionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SessionPage: + """ + Retrieve a specific page of SessionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SessionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SessionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SessionPage: + """ + Asynchronously retrieve a specific page of SessionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SessionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SessionPage(self._version, response, self._solution) + + def get(self, sid: str) -> SessionContext: + """ + Constructs a SessionContext + + :param sid: The Twilio-provided string that uniquely identifies the Session resource to update. + """ + return SessionContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> SessionContext: + """ + Constructs a SessionContext + + :param sid: The Twilio-provided string that uniquely identifies the Session resource to update. + """ + return SessionContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Proxy.V1.SessionList>" diff --git a/twilio/rest/proxy/v1/service/session/interaction.py b/twilio/rest/proxy/v1/service/session/interaction.py new file mode 100644 index 0000000000..7eeccda5bc --- /dev/null +++ b/twilio/rest/proxy/v1/service/session/interaction.py @@ -0,0 +1,571 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Proxy + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class InteractionInstance(InstanceResource): + + class ResourceStatus(object): + ACCEPTED = "accepted" + ANSWERED = "answered" + BUSY = "busy" + CANCELED = "canceled" + COMPLETED = "completed" + DELETED = "deleted" + DELIVERED = "delivered" + DELIVERY_UNKNOWN = "delivery-unknown" + FAILED = "failed" + IN_PROGRESS = "in-progress" + INITIATED = "initiated" + NO_ANSWER = "no-answer" + QUEUED = "queued" + RECEIVED = "received" + RECEIVING = "receiving" + RINGING = "ringing" + SCHEDULED = "scheduled" + SENDING = "sending" + SENT = "sent" + UNDELIVERED = "undelivered" + UNKNOWN = "unknown" + + class Type(object): + MESSAGE = "message" + VOICE = "voice" + UNKNOWN = "unknown" + + """ + :ivar sid: The unique string that we created to identify the Interaction resource. + :ivar session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) resource. + :ivar service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Interaction resource. + :ivar data: A JSON string that includes the message body of message interactions (e.g. `{\"body\": \"hello\"}`) or the call duration (when available) of a call (e.g. `{\"duration\": \"5\"}`). + :ivar type: + :ivar inbound_participant_sid: The SID of the inbound [Participant](https://www.twilio.com/docs/proxy/api/participant) resource. + :ivar inbound_resource_sid: The SID of the inbound resource; either the [Call](https://www.twilio.com/docs/voice/api/call-resource) or [Message](https://www.twilio.com/docs/sms/api/message-resource). + :ivar inbound_resource_status: + :ivar inbound_resource_type: The inbound resource type. Can be [Call](https://www.twilio.com/docs/voice/api/call-resource) or [Message](https://www.twilio.com/docs/sms/api/message-resource). + :ivar inbound_resource_url: The URL of the Twilio inbound resource + :ivar outbound_participant_sid: The SID of the outbound [Participant](https://www.twilio.com/docs/proxy/api/participant)). + :ivar outbound_resource_sid: The SID of the outbound resource; either the [Call](https://www.twilio.com/docs/voice/api/call-resource) or [Message](https://www.twilio.com/docs/sms/api/message-resource). + :ivar outbound_resource_status: + :ivar outbound_resource_type: The outbound resource type. Can be: [Call](https://www.twilio.com/docs/voice/api/call-resource) or [Message](https://www.twilio.com/docs/sms/api/message-resource). + :ivar outbound_resource_url: The URL of the Twilio outbound resource. + :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the Interaction was created. + :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + :ivar url: The absolute URL of the Interaction resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + session_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.session_sid: Optional[str] = payload.get("session_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.data: Optional[str] = payload.get("data") + self.type: Optional["InteractionInstance.Type"] = payload.get("type") + self.inbound_participant_sid: Optional[str] = payload.get( + "inbound_participant_sid" + ) + self.inbound_resource_sid: Optional[str] = payload.get("inbound_resource_sid") + self.inbound_resource_status: Optional["InteractionInstance.ResourceStatus"] = ( + payload.get("inbound_resource_status") + ) + self.inbound_resource_type: Optional[str] = payload.get("inbound_resource_type") + self.inbound_resource_url: Optional[str] = payload.get("inbound_resource_url") + self.outbound_participant_sid: Optional[str] = payload.get( + "outbound_participant_sid" + ) + self.outbound_resource_sid: Optional[str] = payload.get("outbound_resource_sid") + self.outbound_resource_status: Optional[ + "InteractionInstance.ResourceStatus" + ] = payload.get("outbound_resource_status") + self.outbound_resource_type: Optional[str] = payload.get( + "outbound_resource_type" + ) + self.outbound_resource_url: Optional[str] = payload.get("outbound_resource_url") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + "sid": sid or self.sid, + } + self._context: Optional[InteractionContext] = None + + @property + def _proxy(self) -> "InteractionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InteractionContext for this InteractionInstance + """ + if self._context is None: + self._context = InteractionContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the InteractionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InteractionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "InteractionInstance": + """ + Fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InteractionInstance": + """ + Asynchronous coroutine to fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Proxy.V1.InteractionInstance {}>".format(context) + + +class InteractionContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, session_sid: str, sid: str): + """ + Initialize the InteractionContext + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to fetch. + :param session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) of the resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Interaction resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Sessions/{session_sid}/Interactions/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the InteractionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InteractionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> InteractionInstance: + """ + Fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return InteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> InteractionInstance: + """ + Asynchronous coroutine to fetch the InteractionInstance + + + :returns: The fetched InteractionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return InteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Proxy.V1.InteractionContext {}>".format(context) + + +class InteractionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InteractionInstance: + """ + Build an instance of InteractionInstance + + :param payload: Payload response from the API + """ + return InteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Proxy.V1.InteractionPage>" + + +class InteractionList(ListResource): + + def __init__(self, version: Version, service_sid: str, session_sid: str): + """ + Initialize the InteractionList + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) to read the resources from. + :param session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + } + self._uri = ( + "/Services/{service_sid}/Sessions/{session_sid}/Interactions".format( + **self._solution + ) + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InteractionInstance]: + """ + Streams InteractionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[InteractionInstance]: + """ + Asynchronously streams InteractionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionInstance]: + """ + Lists InteractionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[InteractionInstance]: + """ + Asynchronously lists InteractionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InteractionPage: + """ + Retrieve a single page of InteractionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InteractionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InteractionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InteractionPage: + """ + Asynchronously retrieve a single page of InteractionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of InteractionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return InteractionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> InteractionPage: + """ + Retrieve a specific page of InteractionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InteractionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InteractionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> InteractionPage: + """ + Asynchronously retrieve a specific page of InteractionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InteractionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InteractionPage(self._version, response, self._solution) + + def get(self, sid: str) -> InteractionContext: + """ + Constructs a InteractionContext + + :param sid: The Twilio-provided string that uniquely identifies the Interaction resource to fetch. + """ + return InteractionContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InteractionContext: + """ + Constructs a InteractionContext + + :param sid: The Twilio-provided string that uniquely identifies the Interaction resource to fetch. + """ + return InteractionContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Proxy.V1.InteractionList>" diff --git a/twilio/rest/proxy/v1/service/session/participant/__init__.py b/twilio/rest/proxy/v1/service/session/participant/__init__.py new file mode 100644 index 0000000000..7ad20fcffb --- /dev/null +++ b/twilio/rest/proxy/v1/service/session/participant/__init__.py @@ -0,0 +1,634 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Proxy + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.proxy.v1.service.session.participant.message_interaction import ( + MessageInteractionList, +) + + +class ParticipantInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Participant resource. + :ivar session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) resource. + :ivar service_sid: The SID of the resource's parent [Service](https://www.twilio.com/docs/proxy/api/service) resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Participant resource. + :ivar friendly_name: The string that you assigned to describe the participant. This value must be 255 characters or fewer. Supports UTF-8 characters. **This value should not have PII.** + :ivar identifier: The phone number or channel identifier of the Participant. This value must be 191 characters or fewer. Supports UTF-8 characters. + :ivar proxy_identifier: The phone number or short code (masked number) of the participant's partner. The participant will call or message the partner participant at this number. + :ivar proxy_identifier_sid: The SID of the Proxy Identifier assigned to the Participant. + :ivar date_deleted: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date when the Participant was removed from the session. + :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. + :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + :ivar url: The absolute URL of the Participant resource. + :ivar links: The URLs to resources related the participant. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + session_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.session_sid: Optional[str] = payload.get("session_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.identifier: Optional[str] = payload.get("identifier") + self.proxy_identifier: Optional[str] = payload.get("proxy_identifier") + self.proxy_identifier_sid: Optional[str] = payload.get("proxy_identifier_sid") + self.date_deleted: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_deleted") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + "sid": sid or self.sid, + } + self._context: Optional[ParticipantContext] = None + + @property + def _proxy(self) -> "ParticipantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ParticipantContext for this ParticipantInstance + """ + if self._context is None: + self._context = ParticipantContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ParticipantInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ParticipantInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ParticipantInstance": + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ParticipantInstance": + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return await self._proxy.fetch_async() + + @property + def message_interactions(self) -> MessageInteractionList: + """ + Access the message_interactions + """ + return self._proxy.message_interactions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Proxy.V1.ParticipantInstance {}>".format(context) + + +class ParticipantContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, session_sid: str, sid: str): + """ + Initialize the ParticipantContext + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to fetch. + :param session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) of the resource to fetch. + :param sid: The Twilio-provided string that uniquely identifies the Participant resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Sessions/{session_sid}/Participants/{sid}".format( + **self._solution + ) + ) + + self._message_interactions: Optional[MessageInteractionList] = None + + def delete(self) -> bool: + """ + Deletes the ParticipantInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ParticipantInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], + ) + + @property + def message_interactions(self) -> MessageInteractionList: + """ + Access the message_interactions + """ + if self._message_interactions is None: + self._message_interactions = MessageInteractionList( + self._version, + self._solution["service_sid"], + self._solution["session_sid"], + self._solution["sid"], + ) + return self._message_interactions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Proxy.V1.ParticipantContext {}>".format(context) + + +class ParticipantPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: + """ + Build an instance of ParticipantInstance + + :param payload: Payload response from the API + """ + return ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Proxy.V1.ParticipantPage>" + + +class ParticipantList(ListResource): + + def __init__(self, version: Version, service_sid: str, session_sid: str): + """ + Initialize the ParticipantList + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resources to read. + :param session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) of the resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + } + self._uri = ( + "/Services/{service_sid}/Sessions/{session_sid}/Participants".format( + **self._solution + ) + ) + + def create( + self, + identifier: str, + friendly_name: Union[str, object] = values.unset, + proxy_identifier: Union[str, object] = values.unset, + proxy_identifier_sid: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Create the ParticipantInstance + + :param identifier: The phone number of the Participant. + :param friendly_name: The string that you assigned to describe the participant. This value must be 255 characters or fewer. **This value should not have PII.** + :param proxy_identifier: The proxy phone number to use for the Participant. If not specified, Proxy will select a number from the pool. + :param proxy_identifier_sid: The SID of the Proxy Identifier to assign to the Participant. + + :returns: The created ParticipantInstance + """ + + data = values.of( + { + "Identifier": identifier, + "FriendlyName": friendly_name, + "ProxyIdentifier": proxy_identifier, + "ProxyIdentifierSid": proxy_identifier_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + ) + + async def create_async( + self, + identifier: str, + friendly_name: Union[str, object] = values.unset, + proxy_identifier: Union[str, object] = values.unset, + proxy_identifier_sid: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Asynchronously create the ParticipantInstance + + :param identifier: The phone number of the Participant. + :param friendly_name: The string that you assigned to describe the participant. This value must be 255 characters or fewer. **This value should not have PII.** + :param proxy_identifier: The proxy phone number to use for the Participant. If not specified, Proxy will select a number from the pool. + :param proxy_identifier_sid: The SID of the Proxy Identifier to assign to the Participant. + + :returns: The created ParticipantInstance + """ + + data = values.of( + { + "Identifier": identifier, + "FriendlyName": friendly_name, + "ProxyIdentifier": proxy_identifier, + "ProxyIdentifierSid": proxy_identifier_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantInstance]: + """ + Streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ParticipantInstance]: + """ + Asynchronously streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Asynchronously lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Asynchronously retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ParticipantPage: + """ + Retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ParticipantPage: + """ + Asynchronously retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + def get(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: The Twilio-provided string that uniquely identifies the Participant resource to fetch. + """ + return ParticipantContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: The Twilio-provided string that uniquely identifies the Participant resource to fetch. + """ + return ParticipantContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Proxy.V1.ParticipantList>" diff --git a/twilio/rest/proxy/v1/service/session/participant/message_interaction.py b/twilio/rest/proxy/v1/service/session/participant/message_interaction.py new file mode 100644 index 0000000000..4ffe67965b --- /dev/null +++ b/twilio/rest/proxy/v1/service/session/participant/message_interaction.py @@ -0,0 +1,622 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Proxy + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MessageInteractionInstance(InstanceResource): + + class ResourceStatus(object): + ACCEPTED = "accepted" + ANSWERED = "answered" + BUSY = "busy" + CANCELED = "canceled" + COMPLETED = "completed" + DELETED = "deleted" + DELIVERED = "delivered" + DELIVERY_UNKNOWN = "delivery-unknown" + FAILED = "failed" + IN_PROGRESS = "in-progress" + INITIATED = "initiated" + NO_ANSWER = "no-answer" + QUEUED = "queued" + RECEIVED = "received" + RECEIVING = "receiving" + RINGING = "ringing" + SCHEDULED = "scheduled" + SENDING = "sending" + SENT = "sent" + UNDELIVERED = "undelivered" + UNKNOWN = "unknown" + + class Type(object): + MESSAGE = "message" + VOICE = "voice" + UNKNOWN = "unknown" + + """ + :ivar sid: The unique string that we created to identify the MessageInteraction resource. + :ivar session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) resource. + :ivar service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the MessageInteraction resource. + :ivar data: A JSON string that includes the message body sent to the participant. (e.g. `{\"body\": \"hello\"}`) + :ivar type: + :ivar participant_sid: The SID of the [Participant](https://www.twilio.com/docs/proxy/api/participant) resource. + :ivar inbound_participant_sid: Always empty for created Message Interactions. + :ivar inbound_resource_sid: Always empty for created Message Interactions. + :ivar inbound_resource_status: + :ivar inbound_resource_type: Always empty for created Message Interactions. + :ivar inbound_resource_url: Always empty for created Message Interactions. + :ivar outbound_participant_sid: The SID of the outbound [Participant](https://www.twilio.com/docs/proxy/api/participant) resource. + :ivar outbound_resource_sid: The SID of the outbound [Message](https://www.twilio.com/docs/sms/api/message-resource) resource. + :ivar outbound_resource_status: + :ivar outbound_resource_type: The outbound resource type. This value is always `Message`. + :ivar outbound_resource_url: The URL of the Twilio message resource. + :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. + :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + :ivar url: The absolute URL of the MessageInteraction resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + session_sid: str, + participant_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.session_sid: Optional[str] = payload.get("session_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.data: Optional[str] = payload.get("data") + self.type: Optional["MessageInteractionInstance.Type"] = payload.get("type") + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.inbound_participant_sid: Optional[str] = payload.get( + "inbound_participant_sid" + ) + self.inbound_resource_sid: Optional[str] = payload.get("inbound_resource_sid") + self.inbound_resource_status: Optional[ + "MessageInteractionInstance.ResourceStatus" + ] = payload.get("inbound_resource_status") + self.inbound_resource_type: Optional[str] = payload.get("inbound_resource_type") + self.inbound_resource_url: Optional[str] = payload.get("inbound_resource_url") + self.outbound_participant_sid: Optional[str] = payload.get( + "outbound_participant_sid" + ) + self.outbound_resource_sid: Optional[str] = payload.get("outbound_resource_sid") + self.outbound_resource_status: Optional[ + "MessageInteractionInstance.ResourceStatus" + ] = payload.get("outbound_resource_status") + self.outbound_resource_type: Optional[str] = payload.get( + "outbound_resource_type" + ) + self.outbound_resource_url: Optional[str] = payload.get("outbound_resource_url") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + "participant_sid": participant_sid, + "sid": sid or self.sid, + } + self._context: Optional[MessageInteractionContext] = None + + @property + def _proxy(self) -> "MessageInteractionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MessageInteractionContext for this MessageInteractionInstance + """ + if self._context is None: + self._context = MessageInteractionContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "MessageInteractionInstance": + """ + Fetch the MessageInteractionInstance + + + :returns: The fetched MessageInteractionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MessageInteractionInstance": + """ + Asynchronous coroutine to fetch the MessageInteractionInstance + + + :returns: The fetched MessageInteractionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Proxy.V1.MessageInteractionInstance {}>".format(context) + + +class MessageInteractionContext(InstanceContext): + + def __init__( + self, + version: Version, + service_sid: str, + session_sid: str, + participant_sid: str, + sid: str, + ): + """ + Initialize the MessageInteractionContext + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to fetch. + :param session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) of the resource to fetch. + :param participant_sid: The SID of the [Participant](https://www.twilio.com/docs/proxy/api/participant) resource. + :param sid: The Twilio-provided string that uniquely identifies the MessageInteraction resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + "participant_sid": participant_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Sessions/{session_sid}/Participants/{participant_sid}/MessageInteractions/{sid}".format( + **self._solution + ) + + def fetch(self) -> MessageInteractionInstance: + """ + Fetch the MessageInteractionInstance + + + :returns: The fetched MessageInteractionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MessageInteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> MessageInteractionInstance: + """ + Asynchronous coroutine to fetch the MessageInteractionInstance + + + :returns: The fetched MessageInteractionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessageInteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Proxy.V1.MessageInteractionContext {}>".format(context) + + +class MessageInteractionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessageInteractionInstance: + """ + Build an instance of MessageInteractionInstance + + :param payload: Payload response from the API + """ + return MessageInteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Proxy.V1.MessageInteractionPage>" + + +class MessageInteractionList(ListResource): + + def __init__( + self, version: Version, service_sid: str, session_sid: str, participant_sid: str + ): + """ + Initialize the MessageInteractionList + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) to read the resources from. + :param session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) to read the resources from. + :param participant_sid: The SID of the [Participant](https://www.twilio.com/docs/proxy/api/participant) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "session_sid": session_sid, + "participant_sid": participant_sid, + } + self._uri = "/Services/{service_sid}/Sessions/{session_sid}/Participants/{participant_sid}/MessageInteractions".format( + **self._solution + ) + + def create( + self, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + ) -> MessageInteractionInstance: + """ + Create the MessageInteractionInstance + + :param body: The message to send to the participant + :param media_url: Reserved. Not currently supported. + + :returns: The created MessageInteractionInstance + """ + + data = values.of( + { + "Body": body, + "MediaUrl": serialize.map(media_url, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + ) + + async def create_async( + self, + body: Union[str, object] = values.unset, + media_url: Union[List[str], object] = values.unset, + ) -> MessageInteractionInstance: + """ + Asynchronously create the MessageInteractionInstance + + :param body: The message to send to the participant + :param media_url: Reserved. Not currently supported. + + :returns: The created MessageInteractionInstance + """ + + data = values.of( + { + "Body": body, + "MediaUrl": serialize.map(media_url, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessageInteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessageInteractionInstance]: + """ + Streams MessageInteractionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessageInteractionInstance]: + """ + Asynchronously streams MessageInteractionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInteractionInstance]: + """ + Lists MessageInteractionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessageInteractionInstance]: + """ + Asynchronously lists MessageInteractionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessageInteractionPage: + """ + Retrieve a single page of MessageInteractionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInteractionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessageInteractionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessageInteractionPage: + """ + Asynchronously retrieve a single page of MessageInteractionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessageInteractionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessageInteractionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MessageInteractionPage: + """ + Retrieve a specific page of MessageInteractionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInteractionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MessageInteractionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MessageInteractionPage: + """ + Asynchronously retrieve a specific page of MessageInteractionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessageInteractionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessageInteractionPage(self._version, response, self._solution) + + def get(self, sid: str) -> MessageInteractionContext: + """ + Constructs a MessageInteractionContext + + :param sid: The Twilio-provided string that uniquely identifies the MessageInteraction resource to fetch. + """ + return MessageInteractionContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> MessageInteractionContext: + """ + Constructs a MessageInteractionContext + + :param sid: The Twilio-provided string that uniquely identifies the MessageInteraction resource to fetch. + """ + return MessageInteractionContext( + self._version, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + participant_sid=self._solution["participant_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Proxy.V1.MessageInteractionList>" diff --git a/twilio/rest/proxy/v1/service/short_code.py b/twilio/rest/proxy/v1/service/short_code.py new file mode 100644 index 0000000000..df71d4bdd5 --- /dev/null +++ b/twilio/rest/proxy/v1/service/short_code.py @@ -0,0 +1,638 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Proxy + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ShortCodeInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the ShortCode resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ShortCode resource. + :ivar service_sid: The SID of the ShortCode resource's parent [Service](https://www.twilio.com/docs/proxy/api/service) resource. + :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was created. + :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the resource was last updated. + :ivar short_code: The short code's number. + :ivar iso_country: The ISO Country Code for the short code. + :ivar capabilities: + :ivar url: The absolute URL of the ShortCode resource. + :ivar is_reserved: Whether the short code should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.short_code: Optional[str] = payload.get("short_code") + self.iso_country: Optional[str] = payload.get("iso_country") + self.capabilities: Optional[str] = payload.get("capabilities") + self.url: Optional[str] = payload.get("url") + self.is_reserved: Optional[bool] = payload.get("is_reserved") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[ShortCodeContext] = None + + @property + def _proxy(self) -> "ShortCodeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ShortCodeContext for this ShortCodeInstance + """ + if self._context is None: + self._context = ShortCodeContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ShortCodeInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ShortCodeInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ShortCodeInstance": + """ + Fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ShortCodeInstance": + """ + Asynchronous coroutine to fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + return await self._proxy.fetch_async() + + def update( + self, is_reserved: Union[bool, object] = values.unset + ) -> "ShortCodeInstance": + """ + Update the ShortCodeInstance + + :param is_reserved: Whether the short code should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated ShortCodeInstance + """ + return self._proxy.update( + is_reserved=is_reserved, + ) + + async def update_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> "ShortCodeInstance": + """ + Asynchronous coroutine to update the ShortCodeInstance + + :param is_reserved: Whether the short code should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated ShortCodeInstance + """ + return await self._proxy.update_async( + is_reserved=is_reserved, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Proxy.V1.ShortCodeInstance {}>".format(context) + + +class ShortCodeContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the ShortCodeContext + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) of the resource to update. + :param sid: The Twilio-provided string that uniquely identifies the ShortCode resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/ShortCodes/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the ShortCodeInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ShortCodeInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ShortCodeInstance: + """ + Fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ShortCodeInstance: + """ + Asynchronous coroutine to fetch the ShortCodeInstance + + + :returns: The fetched ShortCodeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, is_reserved: Union[bool, object] = values.unset + ) -> ShortCodeInstance: + """ + Update the ShortCodeInstance + + :param is_reserved: Whether the short code should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated ShortCodeInstance + """ + + data = values.of( + { + "IsReserved": serialize.boolean_to_string(is_reserved), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, is_reserved: Union[bool, object] = values.unset + ) -> ShortCodeInstance: + """ + Asynchronous coroutine to update the ShortCodeInstance + + :param is_reserved: Whether the short code should be reserved and not be assigned to a participant using proxy pool logic. See [Reserved Phone Numbers](https://www.twilio.com/docs/proxy/reserved-phone-numbers) for more information. + + :returns: The updated ShortCodeInstance + """ + + data = values.of( + { + "IsReserved": serialize.boolean_to_string(is_reserved), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Proxy.V1.ShortCodeContext {}>".format(context) + + +class ShortCodePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ShortCodeInstance: + """ + Build an instance of ShortCodeInstance + + :param payload: Payload response from the API + """ + return ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Proxy.V1.ShortCodePage>" + + +class ShortCodeList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the ShortCodeList + + :param version: Version that contains the resource + :param service_sid: The SID of the parent [Service](https://www.twilio.com/docs/proxy/api/service) to read the resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/ShortCodes".format(**self._solution) + + def create(self, sid: str) -> ShortCodeInstance: + """ + Create the ShortCodeInstance + + :param sid: The SID of a Twilio [ShortCode](https://www.twilio.com/en-us/messaging/channels/sms/short-codes) resource that represents the short code you would like to assign to your Proxy Service. + + :returns: The created ShortCodeInstance + """ + + data = values.of( + { + "Sid": sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async(self, sid: str) -> ShortCodeInstance: + """ + Asynchronously create the ShortCodeInstance + + :param sid: The SID of a Twilio [ShortCode](https://www.twilio.com/en-us/messaging/channels/sms/short-codes) resource that represents the short code you would like to assign to your Proxy Service. + + :returns: The created ShortCodeInstance + """ + + data = values.of( + { + "Sid": sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ShortCodeInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ShortCodeInstance]: + """ + Streams ShortCodeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ShortCodeInstance]: + """ + Asynchronously streams ShortCodeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ShortCodeInstance]: + """ + Lists ShortCodeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ShortCodeInstance]: + """ + Asynchronously lists ShortCodeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ShortCodePage: + """ + Retrieve a single page of ShortCodeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ShortCodeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ShortCodePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ShortCodePage: + """ + Asynchronously retrieve a single page of ShortCodeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ShortCodeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ShortCodePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ShortCodePage: + """ + Retrieve a specific page of ShortCodeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ShortCodeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ShortCodePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ShortCodePage: + """ + Asynchronously retrieve a specific page of ShortCodeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ShortCodeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ShortCodePage(self._version, response, self._solution) + + def get(self, sid: str) -> ShortCodeContext: + """ + Constructs a ShortCodeContext + + :param sid: The Twilio-provided string that uniquely identifies the ShortCode resource to update. + """ + return ShortCodeContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ShortCodeContext: + """ + Constructs a ShortCodeContext + + :param sid: The Twilio-provided string that uniquely identifies the ShortCode resource to update. + """ + return ShortCodeContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Proxy.V1.ShortCodeList>" diff --git a/twilio/rest/resources/__init__.py b/twilio/rest/resources/__init__.py deleted file mode 100644 index b4b2720135..0000000000 --- a/twilio/rest/resources/__init__.py +++ /dev/null @@ -1,47 +0,0 @@ -import re -import datetime -import logging -import twilio -from twilio import TwilioException, TwilioRestException - -from twilio.rest.resources.imports import ( - parse_qs, json, httplib2 -) - -from twilio.rest.resources.util import ( - transform_params, format_name, parse_date, convert_boolean, convert_case, - convert_keys, normalize_dates -) -from twilio.rest.resources.base import ( - Response, Resource, InstanceResource, ListResource, - make_request, make_twilio_request -) -from twilio.rest.resources.phone_numbers import ( - AvailablePhoneNumber, AvailablePhoneNumbers, PhoneNumber, PhoneNumbers -) -from twilio.rest.resources.recordings import ( - Recording, Recordings, Transcription, Transcriptions -) -from twilio.rest.resources.notifications import ( - Notification, Notifications -) -from twilio.rest.resources.connect_apps import ( - ConnectApp, ConnectApps, AuthorizedConnectApp, AuthorizedConnectApps -) -from twilio.rest.resources.calls import Call, Calls -from twilio.rest.resources.caller_ids import CallerIds, CallerId -from twilio.rest.resources.sandboxes import Sandbox, Sandboxes -from twilio.rest.resources.sms_messages import ( - Sms, SmsMessage, SmsMessages, ShortCode, ShortCodes) -from twilio.rest.resources.conferences import ( - Participant, Participants, Conference, Conferences -) -from twilio.rest.resources.queues import ( - Member, Members, Queue, Queues, -) -from twilio.rest.resources.applications import ( - Application, Applications -) -from twilio.rest.resources.accounts import Account, Accounts - -from twilio.rest.resources.usage import Usage diff --git a/twilio/rest/resources/accounts.py b/twilio/rest/resources/accounts.py deleted file mode 100644 index 6db245a341..0000000000 --- a/twilio/rest/resources/accounts.py +++ /dev/null @@ -1,123 +0,0 @@ -from twilio.rest.resources import InstanceResource, ListResource -from twilio.rest.resources.applications import Applications -from twilio.rest.resources.notifications import Notifications -from twilio.rest.resources.recordings import Transcriptions, Recordings -from twilio.rest.resources.calls import Calls -from twilio.rest.resources.sms_messages import Sms -from twilio.rest.resources.caller_ids import CallerIds -from twilio.rest.resources.phone_numbers import PhoneNumbers -from twilio.rest.resources.conferences import Conferences -from twilio.rest.resources.connect_apps import ( - ConnectApps, AuthorizedConnectApps -) -from twilio.rest.resources.queues import Queues -from twilio.rest.resources.usage import UsageRecords, UsageTriggers - - -class Account(InstanceResource): - """ An Account resource """ - - ACTIVE = "active" - SUSPENDED = "suspended" - CLOSED = "closed" - - subresources = [ - Applications, - Notifications, - Transcriptions, - Recordings, - Calls, - Sms, - CallerIds, - PhoneNumbers, - Conferences, - ConnectApps, - Queues, - AuthorizedConnectApps, - UsageRecords, - UsageTriggers, - ] - - def update(self, **kwargs): - """ - :param friendly_name: Update the description of this account. - :param status: Alter the status of this account - - Use :data:`CLOSED` to irreversibly close this account, - :data:`SUSPENDED` to temporarily suspend it, or :data:`ACTIVE` - to reactivate it. - """ - self.update_instance(**kwargs) - - def close(self): - """ - Permenently deactivate this account - """ - return self.update_instance(status=Account.CLOSED) - - def suspend(self): - """ - Temporarily suspend this account - """ - return self.update_instance(status=Account.SUSPENDED) - - def activate(self): - """ - Reactivate this account - """ - return self.update_instance(status=Account.ACTIVE) - - -class Accounts(ListResource): - """ A list of Account resources """ - - name = "Accounts" - instance = Account - - def list(self, **kwargs): - """ - Returns a page of :class:`Account` resources as a list. For paging - informtion see :class:`ListResource` - - :param date friendly_name: Only list accounts with this friendly name - :param date status: Only list accounts with this status - """ - return self.get_instances(kwargs) - - def update(self, sid, **kwargs): - """ - :param sid: Account identifier - :param friendly_name: Update the description of this account. - :param status: Alter the status of this account - - Use :data:`CLOSED` to irreversibly close this account, - :data:`SUSPENDED` to temporarily suspend it, or :data:`ACTIVE` - to reactivate it. - """ - return self.update_instance(sid, kwargs) - - def close(self, sid): - """ - Permenently deactivate an account, Alias to update - """ - return self.update(sid, status=Account.CLOSED) - - def suspend(self, sid): - """ - Temporarily suspend an account, Alias to update - """ - return self.update(sid, status=Account.SUSPENDED) - - def activate(self, sid): - """ - Reactivate an account, Alias to update - """ - return self.update(sid, status=Account.ACTIVE) - - def create(self, **kwargs): - """ - Returns a newly created sub account resource. - - :param friendly_name: Update the description of this account. - """ - return self.create_instance(kwargs) diff --git a/twilio/rest/resources/applications.py b/twilio/rest/resources/applications.py deleted file mode 100644 index 84d30fae75..0000000000 --- a/twilio/rest/resources/applications.py +++ /dev/null @@ -1,92 +0,0 @@ -from twilio.rest.resources import InstanceResource, ListResource - - -class Application(InstanceResource): - """ An application resource """ - - def update(self, **kwargs): - """ - Update this application - """ - return self.parent.update(self.sid, **kwargs) - - def delete(self): - """ - Delete this application - """ - return self.parent.delete(self.sid) - - -class Applications(ListResource): - - name = "Applications" - instance = Application - - def list(self, **kwargs): - """ - Returns a page of :class:`Application` resources as a list. For paging - informtion see :class:`ListResource` - - :param date friendly_name: List applications with this friendly name - """ - return self.get_instances(kwargs) - - def create(self, **kwargs): - """ - Create an :class:`Application` with any of these optional parameters. - - :param friendly_name: A human readable description of the application, - with maximum length 64 characters. - :param api_version: Requests to this application's URLs will start a - new TwiML session with this API version. - Either 2010-04-01 or 2008-08-01. - :param voice_url: The URL that Twilio should request when somebody - dials a phone number assigned to this application. - :param voice_method: The HTTP method that should be used to request the - VoiceUrl. Either GET or POST. - :param voice_fallback_url: A URL that Twilio will request if an error - occurs requesting or executing the TwiML - defined by VoiceUrl. - :param voice_fallback_method: The HTTP method that should be used to - request the VoiceFallbackUrl. Either GET - or POST. - :param status_callback: The URL that Twilio will request to pass status - parameters (such as call ended) to your - application. - :param status_callback_method: The HTTP method Twilio will use to make - requests to the StatusCallback URL. - Either GET or POST. - :param voice_caller_id_lookup: Do a lookup of a caller's name from the - CNAM database and post it to your app. - Either true or false. - :param sms_url: The URL that Twilio should request when somebody sends - an SMS to a phone number assigned to this application. - :param sms_method: The HTTP method that should be used to request the - SmsUrl. Either GET or POST. - :param sms_fallback_url: A URL that Twilio will request if an error - occurs requesting or executing the TwiML - defined by SmsUrl. - :param sms_fallback_method: The HTTP method that should be used to - request the SmsFallbackUrl. Either GET - or POST. - :param sms_status_callback: Twilio will make a POST request to this URL - to pass status parameters (such as sent or - failed) to your application if you specify - this application's Sid as the - ApplicationSid on an outgoing SMS request. - """ - return self.create_instance(kwargs) - - def update(self, sid, **kwargs): - """ - Update an :class:`Application` with the given parameters. - - All the parameters are describe above in :meth:`create` - """ - return self.update_instance(sid, kwargs) - - def delete(self, sid): - """ - Delete an :class:`Application` - """ - return self.delete_instance(sid) diff --git a/twilio/rest/resources/base.py b/twilio/rest/resources/base.py deleted file mode 100644 index 512326f017..0000000000 --- a/twilio/rest/resources/base.py +++ /dev/null @@ -1,285 +0,0 @@ -import logging -from six import text_type, iteritems, binary_type -from twilio.compat import urlparse -from twilio.compat import urlencode - -import twilio -from twilio import TwilioException, TwilioRestException -from twilio.rest.resources.imports import parse_qs, httplib2, json -from twilio.rest.resources.util import transform_params - - -class Response(object): - """ - Take a httplib2 response and turn it into a requests response - """ - def __init__(self, httplib_resp, content, url): - self.content = content - self.cached = False - self.status_code = int(httplib_resp.status) - self.ok = self.status_code < 400 - self.url = url - - -def make_request(method, url, params=None, data=None, headers=None, - cookies=None, files=None, auth=None, timeout=None, - allow_redirects=False, proxies=None): - """Sends an HTTP request Returns :class:`Response <models.Response>` - - See the requests documentation for explanation of all these parameters - - Currently proxies, files, and cookies are all ignored - """ - http = httplib2.Http(timeout=timeout) - http.follow_redirects = allow_redirects - - if auth is not None: - http.add_credentials(auth[0], auth[1]) - - if data is not None: - udata = {} - for k, v in iteritems(data): - key = k.encode('utf-8') - if isinstance(v, text_type): - udata[key] = v.encode('utf-8') - elif isinstance(v, binary_type): - udata[key] = v - else: - raise ValueError('data should be either a binary or a string') - data = urlencode(udata) - - if params is not None: - enc_params = urlencode(params, doseq=True) - if urlparse(url).query: - url = '%s&%s' % (url, enc_params) - else: - url = '%s?%s' % (url, enc_params) - - resp, content = http.request(url, method, headers=headers, body=data) - - # Format httplib2 request as requests object - return Response(resp, content, url) - - -def make_twilio_request(method, uri, **kwargs): - """ - Make a request to Twilio. Throws an error - """ - headers = kwargs.get("headers", {}) - headers["User-Agent"] = "twilio-python/%s" % twilio.__version__ - - if method == "POST" and "Content-Type" not in headers: - headers["Content-Type"] = "application/x-www-form-urlencoded" - - kwargs["headers"] = headers - - if "Accept" not in headers: - headers["Accept"] = "application/json" - uri += ".json" - - resp = make_request(method, uri, **kwargs) - - if not resp.ok: - try: - error = json.loads(resp.content) - code = error["code"] - message = "%s: %s" % (code, error["message"]) - except: - code = None - message = resp.content - - raise TwilioRestException(resp.status_code, resp.url, message, code) - - return resp - - -class Resource(object): - """A REST Resource""" - - name = "Resource" - - def __init__(self, base_uri, auth): - self.base_uri = base_uri - self.auth = auth - - def __eq__(self, other): - return (isinstance(other, self.__class__) - and self.__dict__ == other.__dict__) - - def __hash__(self): - return hash(frozenset(self.__dict__)) - - def __ne__(self, other): - return not self.__eq__(other) - - def request(self, method, uri, **kwargs): - """ - Send an HTTP request to the resource. - - Raise a TwilioRestException - """ - resp = make_twilio_request(method, uri, auth=self.auth, **kwargs) - - logging.debug(resp.content) - - if method == "DELETE": - return resp, {} - else: - return resp, json.loads(resp.content) - - @property - def uri(self): - format = (self.base_uri, self.name) - return "%s/%s" % format - - -class InstanceResource(Resource): - - subresources = [] - id_key = "sid" - - def __init__(self, parent, sid): - self.parent = parent - self.name = sid - super(InstanceResource, self).__init__(parent.uri, parent.auth) - - def load(self, entries): - if "from" in entries.keys(): - entries["from_"] = entries["from"] - del entries["from"] - - if "uri" in entries.keys(): - del entries["uri"] - - self.__dict__.update(entries) - - def load_subresources(self): - """ - Load all subresources - """ - for resource in self.subresources: - list_resource = resource(self.uri, self.parent.auth) - self.__dict__[list_resource.key] = list_resource - - def update_instance(self, **kwargs): - a = self.parent.update(self.name, **kwargs) - self.load(a.__dict__) - - def delete_instance(self): - return self.parent.delete(self.name) - - -class ListResource(Resource): - - name = "Resources" - instance = InstanceResource - - def __init__(self, *args, **kwargs): - super(ListResource, self).__init__(*args, **kwargs) - - try: - self.key - except AttributeError: - self.key = self.name.lower() - - def get(self, sid): - """Return an instance resource""" - return self.get_instance(sid) - - def get_instance(self, sid): - """Request the specified instance resource""" - uri = "%s/%s" % (self.uri, sid) - resp, item = self.request("GET", uri) - return self.load_instance(item) - - def get_instances(self, params): - """ - Query the list resource for a list of InstanceResources. - - Raises a TwilioRestException if requesting a page of results that does - not exist. - - :param dict params: List of URL parameters to be included in request - :param int page: The page of results to retrieve (most recent at 0) - :param int page_size: The number of results to be returned. - - :returns: -- the list of resources - """ - params = transform_params(params) - - resp, page = self.request("GET", self.uri, params=params) - - if self.key not in page: - raise TwilioException("Key %s not present in response" % self.key) - - return [self.load_instance(ir) for ir in page[self.key]] - - def create_instance(self, body): - """ - Create an InstanceResource via a POST to the List Resource - - :param dict body: Dictionary of POST data - """ - resp, instance = self.request("POST", self.uri, - data=transform_params(body)) - - if resp.status_code != 201: - raise TwilioRestException(resp.status, - self.uri, "Resource not created") - - return self.load_instance(instance) - - def delete_instance(self, sid): - """ - Delete an InstanceResource via DELETE - - body: string -- HTTP Body for the quest - """ - uri = "%s/%s" % (self.uri, sid) - resp, instance = self.request("DELETE", uri) - return resp.status_code == 204 - - def update_instance(self, sid, body): - """ - Update an InstanceResource via a POST - - sid: string -- String identifier for the list resource - body: dictionary -- Dict of items to POST - """ - uri = "%s/%s" % (self.uri, sid) - resp, entry = self.request("POST", uri, data=transform_params(body)) - return self.load_instance(entry) - - def count(self): - """ - Return the number of instance resources contained in this list resource - """ - resp, page = self.request("GET", self.uri) - return page["total"] - - def iter(self, **kwargs): - """ - Return all instance resources using an iterator - """ - params = transform_params(kwargs) - - while True: - resp, page = self.request("GET", self.uri, params=params) - - if self.key not in page: - raise StopIteration() - - for ir in page[self.key]: - yield self.load_instance(ir) - - if not page.get('next_page_uri', ''): - raise StopIteration() - - o = urlparse(page['next_page_uri']) - params.update(parse_qs(o.query)) - - def load_instance(self, data): - instance = self.instance(self, data[self.instance.id_key]) - instance.load(data) - instance.load_subresources() - return instance diff --git a/twilio/rest/resources/caller_ids.py b/twilio/rest/resources/caller_ids.py deleted file mode 100644 index e53038c20d..0000000000 --- a/twilio/rest/resources/caller_ids.py +++ /dev/null @@ -1,72 +0,0 @@ -from twilio.rest.resources import transform_params -from twilio.rest.resources import InstanceResource, ListResource - - -class CallerId(InstanceResource): - - def delete(self): - """ - Deletes this caller ID from the account. - """ - return self.delete_instance() - - def update(self, **kwargs): - """ - Update the CallerId - """ - self.update_instance(**kwargs) - - -class CallerIds(ListResource): - """ A list of :class:`CallerId` resources """ - - name = "OutgoingCallerIds" - key = "outgoing_caller_ids" - instance = CallerId - - def delete(self, sid): - """ - Deletes a specific :class:`CallerId` from the account. - """ - self.delete_instance(sid) - - def list(self, **kwargs): - """ - :param phone_number: Show caller ids with this phone number. - :param friendly_name: Show caller ids with this friendly name. - """ - return self.get_instances(kwargs) - - def update(self, sid, **kwargs): - """ - Update a specific :class:`CallerId` - """ - return self.update_instance(sid, kwargs) - - def validate(self, phone_number, **kwargs): - """ - Begin the validation process for the given number. - - Returns a dictionary with the following keys - - **account_sid**: - The unique id of the Account to which the Validation Request belongs. - - **phone_number**: The incoming phone number being validated, - formatted with a '+' and country code e.g., +16175551212 - - **friendly_name**: The friendly name you provided, if any. - - **validation_code**: The 6 digit validation code that must be entered - via the phone to validate this phone number for Caller ID. - - :param phone_number: The phone number to call and validate - :param friendly_name: A description for the new caller ID - :param call_delay: Number of seconds to delay the validation call. - :param extension: Digits to dial after connecting the validation call. - :returns: A response dictionary - """ - kwargs["phone_number"] = phone_number - params = transform_params(kwargs) - resp, validation = self.request("POST", self.uri, data=params) - return validation diff --git a/twilio/rest/resources/calls.py b/twilio/rest/resources/calls.py deleted file mode 100644 index de6c124aca..0000000000 --- a/twilio/rest/resources/calls.py +++ /dev/null @@ -1,146 +0,0 @@ -from twilio.rest.resources.notifications import Notifications -from twilio.rest.resources.recordings import Recordings -from twilio.rest.resources.util import normalize_dates, parse_date -from twilio.rest.resources import InstanceResource, ListResource - - -class Call(InstanceResource): - """ A call resource """ - - BUSY = "busy" - CANCELED = "canceled" - COMPLETED = "completed" - FAILED = "failed" - IN_PROGRESS = "in-progress" - NO_ANSWER = "no-answer" - QUEUED = "queued" - RINGING = "ringing" - - subresources = [ - Notifications, - Recordings, - ] - - def hangup(self): - """ If this call is currenlty active, hang up the call. - If this call is scheduled to be made, remove the call - from the queue - """ - a = self.parent.hangup(self.name) - self.load(a.__dict__) - - def cancel(self): - """ If the called is queued or rining, cancel the calls. - Will not affect in progress calls - """ - a = self.parent.cancel(self.name) - self.load(a.__dict__) - - def route(self, **kwargs): - """Route the specified :class:`Call` to another url. - - :param url: A valid URL that returns TwiML. - :param method: HTTP method Twilio uses when requesting the above URL. - """ - a = self.parent.route(self.name, **kwargs) - self.load(a.__dict__) - - -class Calls(ListResource): - """ A list of Call resources """ - - name = "Calls" - instance = Call - - @normalize_dates - def list(self, from_=None, ended_after=None, - ended_before=None, ended=None, started_before=None, - started_after=None, started=None, **kwargs): - """ - Returns a page of :class:`Call` resources as a list. For paging - informtion see :class:`ListResource` - - :param date after: Only list calls started after this datetime - :param date before: Only list calls started before this datetime - """ - kwargs["from"] = from_ - kwargs["StartTime<"] = started_before - kwargs["StartTime>"] = started_after - kwargs["StartTime"] = parse_date(started) - kwargs["EndTime<"] = ended_before - kwargs["EndTime>"] = ended_after - kwargs["EndTime"] = parse_date(ended) - return self.get_instances(kwargs) - - def create(self, to, from_, url, status_method=None, **kwargs): - """ - Make a phone call to a number. - - :param string to: The phone number to call - :param string `from_`: The caller ID (must be a verified Twilio number) - :param string url: The URL to read TwiML from when the call connects - :param method: The HTTP method Twilio should use to request the url - :type method: None (defaults to 'POST'), 'GET', or 'POST' - :param string fallback_url: A URL that Twilio will request if an error - occurs requesting or executing the TwiML at url - :param string fallback_method: The HTTP method that Twilio should use - to request the fallback_url - :type fallback_method: None (will make 'POST' request), - 'GET', or 'POST' - :param string status_callback: A URL that Twilio will request when the - call ends to notify your app. - :param string status_method: The HTTP method Twilio should use when - requesting the above URL. - :param string if_machine: Tell Twilio to try and determine if a machine - (like voicemail) or a human has answered the call. - See more in our `answering machine documentation - <http://www.twilio.com/docs/api/rest/making_calls>`_. - :type if_machine: None, 'Continue', or 'Hangup' - :param string send_digits: A string of keys to dial after - connecting to the number. - :type send_digits: None or any combination of - (0-9), '#', '*' or 'w' (to insert a half second pause). - :param int timeout: The integer number of seconds that Twilio should - allow the phone to ring before assuming there is no answer. - :param string application_sid: The 34 character sid of the application - Twilio should use to handle this phone call. - Should not be used in conjunction with the url parameter. - - :return: A :class:`Call` object - """ - kwargs["from"] = from_ - kwargs["to"] = to - kwargs["url"] = url - kwargs["status_callback_method"] = status_method - return self.create_instance(kwargs) - - def update(self, sid, **kwargs): - return self.update_instance(sid, kwargs) - - def cancel(self, sid): - """ If this call is queued or ringing, cancel the call. - Will not affect in-progress calls. - - :param sid: A Call Sid for a specific call - :returns: Updated :class:`Call` resource - """ - return self.update(sid, status=Call.CANCELED) - - def hangup(self, sid): - """ If this call is currently active, hang up the call. If this call is - scheduled to be made, remove the call from the queue. - - :param sid: A Call Sid for a specific call - :returns: Updated :class:`Call` resource - """ - return self.update(sid, status=Call.COMPLETED) - - def route(self, sid, url, method="POST"): - """Route the specified :class:`Call` to another url. - - :param sid: A Call Sid for a specific call - :param url: A valid URL that returns TwiML. - :param method: The HTTP method Twilio uses when requesting the URL. - :returns: Updated :class:`Call` resource - """ - return self.update(sid, url=url, method=method) diff --git a/twilio/rest/resources/conferences.py b/twilio/rest/resources/conferences.py deleted file mode 100644 index b5e771ee5d..0000000000 --- a/twilio/rest/resources/conferences.py +++ /dev/null @@ -1,106 +0,0 @@ -from twilio.rest.resources.util import parse_date, normalize_dates -from twilio.rest.resources import InstanceResource, ListResource - - -class Participant(InstanceResource): - - id_key = "call_sid" - - def mute(self): - """ - Mute the participant - """ - self.update_instance(muted="true") - - def unmute(self): - """ - Unmute the participant - """ - self.update_instance(muted="false") - - def kick(self): - """ - Remove the participant from the given conference - """ - self.delete_instance() - - -class Participants(ListResource): - - name = "Participants" - instance = Participant - - def list(self, **kwargs): - """ - Returns a list of :class:`Participant` resources in the given - conference - - :param conference_sid: Conference this participant is part of - :param boolean muted: If True, only show participants who are muted - """ - return self.get_instances(kwargs) - - def mute(self, call_sid): - """ - Mute the given participant - """ - return self.update(call_sid, muted=True) - - def unmute(self, call_sid): - """ - Unmute the given participant - """ - return self.update(call_sid, muted=False) - - def kick(self, call_sid): - """ - Remove the participant from the given conference - """ - return self.delete(call_sid) - - def delete(self, call_sid): - """ - Remove the participant from the given conference - """ - return self.delete_instance(call_sid) - - def update(self, sid, **kwargs): - """ - :param sid: Participant identifier - :param boolean muted: If true, mute this participant - """ - return self.update_instance(sid, kwargs) - - -class Conference(InstanceResource): - - subresources = [ - Participants - ] - - -class Conferences(ListResource): - - name = "Conferences" - instance = Conference - - @normalize_dates - def list(self, updated_before=None, updated_after=None, created_after=None, - created_before=None, updated=None, created=None, **kwargs): - """ - Return a list of :class:`Conference` resources - - :param status: Show conferences with this status - :param friendly_name: Show conferences with this exact friendly_name - :param date updated_after: List conferences updated after this date - :param date updated_before: List conferences updated before this date - :param date created_after: List conferences created after this date - :param date created_before: List conferences created before this date - """ - kwargs["DateUpdated"] = parse_date(kwargs.get("date_updated", updated)) - kwargs["DateCreated"] = parse_date(kwargs.get("date_created", created)) - kwargs["DateUpdated<"] = updated_before - kwargs["DateUpdated>"] = updated_after - kwargs["DateCreated<"] = created_before - kwargs["DateCreated>"] = created_after - return self.get_instances(kwargs) diff --git a/twilio/rest/resources/connect_apps.py b/twilio/rest/resources/connect_apps.py deleted file mode 100644 index 97cd25926e..0000000000 --- a/twilio/rest/resources/connect_apps.py +++ /dev/null @@ -1,46 +0,0 @@ -from twilio.rest.resources import InstanceResource, ListResource -from six import iteritems - - -class ConnectApp(InstanceResource): - """ An authorized connect app """ - pass - - -class ConnectApps(ListResource): - """ A list of Connect App resources """ - - name = "ConnectApps" - instance = ConnectApp - key = "connect_apps" - - def list(self, **kwargs): - """ - Returns a page of :class:`ConnectApp` resources as a list. For paging - informtion see :class:`ListResource` - """ - return self.get_instances(kwargs) - - -class AuthorizedConnectApp(ConnectApp): - """ An authorized connect app """ - - id_key = "connect_app_sid" - - def load(self, entries): - """ Translate certain parameters into others""" - result = {} - - for k, v in iteritems(entries): - k = k.replace("connect_app_", "") - result[k] = v - - super(AuthorizedConnectApp, self).load(result) - - -class AuthorizedConnectApps(ConnectApps): - """ A list of Authorized Connect App resources """ - - name = "AuthorizedConnectApps" - instance = AuthorizedConnectApp - key = "authorized_connect_apps" diff --git a/twilio/rest/resources/imports.py b/twilio/rest/resources/imports.py deleted file mode 100644 index 1b24b45d1e..0000000000 --- a/twilio/rest/resources/imports.py +++ /dev/null @@ -1,17 +0,0 @@ -# parse_qs -try: - from urlparse import parse_qs -except ImportError: - from cgi import parse_qs - -# json -try: - import json -except ImportError: - try: - import simplejson as json - except ImportError: - from django.utils import simplejson as json - -# httplib2 -import httplib2 diff --git a/twilio/rest/resources/notifications.py b/twilio/rest/resources/notifications.py deleted file mode 100644 index 46d35c19e8..0000000000 --- a/twilio/rest/resources/notifications.py +++ /dev/null @@ -1,41 +0,0 @@ -from twilio.rest.resources.util import normalize_dates -from twilio.rest.resources import InstanceResource, ListResource - - -class Notification(InstanceResource): - - def delete(self): - """ - Delete this notification - """ - return self.delete_instance() - - -class Notifications(ListResource): - - name = "Notifications" - instance = Notification - - @normalize_dates - def list(self, before=None, after=None, **kwargs): - """ - Returns a page of :class:`Notification` resources as a list. - For paging information see :class:`ListResource`. - - **NOTE**: Due to the potentially voluminous amount of data in a - notification, the full HTTP request and response data is only returned - in the Notification instance resource representation. - - :param date after: Only list notifications logged after this datetime - :param date before: Only list notifications logger before this datetime - :param log_level: If 1, only shows errors. If 0, only show warnings - """ - kwargs["MessageDate<"] = before - kwargs["MessageDate>"] = after - return self.get_instances(kwargs) - - def delete(self, sid): - """ - Delete a given Notificiation - """ - return self.delete_instance(sid) diff --git a/twilio/rest/resources/phone_numbers.py b/twilio/rest/resources/phone_numbers.py deleted file mode 100644 index 013e73c7d6..0000000000 --- a/twilio/rest/resources/phone_numbers.py +++ /dev/null @@ -1,183 +0,0 @@ -import re - -from twilio import TwilioException -from twilio.rest.resources.util import change_dict_key, transform_params -from twilio.rest.resources import InstanceResource, ListResource - - -class AvailablePhoneNumber(InstanceResource): - """ An available phone number resource """ - - def __init__(self, parent): - super(AvailablePhoneNumber, self).__init__(parent, "") - self.name = "" - - def purchase(self, **kwargs): - return self.parent.purchase(phone_number=self.phone_number, - **kwargs) - - -class AvailablePhoneNumbers(ListResource): - - name = "AvailablePhoneNumbers" - key = "available_phone_numbers" - instance = AvailablePhoneNumber - - types = {"local": "Local", "tollfree": "TollFree"} - - def __init__(self, base_uri, auth, phone_numbers): - super(AvailablePhoneNumbers, self).__init__(base_uri, auth) - self.phone_numbers = phone_numbers - - def get(self, sid): - raise TwilioException("Individual AvailablePhoneNumbers have no sid") - - def list(self, type="local", country="US", region=None, postal_code=None, - lata=None, rate_center=None, **kwargs): - """ - Search for phone numbers - """ - kwargs["in_region"] = kwargs.get("in_region", region) - kwargs["in_postal_code"] = kwargs.get("in_postal_code", postal_code) - kwargs["in_lata"] = kwargs.get("in_lata", lata) - kwargs["in_rate_center"] = kwargs.get("in_rate_center", rate_center) - params = transform_params(kwargs) - - uri = "%s/%s/%s" % (self.uri, country, self.types[type]) - resp, page = self.request("GET", uri, params=params) - - return [self.load_instance(i) for i in page[self.key]] - - def load_instance(self, data): - instance = self.instance(self.phone_numbers) - instance.load(data) - instance.load_subresources() - return instance - - -class PhoneNumber(InstanceResource): - - def load(self, entries): - """ Set the proper Account owner of this phone number """ - - # Only check if entries has a uri - if "account_sid" in entries: - # Parse the parent's uri to get the scheme and base - uri = re.sub(r'AC(.*)', entries["account_sid"], - self.parent.base_uri) - - self.parent = PhoneNumbers(uri, self.parent.auth) - self.base_uri = self.parent.uri - - super(PhoneNumber, self).load(entries) - - def transfer(self, account_sid): - """ - Transfer the phone number with sid from the current account to another - identified by account_sid - """ - a = self.parent.transfer(self.name, account_sid) - self.load(a.__dict__) - - def update(self, **kwargs): - """ - Update this phone number instance. - """ - kwargs_copy = dict(kwargs) - change_dict_key(kwargs_copy, from_key="status_callback_url", - to_key="status_callback") - - a = self.parent.update(self.name, **kwargs_copy) - self.load(a.__dict__) - - def delete(self): - """ - Release this phone number from your account. Twilio will no longer - answer calls to this number, and you will stop being billed the monthly - phone number fees. The phone number will eventually be recycled and - potentially given to another customer, so use with care. If you make a - mistake, contact us... we may be able to give you the number back. - """ - return self.parent.delete(self.name) - - -class PhoneNumbers(ListResource): - - name = "IncomingPhoneNumbers" - key = "incoming_phone_numbers" - instance = PhoneNumber - - def __init__(self, base_uri, auth): - super(PhoneNumbers, self).__init__(base_uri, auth) - self.available_phone_numbers = \ - AvailablePhoneNumbers(base_uri, auth, self) - - def delete(self, sid): - """ - Release this phone number from your account. Twilio will no longer - answer calls to this number, and you will stop being billed the - monthly phone number fees. The phone number will eventually be - recycled and potentially given to another customer, so use with care. - If you make a mistake, contact us... we may be able to give you the - number back. - """ - return self.delete_instance(sid) - - def list(self, **kwargs): - """ - :param phone_number: Show phone numbers that match this pattern. - :param friendly_name: Show phone numbers with this friendly name - - You can specify partial numbers and use '*' as a wildcard. - """ - return self.get_instances(kwargs) - - def purchase(self, status_callback_url=None, **kwargs): - """ - Attempt to purchase the specified number. The only required parameters - are **either** phone_number or area_code - - :returns: Returns a :class:`PhoneNumber` instance on success, - :data:`False` on failure - """ - kwargs["StatusCallback"] = kwargs.get("status_callback", - status_callback_url) - - if 'phone_number' not in kwargs and 'area_code' not in kwargs: - raise TypeError("phone_number or area_code is required") - - return self.create_instance(kwargs) - - def search(self, **kwargs): - """ - :param type: The type of phone number to search for. - :param string country: Only show numbers for this country (iso2) - :param string region: When searching the US, show numbers in this state - :param string postal_code: Only show numbers in this area code - :param string rate_center: US only. - :param tuple near_lat_long: Find close numbers within Distance miles. - :param integer distance: Search radius for a Near- query in miles. - """ - return self.available_phone_numbers.list(**kwargs) - - def transfer(self, sid, account_sid): - """ - Transfer the phone number with sid from the current account to another - identified by account_sid - """ - return self.update(sid, account_sid=account_sid) - - def update(self, sid, **kwargs): - """ - Update this phone number instance - """ - kwargs_copy = dict(kwargs) - change_dict_key(kwargs_copy, from_key="status_callback_url", - to_key="status_callback") - - if "application_sid" in kwargs_copy: - for sid_type in ["voice_application_sid", "sms_application_sid"]: - if sid_type not in kwargs_copy: - kwargs_copy[sid_type] = kwargs_copy["application_sid"] - del kwargs_copy["application_sid"] - return self.update_instance(sid, kwargs_copy) diff --git a/twilio/rest/resources/queues.py b/twilio/rest/resources/queues.py deleted file mode 100644 index 8081aa3cc4..0000000000 --- a/twilio/rest/resources/queues.py +++ /dev/null @@ -1,97 +0,0 @@ -from twilio.rest.resources import InstanceResource, ListResource - - -class Member(InstanceResource): - id_key = "call_sid" - - -class Members(ListResource): - name = "Members" - instance = Member - key = "queue_members" - - def list(self, **kwargs): - """ - Returns a list of :class:`Member` resources in the given queue - - :param queue_sid: Queue this participant is part of - """ - return self.get_instances(kwargs) - - def dequeue(self, url, call_sid='Front', **kwargs): - """ - Dequeues a member from the queue and have the member's call - begin executing the TwiML document at the url. - - :param call_sid: Call sid specifying the member, if not given, - the member at the front of the queue will be used - :param url: url of the TwiML document to be executed. - """ - kwargs['url'] = url - return self.update_instance(call_sid, kwargs) - - -class Queue(InstanceResource): - - subresources = [ - Members - ] - - def update(self, **kwargs): - """ - Update this queue - - :param friendly_name: A new friendly name for this queue - :param max_size: A new max size. Changing a max size to less than the - current size results in the queue rejecting incoming - requests until it shrinks below the new max size - """ - return self.parent.update_instance(self.name, kwargs) - - def delete(self): - """ - Delete this queue. Can only be run on empty queues. - """ - return self.parent.delete_instance(self.name) - - -class Queues(ListResource): - name = "Queues" - instance = Queue - - def list(self, **kwargs): - """ - Returns a page of :class:`Queue` resources as a list sorted - by DateUpdated. For paging informtion see :class:`ListResource` - """ - return self.get_instances(kwargs) - - def create(self, name, **kwargs): - """ Create an :class:`Queue` with any of these optional parameters. - - :param name: A human readable description of the application, - with maximum length 64 characters. - :param max_size: The limit on calls allowed into the queue (optional) - """ - kwargs['friendly_name'] = name - return self.create_instance(kwargs) - - def update(self, sid, **kwargs): - """ - Update a :class:`Queue` - - :param sid: String identifier for a Queue resource - :param friendly_name: A new friendly name for this queue - :param max_size: A new max size. Changing a max size to less than the - current size results in the queue rejecting incoming - requests until it shrinks below the new max size - """ - return self.update_instance(sid, kwargs) - - def delete(self, sid): - """ - Delete a :class:`Queue`. Can only be run on empty queues. - - :param sid: String identifier for a Queue resource - """ - return self.delete_instance(sid) diff --git a/twilio/rest/resources/recordings.py b/twilio/rest/resources/recordings.py deleted file mode 100644 index e800e9aa98..0000000000 --- a/twilio/rest/resources/recordings.py +++ /dev/null @@ -1,63 +0,0 @@ -from twilio.rest.resources.util import normalize_dates - -from twilio.rest.resources import InstanceResource, ListResource - - -class Transcription(InstanceResource): - pass - - -class Transcriptions(ListResource): - - name = "Transcriptions" - instance = Transcription - - def list(self, **kwargs): - """ - Return a list of :class:`Transcription` resources - """ - return self.get_instances(kwargs) - - -class Recording(InstanceResource): - - subresources = [Transcriptions] - - def __init__(self, *args, **kwargs): - super(Recording, self).__init__(*args, **kwargs) - self.formats = { - "mp3": self.uri + ".mp3", - "wav": self.uri + ".wav", - } - - def delete(self): - """ - Delete this recording - """ - return self.delete_instance() - - -class Recordings(ListResource): - - name = "Recordings" - instance = Recording - - @normalize_dates - def list(self, before=None, after=None, **kwargs): - """ - Returns a page of :class:`Recording` resources as a list. - For paging information see :class:`ListResource`. - - :param date after: Only list recordings logged after this datetime - :param date before: Only list recordings logger before this datetime - :param call_sid: Only list recordings from this :class:`Call` - """ - kwargs["DateCreated<"] = before - kwargs["DateCreated>"] = after - return self.get_instances(kwargs) - - def delete(self, sid): - """ - Delete the given recording - """ - return self.delete_instance(sid) diff --git a/twilio/rest/resources/sandboxes.py b/twilio/rest/resources/sandboxes.py deleted file mode 100644 index 691e296325..0000000000 --- a/twilio/rest/resources/sandboxes.py +++ /dev/null @@ -1,32 +0,0 @@ -from twilio.rest.resources.util import transform_params -from twilio.rest.resources import InstanceResource, ListResource - - -class Sandbox(InstanceResource): - - id_key = "pin" - - def update(self, **kwargs): - """ - Update your Twilio Sandbox - """ - a = self.parent.update(**kwargs) - self.load(a.__dict__) - - -class Sandboxes(ListResource): - - name = "Sandbox" - instance = Sandbox - - def get(self): - """Request the specified instance resource""" - return self.get_instance(self.uri) - - def update(self, **kwargs): - """ - Update your Twilio Sandbox - """ - resp, entry = self.request("POST", self.uri, - body=transform_params(kwargs)) - return self.create_instance(entry) diff --git a/twilio/rest/resources/sms_messages.py b/twilio/rest/resources/sms_messages.py deleted file mode 100644 index 78fc1755b9..0000000000 --- a/twilio/rest/resources/sms_messages.py +++ /dev/null @@ -1,116 +0,0 @@ -from twilio.rest.resources.util import normalize_dates, parse_date -from twilio.rest.resources import InstanceResource, ListResource - - -class ShortCode(InstanceResource): - - def update(self, **kwargs): - return self.parent.update(self.name, **kwargs) - - -class ShortCodes(ListResource): - - name = "ShortCodes" - key = "short_codes" - instance = ShortCode - - def list(self, **kwargs): - """ - Returns a page of :class:`ShortCode` resources as a list. For - paging information see :class:`ListResource`. - - :param short_code: Only show the ShortCode resources that match this - pattern. You can specify partial numbers and use '*' - as a wildcard for any digit. - :param friendly_name: Only show the ShortCode resources with friendly - names that exactly match this name. - """ - return self.get_instances(kwargs) - - def update(self, sid, url=None, method=None, fallback_url=None, - fallback_method=None, **kwargs): - """ - Update a specific :class:`ShortCode`, by specifying the sid. - - :param friendly_name: Description of the short code, with maximum - length 64 characters. - :param api_version: SMSs to this short code will start a new TwiML - session with this API version. - :param url: The URL that Twilio should request when somebody sends an - SMS to the short code. - :param method: The HTTP method that should be used to request the url. - :param fallback_url: A URL that Twilio will request if an error occurs - requesting or executing the TwiML at the url. - :param fallback_method: The HTTP method that should be used to request - the fallback_url. - """ - kwargs["sms_url"] = kwargs.get("sms_url", url) - kwargs["sms_method"] = kwargs.get("sms_method", method) - kwargs["sms_fallback_url"] = \ - kwargs.get("sms_fallback_url", fallback_url) - kwargs["sms_fallback_method"] = \ - kwargs.get("sms_fallback_method", fallback_method) - return self.update_instance(sid, kwargs) - - -class Sms(object): - """ - Holds all the specific SMS list resources - """ - - name = "SMS" - key = "sms" - - def __init__(self, base_uri, auth): - self.uri = "%s/SMS" % base_uri - self.messages = SmsMessages(self.uri, auth) - self.short_codes = ShortCodes(self.uri, auth) - - -class SmsMessage(InstanceResource): - pass - - -class SmsMessages(ListResource): - - name = "Messages" - key = "sms_messages" - instance = SmsMessage - - def create(self, from_=None, **kwargs): - """ - Create and send a SMS Message. - - :param string to: The destination phone number. - :param string `from_`: The phone number sending this message - (must be a verified Twilio number) - :param string body: The message you want to send, - limited to 160 characters. - :param status_callback: A URL that Twilio will POST to when - your message is processed. - :param string application_sid: The 34 character sid of the application - Twilio should use to handle this phone call. - """ - kwargs["from"] = from_ - return self.create_instance(kwargs) - - @normalize_dates - def list(self, from_=None, before=None, after=None, date_sent=None, **kw): - """ - Returns a page of :class:`SMSMessage` resources as a list. For - paging informtion see :class:`ListResource`. - - :param to: Only show SMS messages to this phone number. - :param from_: Only show SMS messages from this phone number. - :param date after: Only list SMS messages sent after this date. - :param date before: Only list SMS message sent before this date. - :param date date_sent: Only list SMS message sent on this date. - :param `from_`: Only show SMS messages from this phone number. - :param date after: Only list recordings logged after this datetime - :param date before: Only list recordings logged before this datetime - """ - kw["From"] = from_ - kw["DateSent<"] = before - kw["DateSent>"] = after - kw["DateSent"] = parse_date(date_sent) - return self.get_instances(kw) diff --git a/twilio/rest/resources/usage.py b/twilio/rest/resources/usage.py deleted file mode 100644 index cff21acf2e..0000000000 --- a/twilio/rest/resources/usage.py +++ /dev/null @@ -1,178 +0,0 @@ -from twilio.rest.resources import InstanceResource, ListResource - - -class UsageTrigger(InstanceResource): - """ A usage trigger resource """ - - def update(self, **kwargs): - """ - Update this usage trigger - """ - return self.parent.update(self.sid, **kwargs) - - def delete(self): - """ - Delete this usage trigger - """ - return self.parent.delete(self.sid) - - -class UsageTriggers(ListResource): - name = "Usage/Triggers" - instance = UsageTrigger - key = "usage_triggers" - - def list(self, **kwargs): - """ - Returns a page of :class:`UsageTrigger` resources as a list. For paging - information see :class:`ListResource` - - :param recurring: Only show UsageTriggers that count over this - interval. One of daily, monthly, or yearly. To - retrieve non-recurring triggers, leave this empty or - use alltime. - :param usage_category: Only show UsageTriggers that watch this usage - category. Must be one of the supported usage - categories. - :trigger_by: Only show UsageTriggers that trigger by this field in the - UsageRecord. Must be one of: count, usage, or price as - described in the UsageRecords documentation. - """ - return self.get_instances(kwargs) - - def create(self, **kwargs): - """ - Create an :class:`Application` with any of these optional parameters. - - :param friendly_name: A human readable description of the application, - with maximum length 64 characters. - :param usage_category: The trigger will watch this usage category. - :param trigger_value: The trigger will fire when usage reaches this - value. - :param callback_url: Twilio will make a request to this url when the - trigger fires. - :param trigger_by: The field in the UsageRecord that will fire the - trigger. One of count, usage, or price as described - in the UsageRecords documentation. The default is - usage. - :param recurring: The interval the trigger will count over. Must be one - of: daily, monthly, or yearly. Omit this to create a - non-recurring trigger. - :param callback_method: Twilio will use this HTTP method when making a - request to the CallbackUrl. GET or POST. The - default is POST. - """ - return self.create_instance(kwargs) - - def update(self, sid, **kwargs): - """ Update the UsageTrigger with the given sid to have the kwargs """ - return self.update_instance(sid, kwargs) - - def delete(self, sid): - """ - Delete a :class:`UsageTrigger` - """ - return self.delete_instance(sid) - - -class UsageRecord(InstanceResource): - """ A usage record resource """ - - def load(self, entries): - uri = entries.get('uri') - super(UsageRecord, self).load(entries) - self.__dict__.update({'uri': uri}) - - @property - def uri(self): - return self.__dict__.get('uri') - - -class BaseUsageRecords(ListResource): - name = "Usage/Records" - instance = UsageRecord - key = "usage_records" - - def list(self, **kwargs): - """ - Returns a page of :class:`UsageRecord` resources as a list. For paging - information see :class:`ListResource` - - :param category: Only include usage of this usage category. - :param start_date: Only include usage that has occurred on or after - this date. Format is YYYY-MM-DD. All dates are in - GMT. - :param end_date: Only include usage that has occurred on or before this - date. Format is YYYY-MM-DD. All dates are in GMT. - """ - return self.get_instances(kwargs) - - def get(self, *args, **kwargs): - raise AttributeError('Unsupported in UsageRecords') - - def load_instance(self, data): - instance = self.instance(self, "Resource") - instance.load(data) - instance.load_subresources() - return instance - - -class UsageRecords(BaseUsageRecords): - - def __init__(self, base_uri, auth): - super(UsageRecords, self).__init__(base_uri, auth) - self.daily = UsageRecordsDaily(base_uri, auth) - self.monthly = UsageRecordsMonthly(base_uri, auth) - self.yearly = UsageRecordsYearly(base_uri, auth) - self.today = UsageRecordsToday(base_uri, auth) - self.yesterday = UsageRecordsYesterday(base_uri, auth) - self.this_month = UsageRecordsThisMonth(base_uri, auth) - self.last_month = UsageRecordsLastMonth(base_uri, auth) - - -class UsageRecordsDaily(BaseUsageRecords): - name = "Usage/Records/Daily" - - -class UsageRecordsMonthly(BaseUsageRecords): - name = "Usage/Records/Monthly" - - -class UsageRecordsYearly(BaseUsageRecords): - name = "Usage/Records/Yearly" - - -class UsageRecordsToday(BaseUsageRecords): - name = "Usage/Records/Today" - - -class UsageRecordsYesterday(BaseUsageRecords): - name = "Usage/Records/Yesterday" - - -class UsageRecordsThisMonth(BaseUsageRecords): - name = "Usage/Records/ThisMonth" - - -class UsageRecordsLastMonth(BaseUsageRecords): - name = "Usage/Records/LastMonth" - -UsageRecord.subresources = [ - UsageRecordsDaily, - UsageRecordsMonthly, - UsageRecordsYearly, - UsageRecordsToday, - UsageRecordsYesterday, - UsageRecordsThisMonth, - UsageRecordsLastMonth -] - - -class Usage(object): - """ - Holds all the specific Usage list resources - """ - - def __init__(self, base_uri, auth): - self.records = UsageRecords(base_uri, auth) - self.triggers = UsageTriggers(base_uri, auth) diff --git a/twilio/rest/resources/util.py b/twilio/rest/resources/util.py deleted file mode 100644 index 61a35f03db..0000000000 --- a/twilio/rest/resources/util.py +++ /dev/null @@ -1,111 +0,0 @@ -import datetime -from six import iteritems - - -def transform_params(parameters): - """ - Transform parameters, throwing away any None values - and convert False and True values to strings - - Ex: - {"record": true, "date_created": "2012-01-02"} - - becomes: - {"Record": "true", "DateCreated": "2012-01-02"} - """ - transformed_parameters = {} - - for key, value in iteritems(parameters): - if value is not None: - transformed_parameters[format_name(key)] = convert_boolean(value) - - return transformed_parameters - - -def format_name(word): - if word.lower() == word: - return convert_case(word) - else: - return word - - -def parse_date(d): - """ - Return a string representation of a date that the Twilio API understands - Format is YYYY-MM-DD. Returns None if d is not a string, datetime, or date - """ - if isinstance(d, datetime.datetime): - return str(d.date()) - elif isinstance(d, datetime.date): - return str(d) - elif isinstance(d, str): - return d - - -def convert_boolean(boolean): - if isinstance(boolean, bool): - return 'true' if boolean else 'false' - return boolean - - -def convert_case(s): - """ - Given a string in snake case, convert to CamelCase - - Ex: - date_created -> DateCreated - """ - return ''.join([a.title() for a in s.split("_") if a]) - - -def convert_keys(d): - """ - Return a dictionary with all keys converted from arguments - """ - special = { - "started_before": "StartTime<", - "started_after": "StartTime>", - "started": "StartTime", - "ended_before": "EndTime<", - "ended_after": "EndTime>", - "ended": "EndTime", - "from_": "From", - } - - result = {} - - for k, v in iteritems(d): - if k in special: - result[special[k]] = v - else: - result[convert_case(k)] = v - - return result - - -def normalize_dates(myfunc): - def inner_func(*args, **kwargs): - for k, v in iteritems(kwargs): - res = [True for s in ["after", "before", "on"] if s in k] - if len(res): - kwargs[k] = parse_date(v) - return myfunc(*args, **kwargs) - inner_func.__doc__ = myfunc.__doc__ - inner_func.__repr__ = myfunc.__repr__ - return inner_func - - -def change_dict_key(d, from_key, to_key): - """ - Changes a dictionary's key from from_key to to_key. - No-op if the key does not exist. - - :param d: Dictionary with key to change - :param from_key: Old key - :param to_key: New key - :return: None - """ - try: - d[to_key] = d.pop(from_key) - except KeyError: - pass diff --git a/twilio/rest/routes/RoutesBase.py b/twilio/rest/routes/RoutesBase.py new file mode 100644 index 0000000000..a47d67f093 --- /dev/null +++ b/twilio/rest/routes/RoutesBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.routes.v2 import V2 + + +class RoutesBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Routes Domain + + :returns: Domain for Routes + """ + super().__init__(twilio, "https://routes.twilio.com") + self._v2: Optional[V2] = None + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Routes + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Routes>" diff --git a/twilio/rest/routes/__init__.py b/twilio/rest/routes/__init__.py new file mode 100644 index 0000000000..a559ba0df4 --- /dev/null +++ b/twilio/rest/routes/__init__.py @@ -0,0 +1,35 @@ +from warnings import warn + +from twilio.rest.routes.RoutesBase import RoutesBase +from twilio.rest.routes.v2.phone_number import PhoneNumberList +from twilio.rest.routes.v2.sip_domain import SipDomainList +from twilio.rest.routes.v2.trunk import TrunkList + + +class Routes(RoutesBase): + @property + def phone_numbers(self) -> PhoneNumberList: + warn( + "phone_numbers is deprecated. Use v2.phone_numbers instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.phone_numbers + + @property + def sip_domains(self) -> SipDomainList: + warn( + "sip_domains is deprecated. Use v2.sip_domains instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.sip_domains + + @property + def trunks(self) -> TrunkList: + warn( + "trunks is deprecated. Use v2.trunks instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.trunks diff --git a/twilio/rest/routes/v2/__init__.py b/twilio/rest/routes/v2/__init__.py new file mode 100644 index 0000000000..56a140efc3 --- /dev/null +++ b/twilio/rest/routes/v2/__init__.py @@ -0,0 +1,59 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Routes + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.routes.v2.phone_number import PhoneNumberList +from twilio.rest.routes.v2.sip_domain import SipDomainList +from twilio.rest.routes.v2.trunk import TrunkList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Routes + + :param domain: The Twilio.routes domain + """ + super().__init__(domain, "v2") + self._phone_numbers: Optional[PhoneNumberList] = None + self._sip_domains: Optional[SipDomainList] = None + self._trunks: Optional[TrunkList] = None + + @property + def phone_numbers(self) -> PhoneNumberList: + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList(self) + return self._phone_numbers + + @property + def sip_domains(self) -> SipDomainList: + if self._sip_domains is None: + self._sip_domains = SipDomainList(self) + return self._sip_domains + + @property + def trunks(self) -> TrunkList: + if self._trunks is None: + self._trunks = TrunkList(self) + return self._trunks + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Routes.V2>" diff --git a/twilio/rest/routes/v2/phone_number.py b/twilio/rest/routes/v2/phone_number.py new file mode 100644 index 0000000000..1b67509bb0 --- /dev/null +++ b/twilio/rest/routes/v2/phone_number.py @@ -0,0 +1,311 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Routes + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PhoneNumberInstance(InstanceResource): + """ + :ivar phone_number: The phone number in E.164 format + :ivar url: The absolute URL of the resource. + :ivar sid: A 34 character string that uniquely identifies the Inbound Processing Region assignments for this phone number. + :ivar account_sid: The unique SID identifier of the Account. + :ivar friendly_name: A human readable description of the Inbound Processing Region assignments for this phone number, up to 64 characters. + :ivar voice_region: The Inbound Processing Region used for this phone number for voice. + :ivar date_created: The date that this phone number was assigned an Inbound Processing Region, given in ISO 8601 format. + :ivar date_updated: The date that the Inbound Processing Region was updated for this phone number, given in ISO 8601 format. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + phone_number: Optional[str] = None, + ): + super().__init__(version) + + self.phone_number: Optional[str] = payload.get("phone_number") + self.url: Optional[str] = payload.get("url") + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.voice_region: Optional[str] = payload.get("voice_region") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "phone_number": phone_number or self.phone_number, + } + self._context: Optional[PhoneNumberContext] = None + + @property + def _proxy(self) -> "PhoneNumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PhoneNumberContext for this PhoneNumberInstance + """ + if self._context is None: + self._context = PhoneNumberContext( + self._version, + phone_number=self._solution["phone_number"], + ) + return self._context + + def fetch(self) -> "PhoneNumberInstance": + """ + Fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "PhoneNumberInstance": + """ + Update the PhoneNumberInstance + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated PhoneNumberInstance + """ + return self._proxy.update( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + async def update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to update the PhoneNumberInstance + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated PhoneNumberInstance + """ + return await self._proxy.update_async( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Routes.V2.PhoneNumberInstance {}>".format(context) + + +class PhoneNumberContext(InstanceContext): + + def __init__(self, version: Version, phone_number: str): + """ + Initialize the PhoneNumberContext + + :param version: Version that contains the resource + :param phone_number: The phone number in E.164 format + """ + super().__init__(version) + + # Path Solution + self._solution = { + "phone_number": phone_number, + } + self._uri = "/PhoneNumbers/{phone_number}".format(**self._solution) + + def fetch(self) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + async def fetch_async(self) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + def update( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Update the PhoneNumberInstance + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated PhoneNumberInstance + """ + + data = values.of( + { + "VoiceRegion": voice_region, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, payload, phone_number=self._solution["phone_number"] + ) + + async def update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> PhoneNumberInstance: + """ + Asynchronous coroutine to update the PhoneNumberInstance + + :param voice_region: The Inbound Processing Region used for this phone number for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated PhoneNumberInstance + """ + + data = values.of( + { + "VoiceRegion": voice_region, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, payload, phone_number=self._solution["phone_number"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Routes.V2.PhoneNumberContext {}>".format(context) + + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PhoneNumberList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, phone_number: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param phone_number: The phone number in E.164 format + """ + return PhoneNumberContext(self._version, phone_number=phone_number) + + def __call__(self, phone_number: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param phone_number: The phone number in E.164 format + """ + return PhoneNumberContext(self._version, phone_number=phone_number) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Routes.V2.PhoneNumberList>" diff --git a/twilio/rest/routes/v2/sip_domain.py b/twilio/rest/routes/v2/sip_domain.py new file mode 100644 index 0000000000..2326a5dbc1 --- /dev/null +++ b/twilio/rest/routes/v2/sip_domain.py @@ -0,0 +1,311 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Routes + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SipDomainInstance(InstanceResource): + """ + :ivar sip_domain: + :ivar url: + :ivar sid: + :ivar account_sid: + :ivar friendly_name: + :ivar voice_region: + :ivar date_created: + :ivar date_updated: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + sip_domain: Optional[str] = None, + ): + super().__init__(version) + + self.sip_domain: Optional[str] = payload.get("sip_domain") + self.url: Optional[str] = payload.get("url") + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.voice_region: Optional[str] = payload.get("voice_region") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "sip_domain": sip_domain or self.sip_domain, + } + self._context: Optional[SipDomainContext] = None + + @property + def _proxy(self) -> "SipDomainContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SipDomainContext for this SipDomainInstance + """ + if self._context is None: + self._context = SipDomainContext( + self._version, + sip_domain=self._solution["sip_domain"], + ) + return self._context + + def fetch(self) -> "SipDomainInstance": + """ + Fetch the SipDomainInstance + + + :returns: The fetched SipDomainInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SipDomainInstance": + """ + Asynchronous coroutine to fetch the SipDomainInstance + + + :returns: The fetched SipDomainInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "SipDomainInstance": + """ + Update the SipDomainInstance + + :param voice_region: + :param friendly_name: + + :returns: The updated SipDomainInstance + """ + return self._proxy.update( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + async def update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "SipDomainInstance": + """ + Asynchronous coroutine to update the SipDomainInstance + + :param voice_region: + :param friendly_name: + + :returns: The updated SipDomainInstance + """ + return await self._proxy.update_async( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Routes.V2.SipDomainInstance {}>".format(context) + + +class SipDomainContext(InstanceContext): + + def __init__(self, version: Version, sip_domain: str): + """ + Initialize the SipDomainContext + + :param version: Version that contains the resource + :param sip_domain: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sip_domain": sip_domain, + } + self._uri = "/SipDomains/{sip_domain}".format(**self._solution) + + def fetch(self) -> SipDomainInstance: + """ + Fetch the SipDomainInstance + + + :returns: The fetched SipDomainInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SipDomainInstance( + self._version, + payload, + sip_domain=self._solution["sip_domain"], + ) + + async def fetch_async(self) -> SipDomainInstance: + """ + Asynchronous coroutine to fetch the SipDomainInstance + + + :returns: The fetched SipDomainInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SipDomainInstance( + self._version, + payload, + sip_domain=self._solution["sip_domain"], + ) + + def update( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> SipDomainInstance: + """ + Update the SipDomainInstance + + :param voice_region: + :param friendly_name: + + :returns: The updated SipDomainInstance + """ + + data = values.of( + { + "VoiceRegion": voice_region, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SipDomainInstance( + self._version, payload, sip_domain=self._solution["sip_domain"] + ) + + async def update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> SipDomainInstance: + """ + Asynchronous coroutine to update the SipDomainInstance + + :param voice_region: + :param friendly_name: + + :returns: The updated SipDomainInstance + """ + + data = values.of( + { + "VoiceRegion": voice_region, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SipDomainInstance( + self._version, payload, sip_domain=self._solution["sip_domain"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Routes.V2.SipDomainContext {}>".format(context) + + +class SipDomainList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SipDomainList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sip_domain: str) -> SipDomainContext: + """ + Constructs a SipDomainContext + + :param sip_domain: + """ + return SipDomainContext(self._version, sip_domain=sip_domain) + + def __call__(self, sip_domain: str) -> SipDomainContext: + """ + Constructs a SipDomainContext + + :param sip_domain: + """ + return SipDomainContext(self._version, sip_domain=sip_domain) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Routes.V2.SipDomainList>" diff --git a/twilio/rest/routes/v2/trunk.py b/twilio/rest/routes/v2/trunk.py new file mode 100644 index 0000000000..f783ce92ca --- /dev/null +++ b/twilio/rest/routes/v2/trunk.py @@ -0,0 +1,311 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Routes + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TrunkInstance(InstanceResource): + """ + :ivar sip_trunk_domain: The absolute URL of the SIP Trunk + :ivar url: The absolute URL of the resource. + :ivar sid: A 34 character string that uniquely identifies the Inbound Processing Region assignments for this SIP Trunk. + :ivar account_sid: The unique SID identifier of the Account. + :ivar friendly_name: A human readable description of the Inbound Processing Region assignments for this SIP Trunk, up to 64 characters. + :ivar voice_region: The Inbound Processing Region used for this SIP Trunk for voice. + :ivar date_created: The date that this SIP Trunk was assigned an Inbound Processing Region, given in ISO 8601 format. + :ivar date_updated: The date that the Inbound Processing Region was updated for this SIP Trunk, given in ISO 8601 format. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + sip_trunk_domain: Optional[str] = None, + ): + super().__init__(version) + + self.sip_trunk_domain: Optional[str] = payload.get("sip_trunk_domain") + self.url: Optional[str] = payload.get("url") + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.voice_region: Optional[str] = payload.get("voice_region") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "sip_trunk_domain": sip_trunk_domain or self.sip_trunk_domain, + } + self._context: Optional[TrunkContext] = None + + @property + def _proxy(self) -> "TrunkContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TrunkContext for this TrunkInstance + """ + if self._context is None: + self._context = TrunkContext( + self._version, + sip_trunk_domain=self._solution["sip_trunk_domain"], + ) + return self._context + + def fetch(self) -> "TrunkInstance": + """ + Fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TrunkInstance": + """ + Asynchronous coroutine to fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "TrunkInstance": + """ + Update the TrunkInstance + + :param voice_region: The Inbound Processing Region used for this SIP Trunk for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated TrunkInstance + """ + return self._proxy.update( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + async def update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "TrunkInstance": + """ + Asynchronous coroutine to update the TrunkInstance + + :param voice_region: The Inbound Processing Region used for this SIP Trunk for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated TrunkInstance + """ + return await self._proxy.update_async( + voice_region=voice_region, + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Routes.V2.TrunkInstance {}>".format(context) + + +class TrunkContext(InstanceContext): + + def __init__(self, version: Version, sip_trunk_domain: str): + """ + Initialize the TrunkContext + + :param version: Version that contains the resource + :param sip_trunk_domain: The absolute URL of the SIP Trunk + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sip_trunk_domain": sip_trunk_domain, + } + self._uri = "/Trunks/{sip_trunk_domain}".format(**self._solution) + + def fetch(self) -> TrunkInstance: + """ + Fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TrunkInstance( + self._version, + payload, + sip_trunk_domain=self._solution["sip_trunk_domain"], + ) + + async def fetch_async(self) -> TrunkInstance: + """ + Asynchronous coroutine to fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TrunkInstance( + self._version, + payload, + sip_trunk_domain=self._solution["sip_trunk_domain"], + ) + + def update( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> TrunkInstance: + """ + Update the TrunkInstance + + :param voice_region: The Inbound Processing Region used for this SIP Trunk for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated TrunkInstance + """ + + data = values.of( + { + "VoiceRegion": voice_region, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrunkInstance( + self._version, payload, sip_trunk_domain=self._solution["sip_trunk_domain"] + ) + + async def update_async( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> TrunkInstance: + """ + Asynchronous coroutine to update the TrunkInstance + + :param voice_region: The Inbound Processing Region used for this SIP Trunk for voice + :param friendly_name: A human readable description of this resource, up to 64 characters. + + :returns: The updated TrunkInstance + """ + + data = values.of( + { + "VoiceRegion": voice_region, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrunkInstance( + self._version, payload, sip_trunk_domain=self._solution["sip_trunk_domain"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Routes.V2.TrunkContext {}>".format(context) + + +class TrunkList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TrunkList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sip_trunk_domain: str) -> TrunkContext: + """ + Constructs a TrunkContext + + :param sip_trunk_domain: The absolute URL of the SIP Trunk + """ + return TrunkContext(self._version, sip_trunk_domain=sip_trunk_domain) + + def __call__(self, sip_trunk_domain: str) -> TrunkContext: + """ + Constructs a TrunkContext + + :param sip_trunk_domain: The absolute URL of the SIP Trunk + """ + return TrunkContext(self._version, sip_trunk_domain=sip_trunk_domain) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Routes.V2.TrunkList>" diff --git a/twilio/rest/serverless/ServerlessBase.py b/twilio/rest/serverless/ServerlessBase.py new file mode 100644 index 0000000000..d6e227c0b7 --- /dev/null +++ b/twilio/rest/serverless/ServerlessBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.serverless.v1 import V1 + + +class ServerlessBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Serverless Domain + + :returns: Domain for Serverless + """ + super().__init__(twilio, "https://serverless.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Serverless + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Serverless>" diff --git a/twilio/rest/serverless/__init__.py b/twilio/rest/serverless/__init__.py new file mode 100644 index 0000000000..a9f32edb0f --- /dev/null +++ b/twilio/rest/serverless/__init__.py @@ -0,0 +1,15 @@ +from warnings import warn + +from twilio.rest.serverless.ServerlessBase import ServerlessBase +from twilio.rest.serverless.v1.service import ServiceList + + +class Serverless(ServerlessBase): + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v1.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.services diff --git a/twilio/rest/serverless/v1/__init__.py b/twilio/rest/serverless/v1/__init__.py new file mode 100644 index 0000000000..e494615caf --- /dev/null +++ b/twilio/rest/serverless/v1/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.serverless.v1.service import ServiceList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Serverless + + :param domain: The Twilio.serverless domain + """ + super().__init__(domain, "v1") + self._services: Optional[ServiceList] = None + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1>" diff --git a/twilio/rest/serverless/v1/service/__init__.py b/twilio/rest/serverless/v1/service/__init__.py new file mode 100644 index 0000000000..f6e4e5841e --- /dev/null +++ b/twilio/rest/serverless/v1/service/__init__.py @@ -0,0 +1,742 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.serverless.v1.service.asset import AssetList +from twilio.rest.serverless.v1.service.build import BuildList +from twilio.rest.serverless.v1.service.environment import EnvironmentList +from twilio.rest.serverless.v1.service.function import FunctionList + + +class ServiceInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Service resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + :ivar friendly_name: The string that you assigned to describe the Service resource. + :ivar unique_name: A user-defined string that uniquely identifies the Service resource. It can be used in place of the Service resource's `sid` in the URL to address the Service resource. + :ivar include_credentials: Whether to inject Account credentials into a function invocation context. + :ivar ui_editable: Whether the Service resource's properties and subresources can be edited via the UI. + :ivar domain_base: The base domain name for this Service, which is a combination of the unique name and a randomly generated string. + :ivar date_created: The date and time in GMT when the Service resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Service resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Service resource. + :ivar links: The URLs of the Service's nested resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.include_credentials: Optional[bool] = payload.get("include_credentials") + self.ui_editable: Optional[bool] = payload.get("ui_editable") + self.domain_base: Optional[str] = payload.get("domain_base") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param include_credentials: Whether to inject Account credentials into a function invocation context. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param ui_editable: Whether the Service resource's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) + + async def update_async( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param include_credentials: Whether to inject Account credentials into a function invocation context. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param ui_editable: Whether the Service resource's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + include_credentials=include_credentials, + friendly_name=friendly_name, + ui_editable=ui_editable, + ) + + @property + def assets(self) -> AssetList: + """ + Access the assets + """ + return self._proxy.assets + + @property + def builds(self) -> BuildList: + """ + Access the builds + """ + return self._proxy.builds + + @property + def environments(self) -> EnvironmentList: + """ + Access the environments + """ + return self._proxy.environments + + @property + def functions(self) -> FunctionList: + """ + Access the functions + """ + return self._proxy.functions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Serverless.V1.ServiceInstance {}>".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The `sid` or `unique_name` of the Service resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._assets: Optional[AssetList] = None + self._builds: Optional[BuildList] = None + self._environments: Optional[EnvironmentList] = None + self._functions: Optional[FunctionList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param include_credentials: Whether to inject Account credentials into a function invocation context. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param ui_editable: Whether the Service resource's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "IncludeCredentials": serialize.boolean_to_string(include_credentials), + "FriendlyName": friendly_name, + "UiEditable": serialize.boolean_to_string(ui_editable), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + include_credentials: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param include_credentials: Whether to inject Account credentials into a function invocation context. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param ui_editable: Whether the Service resource's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "IncludeCredentials": serialize.boolean_to_string(include_credentials), + "FriendlyName": friendly_name, + "UiEditable": serialize.boolean_to_string(ui_editable), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def assets(self) -> AssetList: + """ + Access the assets + """ + if self._assets is None: + self._assets = AssetList( + self._version, + self._solution["sid"], + ) + return self._assets + + @property + def builds(self) -> BuildList: + """ + Access the builds + """ + if self._builds is None: + self._builds = BuildList( + self._version, + self._solution["sid"], + ) + return self._builds + + @property + def environments(self) -> EnvironmentList: + """ + Access the environments + """ + if self._environments is None: + self._environments = EnvironmentList( + self._version, + self._solution["sid"], + ) + return self._environments + + @property + def functions(self) -> FunctionList: + """ + Access the functions + """ + if self._functions is None: + self._functions = FunctionList( + self._version, + self._solution["sid"], + ) + return self._functions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Serverless.V1.ServiceContext {}>".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1.ServicePage>" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create( + self, + unique_name: str, + friendly_name: str, + include_credentials: Union[bool, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param unique_name: A user-defined string that uniquely identifies the Service resource. It can be used as an alternative to the `sid` in the URL path to address the Service resource. This value must be 50 characters or less in length and be unique. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param include_credentials: Whether to inject Account credentials into a function invocation context. The default value is `true`. + :param ui_editable: Whether the Service's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "IncludeCredentials": serialize.boolean_to_string(include_credentials), + "UiEditable": serialize.boolean_to_string(ui_editable), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async( + self, + unique_name: str, + friendly_name: str, + include_credentials: Union[bool, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param unique_name: A user-defined string that uniquely identifies the Service resource. It can be used as an alternative to the `sid` in the URL path to address the Service resource. This value must be 50 characters or less in length and be unique. + :param friendly_name: A descriptive string that you create to describe the Service resource. It can be a maximum of 255 characters. + :param include_credentials: Whether to inject Account credentials into a function invocation context. The default value is `true`. + :param ui_editable: Whether the Service's properties and subresources can be edited via the UI. The default value is `false`. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "IncludeCredentials": serialize.boolean_to_string(include_credentials), + "UiEditable": serialize.boolean_to_string(ui_editable), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The `sid` or `unique_name` of the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The `sid` or `unique_name` of the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1.ServiceList>" diff --git a/twilio/rest/serverless/v1/service/asset/__init__.py b/twilio/rest/serverless/v1/service/asset/__init__.py new file mode 100644 index 0000000000..de68b969be --- /dev/null +++ b/twilio/rest/serverless/v1/service/asset/__init__.py @@ -0,0 +1,649 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.serverless.v1.service.asset.asset_version import AssetVersionList + + +class AssetInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Asset resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Asset resource. + :ivar service_sid: The SID of the Service that the Asset resource is associated with. + :ivar friendly_name: The string that you assigned to describe the Asset resource. It can be a maximum of 255 characters. + :ivar date_created: The date and time in GMT when the Asset resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Asset resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Asset resource. + :ivar links: The URLs of the Asset resource's nested resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[AssetContext] = None + + @property + def _proxy(self) -> "AssetContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AssetContext for this AssetInstance + """ + if self._context is None: + self._context = AssetContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AssetInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssetInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "AssetInstance": + """ + Fetch the AssetInstance + + + :returns: The fetched AssetInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AssetInstance": + """ + Asynchronous coroutine to fetch the AssetInstance + + + :returns: The fetched AssetInstance + """ + return await self._proxy.fetch_async() + + def update(self, friendly_name: str) -> "AssetInstance": + """ + Update the AssetInstance + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: The updated AssetInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async(self, friendly_name: str) -> "AssetInstance": + """ + Asynchronous coroutine to update the AssetInstance + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: The updated AssetInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + @property + def asset_versions(self) -> AssetVersionList: + """ + Access the asset_versions + """ + return self._proxy.asset_versions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Serverless.V1.AssetInstance {}>".format(context) + + +class AssetContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the AssetContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to update the Asset resource from. + :param sid: The SID that identifies the Asset resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Assets/{sid}".format(**self._solution) + + self._asset_versions: Optional[AssetVersionList] = None + + def delete(self) -> bool: + """ + Deletes the AssetInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AssetInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> AssetInstance: + """ + Fetch the AssetInstance + + + :returns: The fetched AssetInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AssetInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AssetInstance: + """ + Asynchronous coroutine to fetch the AssetInstance + + + :returns: The fetched AssetInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AssetInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update(self, friendly_name: str) -> AssetInstance: + """ + Update the AssetInstance + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: The updated AssetInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssetInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, friendly_name: str) -> AssetInstance: + """ + Asynchronous coroutine to update the AssetInstance + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: The updated AssetInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssetInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def asset_versions(self) -> AssetVersionList: + """ + Access the asset_versions + """ + if self._asset_versions is None: + self._asset_versions = AssetVersionList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._asset_versions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Serverless.V1.AssetContext {}>".format(context) + + +class AssetPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AssetInstance: + """ + Build an instance of AssetInstance + + :param payload: Payload response from the API + """ + return AssetInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1.AssetPage>" + + +class AssetList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the AssetList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Asset resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Assets".format(**self._solution) + + def create(self, friendly_name: str) -> AssetInstance: + """ + Create the AssetInstance + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: The created AssetInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssetInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async(self, friendly_name: str) -> AssetInstance: + """ + Asynchronously create the AssetInstance + + :param friendly_name: A descriptive string that you create to describe the Asset resource. It can be a maximum of 255 characters. + + :returns: The created AssetInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AssetInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssetInstance]: + """ + Streams AssetInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AssetInstance]: + """ + Asynchronously streams AssetInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssetInstance]: + """ + Lists AssetInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssetInstance]: + """ + Asynchronously lists AssetInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssetPage: + """ + Retrieve a single page of AssetInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssetInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssetPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssetPage: + """ + Asynchronously retrieve a single page of AssetInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssetInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssetPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AssetPage: + """ + Retrieve a specific page of AssetInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssetInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AssetPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AssetPage: + """ + Asynchronously retrieve a specific page of AssetInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssetInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssetPage(self._version, response, self._solution) + + def get(self, sid: str) -> AssetContext: + """ + Constructs a AssetContext + + :param sid: The SID that identifies the Asset resource to update. + """ + return AssetContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> AssetContext: + """ + Constructs a AssetContext + + :param sid: The SID that identifies the Asset resource to update. + """ + return AssetContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1.AssetList>" diff --git a/twilio/rest/serverless/v1/service/asset/asset_version.py b/twilio/rest/serverless/v1/service/asset/asset_version.py new file mode 100644 index 0000000000..31f85d4c29 --- /dev/null +++ b/twilio/rest/serverless/v1/service/asset/asset_version.py @@ -0,0 +1,468 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class AssetVersionInstance(InstanceResource): + + class Visibility(object): + PUBLIC = "public" + PRIVATE = "private" + PROTECTED = "protected" + + """ + :ivar sid: The unique string that we created to identify the Asset Version resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Asset Version resource. + :ivar service_sid: The SID of the Service that the Asset Version resource is associated with. + :ivar asset_sid: The SID of the Asset resource that is the parent of the Asset Version. + :ivar path: The URL-friendly string by which the Asset Version can be referenced. It can be a maximum of 255 characters. All paths begin with a forward slash ('/'). If an Asset Version creation request is submitted with a path not containing a leading slash, the path will automatically be prepended with one. + :ivar visibility: + :ivar date_created: The date and time in GMT when the Asset Version resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Asset Version resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + asset_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.asset_sid: Optional[str] = payload.get("asset_sid") + self.path: Optional[str] = payload.get("path") + self.visibility: Optional["AssetVersionInstance.Visibility"] = payload.get( + "visibility" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "asset_sid": asset_sid, + "sid": sid or self.sid, + } + self._context: Optional[AssetVersionContext] = None + + @property + def _proxy(self) -> "AssetVersionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AssetVersionContext for this AssetVersionInstance + """ + if self._context is None: + self._context = AssetVersionContext( + self._version, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AssetVersionInstance": + """ + Fetch the AssetVersionInstance + + + :returns: The fetched AssetVersionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AssetVersionInstance": + """ + Asynchronous coroutine to fetch the AssetVersionInstance + + + :returns: The fetched AssetVersionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Serverless.V1.AssetVersionInstance {}>".format(context) + + +class AssetVersionContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, asset_sid: str, sid: str): + """ + Initialize the AssetVersionContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Asset Version resource from. + :param asset_sid: The SID of the Asset resource that is the parent of the Asset Version resource to fetch. + :param sid: The SID of the Asset Version resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "asset_sid": asset_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Assets/{asset_sid}/Versions/{sid}".format( + **self._solution + ) + + def fetch(self) -> AssetVersionInstance: + """ + Fetch the AssetVersionInstance + + + :returns: The fetched AssetVersionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AssetVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AssetVersionInstance: + """ + Asynchronous coroutine to fetch the AssetVersionInstance + + + :returns: The fetched AssetVersionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AssetVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Serverless.V1.AssetVersionContext {}>".format(context) + + +class AssetVersionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AssetVersionInstance: + """ + Build an instance of AssetVersionInstance + + :param payload: Payload response from the API + """ + return AssetVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1.AssetVersionPage>" + + +class AssetVersionList(ListResource): + + def __init__(self, version: Version, service_sid: str, asset_sid: str): + """ + Initialize the AssetVersionList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Asset Version resource from. + :param asset_sid: The SID of the Asset resource that is the parent of the Asset Version resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "asset_sid": asset_sid, + } + self._uri = "/Services/{service_sid}/Assets/{asset_sid}/Versions".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AssetVersionInstance]: + """ + Streams AssetVersionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AssetVersionInstance]: + """ + Asynchronously streams AssetVersionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssetVersionInstance]: + """ + Lists AssetVersionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AssetVersionInstance]: + """ + Asynchronously lists AssetVersionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssetVersionPage: + """ + Retrieve a single page of AssetVersionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssetVersionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssetVersionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AssetVersionPage: + """ + Asynchronously retrieve a single page of AssetVersionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of AssetVersionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AssetVersionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> AssetVersionPage: + """ + Retrieve a specific page of AssetVersionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssetVersionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AssetVersionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> AssetVersionPage: + """ + Asynchronously retrieve a specific page of AssetVersionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AssetVersionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AssetVersionPage(self._version, response, self._solution) + + def get(self, sid: str) -> AssetVersionContext: + """ + Constructs a AssetVersionContext + + :param sid: The SID of the Asset Version resource to fetch. + """ + return AssetVersionContext( + self._version, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AssetVersionContext: + """ + Constructs a AssetVersionContext + + :param sid: The SID of the Asset Version resource to fetch. + """ + return AssetVersionContext( + self._version, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1.AssetVersionList>" diff --git a/twilio/rest/serverless/v1/service/build/__init__.py b/twilio/rest/serverless/v1/service/build/__init__.py new file mode 100644 index 0000000000..5a7b6b7023 --- /dev/null +++ b/twilio/rest/serverless/v1/service/build/__init__.py @@ -0,0 +1,614 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.serverless.v1.service.build.build_status import BuildStatusList + + +class BuildInstance(InstanceResource): + + + class Runtime(object): + NODE8 = "node8" + NODE10 = "node10" + NODE12 = "node12" + NODE14 = "node14" + NODE16 = "node16" + NODE18 = "node18" + NODE20 = "node20" + NODE22 = "node22" + + class Status(object): + BUILDING = "building" + COMPLETED = "completed" + FAILED = "failed" + + """ + :ivar sid: The unique string that we created to identify the Build resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Build resource. + :ivar service_sid: The SID of the Service that the Build resource is associated with. + :ivar status: + :ivar asset_versions: The list of Asset Version resource SIDs that are included in the Build. + :ivar function_versions: The list of Function Version resource SIDs that are included in the Build. + :ivar dependencies: A list of objects that describe the Dependencies included in the Build. Each object contains the `name` and `version` of the dependency. + :ivar runtime: + :ivar date_created: The date and time in GMT when the Build resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Build resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Build resource. + :ivar links: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], service_sid: str, sid: Optional[str] = None): + super().__init__(version) + + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.status: Optional["BuildInstance.Status"] = payload.get("status") + self.asset_versions: Optional[List[Dict[str, object]]] = payload.get("asset_versions") + self.function_versions: Optional[List[Dict[str, object]]] = payload.get("function_versions") + self.dependencies: Optional[List[Dict[str, object]]] = payload.get("dependencies") + self.runtime: Optional["BuildInstance.Runtime"] = payload.get("runtime") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime(payload.get("date_created")) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime(payload.get("date_updated")) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[BuildContext] = None + + @property + def _proxy(self) -> "BuildContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BuildContext for this BuildInstance + """ + if self._context is None: + self._context = BuildContext(self._version, service_sid=self._solution['service_sid'], sid=self._solution['sid'],) + return self._context + + + def delete(self) -> bool: + """ + Deletes the BuildInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BuildInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + + def fetch(self) -> "BuildInstance": + """ + Fetch the BuildInstance + + + :returns: The fetched BuildInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BuildInstance": + """ + Asynchronous coroutine to fetch the BuildInstance + + + :returns: The fetched BuildInstance + """ + return await self._proxy.fetch_async() + + @property + def build_status(self) -> BuildStatusList: + """ + Access the build_status + """ + return self._proxy.build_status + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) + return '<Twilio.Serverless.V1.BuildInstance {}>'.format(context) + +class BuildContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the BuildContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Build resource from. + :param sid: The SID of the Build resource to fetch. + """ + super().__init__(version) + + + # Path Solution + self._solution = { + 'service_sid': service_sid, + 'sid': sid, + } + self._uri = '/Services/{service_sid}/Builds/{sid}'.format(**self._solution) + + self._build_status: Optional[BuildStatusList] = None + + + def delete(self) -> bool: + """ + Deletes the BuildInstance + + + :returns: True if delete succeeds, False otherwise + """ + + + headers = values.of({}) + + + + return self._version.delete(method='DELETE', uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BuildInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + + + return await self._version.delete_async(method='DELETE', uri=self._uri, headers=headers) + + + def fetch(self) -> BuildInstance: + """ + Fetch the BuildInstance + + + :returns: The fetched BuildInstance + """ + + + headers = values.of({}) + + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method='GET', uri=self._uri , headers=headers) + + return BuildInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + + async def fetch_async(self) -> BuildInstance: + """ + Asynchronous coroutine to fetch the BuildInstance + + + :returns: The fetched BuildInstance + """ + + + headers = values.of({}) + + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async(method='GET', uri=self._uri , headers=headers) + + return BuildInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + + + @property + def build_status(self) -> BuildStatusList: + """ + Access the build_status + """ + if self._build_status is None: + self._build_status = BuildStatusList( + self._version, + self._solution['service_sid'], + self._solution['sid'], + ) + return self._build_status + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) + return '<Twilio.Serverless.V1.BuildContext {}>'.format(context) + + + + + + + + + +class BuildPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BuildInstance: + """ + Build an instance of BuildInstance + + :param payload: Payload response from the API + """ + return BuildInstance(self._version, payload, service_sid=self._solution["service_sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1.BuildPage>" + + + + + +class BuildList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the BuildList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Build resources from. + + """ + super().__init__(version) + + + # Path Solution + self._solution = { 'service_sid': service_sid, } + self._uri = '/Services/{service_sid}/Builds'.format(**self._solution) + + + + + + def create(self, asset_versions: Union[List[str], object]=values.unset, function_versions: Union[List[str], object]=values.unset, dependencies: Union[str, object]=values.unset, runtime: Union[str, object]=values.unset) -> BuildInstance: + """ + Create the BuildInstance + + :param asset_versions: The list of Asset Version resource SIDs to include in the Build. + :param function_versions: The list of the Function Version resource SIDs to include in the Build. + :param dependencies: A list of objects that describe the Dependencies included in the Build. Each object contains the `name` and `version` of the dependency. + :param runtime: The Runtime version that will be used to run the Build resource when it is deployed. + + :returns: The created BuildInstance + """ + + data = values.of({ + 'AssetVersions': serialize.map(asset_versions, lambda e: e), + 'FunctionVersions': serialize.map(function_versions, lambda e: e), + 'Dependencies': dependencies, + 'Runtime': runtime, + }) + headers = values.of({ + 'Content-Type': 'application/x-www-form-urlencoded' + }) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + + headers["Accept"] = "application/json" + + + payload = self._version.create(method='POST', uri=self._uri, data=data, headers=headers) + + return BuildInstance(self._version, payload, service_sid=self._solution['service_sid']) + + async def create_async(self, asset_versions: Union[List[str], object]=values.unset, function_versions: Union[List[str], object]=values.unset, dependencies: Union[str, object]=values.unset, runtime: Union[str, object]=values.unset) -> BuildInstance: + """ + Asynchronously create the BuildInstance + + :param asset_versions: The list of Asset Version resource SIDs to include in the Build. + :param function_versions: The list of the Function Version resource SIDs to include in the Build. + :param dependencies: A list of objects that describe the Dependencies included in the Build. Each object contains the `name` and `version` of the dependency. + :param runtime: The Runtime version that will be used to run the Build resource when it is deployed. + + :returns: The created BuildInstance + """ + + data = values.of({ + 'AssetVersions': serialize.map(asset_versions, lambda e: e), + 'FunctionVersions': serialize.map(function_versions, lambda e: e), + 'Dependencies': dependencies, + 'Runtime': runtime, + }) + headers = values.of({ + 'Content-Type': 'application/x-www-form-urlencoded' + }) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + + headers["Accept"] = "application/json" + + + payload = await self._version.create_async(method='POST', uri=self._uri, data=data, headers=headers) + + return BuildInstance(self._version, payload, service_sid=self._solution['service_sid']) + + + def stream(self, + + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BuildInstance]: + """ + Streams BuildInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + page_size=limits['page_size'] + ) + + return self._version.stream(page, limits['limit']) + + async def stream_async(self, + + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BuildInstance]: + """ + Asynchronously streams BuildInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + page_size=limits['page_size'] + ) + + return self._version.stream_async(page, limits['limit']) + + def list(self, + + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BuildInstance]: + """ + Lists BuildInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list(self.stream( + limit=limit, + page_size=page_size, + )) + + async def list_async(self, + + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BuildInstance]: + """ + Asynchronously lists BuildInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [record async for record in await self.stream_async( + limit=limit, + page_size=page_size, + )] + + def page(self, + + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BuildPage: + """ + Retrieve a single page of BuildInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BuildInstance + """ + data = values.of({ + 'PageToken': page_token, + 'Page': page_number, + 'PageSize': page_size, + }) + + headers = values.of({ + 'Content-Type': 'application/x-www-form-urlencoded' + }) + + + headers["Accept"] = "application/json" + + + response = self._version.page(method='GET', uri=self._uri, params=data, headers=headers) + return BuildPage(self._version, response, self._solution) + + async def page_async(self, + + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BuildPage: + """ + Asynchronously retrieve a single page of BuildInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BuildInstance + """ + data = values.of({ + 'PageToken': page_token, + 'Page': page_number, + 'PageSize': page_size, + }) + + headers = values.of({ + 'Content-Type': 'application/x-www-form-urlencoded' + }) + + + headers["Accept"] = "application/json" + + + response = await self._version.page_async(method='GET', uri=self._uri, params=data, headers=headers) + return BuildPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> BuildPage: + """ + Retrieve a specific page of BuildInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BuildInstance + """ + response = self._version.domain.twilio.request( + 'GET', + target_url + ) + return BuildPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> BuildPage: + """ + Asynchronously retrieve a specific page of BuildInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BuildInstance + """ + response = await self._version.domain.twilio.request_async( + 'GET', + target_url + ) + return BuildPage(self._version, response, self._solution) + + + + + + def get(self, sid: str) -> BuildContext: + """ + Constructs a BuildContext + + :param sid: The SID of the Build resource to fetch. + """ + return BuildContext(self._version, service_sid=self._solution['service_sid'], sid=sid) + + def __call__(self, sid: str) -> BuildContext: + """ + Constructs a BuildContext + + :param sid: The SID of the Build resource to fetch. + """ + return BuildContext(self._version, service_sid=self._solution['service_sid'], sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return '<Twilio.Serverless.V1.BuildList>' + diff --git a/twilio/rest/serverless/v1/service/build/build_status.py b/twilio/rest/serverless/v1/service/build/build_status.py new file mode 100644 index 0000000000..e67c00e00e --- /dev/null +++ b/twilio/rest/serverless/v1/service/build/build_status.py @@ -0,0 +1,221 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + + +class BuildStatusInstance(InstanceResource): + + + class Status(object): + BUILDING = "building" + COMPLETED = "completed" + FAILED = "failed" + + """ + :ivar sid: The unique string that we created to identify the Build resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Build resource. + :ivar service_sid: The SID of the Service that the Build resource is associated with. + :ivar status: + :ivar url: The absolute URL of the Build Status resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], service_sid: str, sid: str): + super().__init__(version) + + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.status: Optional["BuildStatusInstance.Status"] = payload.get("status") + self.url: Optional[str] = payload.get("url") + + + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._context: Optional[BuildStatusContext] = None + + @property + def _proxy(self) -> "BuildStatusContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BuildStatusContext for this BuildStatusInstance + """ + if self._context is None: + self._context = BuildStatusContext(self._version, service_sid=self._solution['service_sid'], sid=self._solution['sid'],) + return self._context + + + def fetch(self) -> "BuildStatusInstance": + """ + Fetch the BuildStatusInstance + + + :returns: The fetched BuildStatusInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BuildStatusInstance": + """ + Asynchronous coroutine to fetch the BuildStatusInstance + + + :returns: The fetched BuildStatusInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) + return '<Twilio.Serverless.V1.BuildStatusInstance {}>'.format(context) + +class BuildStatusContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the BuildStatusContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Build resource from. + :param sid: The SID of the Build resource to fetch. + """ + super().__init__(version) + + + # Path Solution + self._solution = { + 'service_sid': service_sid, + 'sid': sid, + } + self._uri = '/Services/{service_sid}/Builds/{sid}/Status'.format(**self._solution) + + + + def fetch(self) -> BuildStatusInstance: + """ + Fetch the BuildStatusInstance + + + :returns: The fetched BuildStatusInstance + """ + + + headers = values.of({}) + + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method='GET', uri=self._uri , headers=headers) + + return BuildStatusInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + + async def fetch_async(self) -> BuildStatusInstance: + """ + Asynchronous coroutine to fetch the BuildStatusInstance + + + :returns: The fetched BuildStatusInstance + """ + + + headers = values.of({}) + + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async(method='GET', uri=self._uri , headers=headers) + + return BuildStatusInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items()) + return '<Twilio.Serverless.V1.BuildStatusContext {}>'.format(context) + + + +class BuildStatusList(ListResource): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the BuildStatusList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Build resource from. + :param sid: The SID of the Build resource to fetch. + + """ + super().__init__(version) + + + # Path Solution + self._solution = { 'service_sid': service_sid, 'sid': sid, } + + + + + def get(self) -> BuildStatusContext: + """ + Constructs a BuildStatusContext + + """ + return BuildStatusContext(self._version, service_sid=self._solution['service_sid'], sid=self._solution['sid']) + + def __call__(self) -> BuildStatusContext: + """ + Constructs a BuildStatusContext + + """ + return BuildStatusContext(self._version, service_sid=self._solution['service_sid'], sid=self._solution['sid']) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return '<Twilio.Serverless.V1.BuildStatusList>' + diff --git a/twilio/rest/serverless/v1/service/environment/__init__.py b/twilio/rest/serverless/v1/service/environment/__init__.py new file mode 100644 index 0000000000..cdad0504a7 --- /dev/null +++ b/twilio/rest/serverless/v1/service/environment/__init__.py @@ -0,0 +1,623 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.serverless.v1.service.environment.deployment import DeploymentList +from twilio.rest.serverless.v1.service.environment.log import LogList +from twilio.rest.serverless.v1.service.environment.variable import VariableList + + +class EnvironmentInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Environment resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Environment resource. + :ivar service_sid: The SID of the Service that the Environment resource is associated with. + :ivar build_sid: The SID of the build deployed in the environment. + :ivar unique_name: A user-defined string that uniquely identifies the Environment resource. + :ivar domain_suffix: A URL-friendly name that represents the environment and forms part of the domain name. + :ivar domain_name: The domain name for all Functions and Assets deployed in the Environment, using the Service unique name, a randomly-generated Service suffix, and an optional Environment domain suffix. + :ivar date_created: The date and time in GMT when the Environment resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Environment resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Environment resource. + :ivar links: The URLs of the Environment resource's nested resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.build_sid: Optional[str] = payload.get("build_sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.domain_suffix: Optional[str] = payload.get("domain_suffix") + self.domain_name: Optional[str] = payload.get("domain_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[EnvironmentContext] = None + + @property + def _proxy(self) -> "EnvironmentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EnvironmentContext for this EnvironmentInstance + """ + if self._context is None: + self._context = EnvironmentContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the EnvironmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EnvironmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "EnvironmentInstance": + """ + Fetch the EnvironmentInstance + + + :returns: The fetched EnvironmentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EnvironmentInstance": + """ + Asynchronous coroutine to fetch the EnvironmentInstance + + + :returns: The fetched EnvironmentInstance + """ + return await self._proxy.fetch_async() + + @property + def deployments(self) -> DeploymentList: + """ + Access the deployments + """ + return self._proxy.deployments + + @property + def logs(self) -> LogList: + """ + Access the logs + """ + return self._proxy.logs + + @property + def variables(self) -> VariableList: + """ + Access the variables + """ + return self._proxy.variables + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Serverless.V1.EnvironmentInstance {}>".format(context) + + +class EnvironmentContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the EnvironmentContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Environment resource from. + :param sid: The SID of the Environment resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Environments/{sid}".format( + **self._solution + ) + + self._deployments: Optional[DeploymentList] = None + self._logs: Optional[LogList] = None + self._variables: Optional[VariableList] = None + + def delete(self) -> bool: + """ + Deletes the EnvironmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EnvironmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> EnvironmentInstance: + """ + Fetch the EnvironmentInstance + + + :returns: The fetched EnvironmentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EnvironmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EnvironmentInstance: + """ + Asynchronous coroutine to fetch the EnvironmentInstance + + + :returns: The fetched EnvironmentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EnvironmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def deployments(self) -> DeploymentList: + """ + Access the deployments + """ + if self._deployments is None: + self._deployments = DeploymentList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._deployments + + @property + def logs(self) -> LogList: + """ + Access the logs + """ + if self._logs is None: + self._logs = LogList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._logs + + @property + def variables(self) -> VariableList: + """ + Access the variables + """ + if self._variables is None: + self._variables = VariableList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._variables + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Serverless.V1.EnvironmentContext {}>".format(context) + + +class EnvironmentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EnvironmentInstance: + """ + Build an instance of EnvironmentInstance + + :param payload: Payload response from the API + """ + return EnvironmentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1.EnvironmentPage>" + + +class EnvironmentList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the EnvironmentList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Environment resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Environments".format(**self._solution) + + def create( + self, unique_name: str, domain_suffix: Union[str, object] = values.unset + ) -> EnvironmentInstance: + """ + Create the EnvironmentInstance + + :param unique_name: A user-defined string that uniquely identifies the Environment resource. It can be a maximum of 100 characters. + :param domain_suffix: A URL-friendly name that represents the environment and forms part of the domain name. It can be a maximum of 16 characters. + + :returns: The created EnvironmentInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "DomainSuffix": domain_suffix, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EnvironmentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, unique_name: str, domain_suffix: Union[str, object] = values.unset + ) -> EnvironmentInstance: + """ + Asynchronously create the EnvironmentInstance + + :param unique_name: A user-defined string that uniquely identifies the Environment resource. It can be a maximum of 100 characters. + :param domain_suffix: A URL-friendly name that represents the environment and forms part of the domain name. It can be a maximum of 16 characters. + + :returns: The created EnvironmentInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "DomainSuffix": domain_suffix, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EnvironmentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EnvironmentInstance]: + """ + Streams EnvironmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EnvironmentInstance]: + """ + Asynchronously streams EnvironmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EnvironmentInstance]: + """ + Lists EnvironmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EnvironmentInstance]: + """ + Asynchronously lists EnvironmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EnvironmentPage: + """ + Retrieve a single page of EnvironmentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EnvironmentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EnvironmentPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EnvironmentPage: + """ + Asynchronously retrieve a single page of EnvironmentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EnvironmentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EnvironmentPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> EnvironmentPage: + """ + Retrieve a specific page of EnvironmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EnvironmentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EnvironmentPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> EnvironmentPage: + """ + Asynchronously retrieve a specific page of EnvironmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EnvironmentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EnvironmentPage(self._version, response, self._solution) + + def get(self, sid: str) -> EnvironmentContext: + """ + Constructs a EnvironmentContext + + :param sid: The SID of the Environment resource to fetch. + """ + return EnvironmentContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> EnvironmentContext: + """ + Constructs a EnvironmentContext + + :param sid: The SID of the Environment resource to fetch. + """ + return EnvironmentContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1.EnvironmentList>" diff --git a/twilio/rest/serverless/v1/service/environment/deployment.py b/twilio/rest/serverless/v1/service/environment/deployment.py new file mode 100644 index 0000000000..d28a4b8db1 --- /dev/null +++ b/twilio/rest/serverless/v1/service/environment/deployment.py @@ -0,0 +1,540 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DeploymentInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Deployment resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Deployment resource. + :ivar service_sid: The SID of the Service that the Deployment resource is associated with. + :ivar environment_sid: The SID of the Environment for the Deployment. + :ivar build_sid: The SID of the Build for the deployment. + :ivar date_created: The date and time in GMT when the Deployment resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Deployment resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Deployment resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + environment_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.environment_sid: Optional[str] = payload.get("environment_sid") + self.build_sid: Optional[str] = payload.get("build_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + "sid": sid or self.sid, + } + self._context: Optional[DeploymentContext] = None + + @property + def _proxy(self) -> "DeploymentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DeploymentContext for this DeploymentInstance + """ + if self._context is None: + self._context = DeploymentContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "DeploymentInstance": + """ + Fetch the DeploymentInstance + + + :returns: The fetched DeploymentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DeploymentInstance": + """ + Asynchronous coroutine to fetch the DeploymentInstance + + + :returns: The fetched DeploymentInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Serverless.V1.DeploymentInstance {}>".format(context) + + +class DeploymentContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, environment_sid: str, sid: str + ): + """ + Initialize the DeploymentContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Deployment resource from. + :param environment_sid: The SID of the Environment used by the Deployment to fetch. + :param sid: The SID that identifies the Deployment resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Environments/{environment_sid}/Deployments/{sid}".format( + **self._solution + ) + + def fetch(self) -> DeploymentInstance: + """ + Fetch the DeploymentInstance + + + :returns: The fetched DeploymentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> DeploymentInstance: + """ + Asynchronous coroutine to fetch the DeploymentInstance + + + :returns: The fetched DeploymentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Serverless.V1.DeploymentContext {}>".format(context) + + +class DeploymentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DeploymentInstance: + """ + Build an instance of DeploymentInstance + + :param payload: Payload response from the API + """ + return DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1.DeploymentPage>" + + +class DeploymentList(ListResource): + + def __init__(self, version: Version, service_sid: str, environment_sid: str): + """ + Initialize the DeploymentList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Deployment resources from. + :param environment_sid: The SID of the Environment used by the Deployment resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + } + self._uri = ( + "/Services/{service_sid}/Environments/{environment_sid}/Deployments".format( + **self._solution + ) + ) + + def create( + self, + build_sid: Union[str, object] = values.unset, + is_plugin: Union[bool, object] = values.unset, + ) -> DeploymentInstance: + """ + Create the DeploymentInstance + + :param build_sid: The SID of the Build for the Deployment. + :param is_plugin: Whether the Deployment is a plugin. + + :returns: The created DeploymentInstance + """ + + data = values.of( + { + "BuildSid": build_sid, + "IsPlugin": serialize.boolean_to_string(is_plugin), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + + async def create_async( + self, + build_sid: Union[str, object] = values.unset, + is_plugin: Union[bool, object] = values.unset, + ) -> DeploymentInstance: + """ + Asynchronously create the DeploymentInstance + + :param build_sid: The SID of the Build for the Deployment. + :param is_plugin: Whether the Deployment is a plugin. + + :returns: The created DeploymentInstance + """ + + data = values.of( + { + "BuildSid": build_sid, + "IsPlugin": serialize.boolean_to_string(is_plugin), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DeploymentInstance]: + """ + Streams DeploymentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DeploymentInstance]: + """ + Asynchronously streams DeploymentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeploymentInstance]: + """ + Lists DeploymentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DeploymentInstance]: + """ + Asynchronously lists DeploymentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DeploymentPage: + """ + Retrieve a single page of DeploymentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DeploymentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DeploymentPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DeploymentPage: + """ + Asynchronously retrieve a single page of DeploymentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DeploymentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DeploymentPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DeploymentPage: + """ + Retrieve a specific page of DeploymentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DeploymentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DeploymentPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DeploymentPage: + """ + Asynchronously retrieve a specific page of DeploymentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DeploymentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DeploymentPage(self._version, response, self._solution) + + def get(self, sid: str) -> DeploymentContext: + """ + Constructs a DeploymentContext + + :param sid: The SID that identifies the Deployment resource to fetch. + """ + return DeploymentContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> DeploymentContext: + """ + Constructs a DeploymentContext + + :param sid: The SID that identifies the Deployment resource to fetch. + """ + return DeploymentContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1.DeploymentList>" diff --git a/twilio/rest/serverless/v1/service/environment/log.py b/twilio/rest/serverless/v1/service/environment/log.py new file mode 100644 index 0000000000..a3c9a6c2da --- /dev/null +++ b/twilio/rest/serverless/v1/service/environment/log.py @@ -0,0 +1,538 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class LogInstance(InstanceResource): + + class Level(object): + INFO = "info" + WARN = "warn" + ERROR = "error" + + """ + :ivar sid: The unique string that we created to identify the Log resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Log resource. + :ivar service_sid: The SID of the Service that the Log resource is associated with. + :ivar environment_sid: The SID of the environment in which the log occurred. + :ivar build_sid: The SID of the build that corresponds to the log. + :ivar deployment_sid: The SID of the deployment that corresponds to the log. + :ivar function_sid: The SID of the function whose invocation produced the log. + :ivar request_sid: The SID of the request associated with the log. + :ivar level: + :ivar message: The log message. + :ivar date_created: The date and time in GMT when the Log resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Log resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + environment_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.environment_sid: Optional[str] = payload.get("environment_sid") + self.build_sid: Optional[str] = payload.get("build_sid") + self.deployment_sid: Optional[str] = payload.get("deployment_sid") + self.function_sid: Optional[str] = payload.get("function_sid") + self.request_sid: Optional[str] = payload.get("request_sid") + self.level: Optional["LogInstance.Level"] = payload.get("level") + self.message: Optional[str] = payload.get("message") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + "sid": sid or self.sid, + } + self._context: Optional[LogContext] = None + + @property + def _proxy(self) -> "LogContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: LogContext for this LogInstance + """ + if self._context is None: + self._context = LogContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "LogInstance": + """ + Fetch the LogInstance + + + :returns: The fetched LogInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "LogInstance": + """ + Asynchronous coroutine to fetch the LogInstance + + + :returns: The fetched LogInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Serverless.V1.LogInstance {}>".format(context) + + +class LogContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, environment_sid: str, sid: str + ): + """ + Initialize the LogContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Log resource from. + :param environment_sid: The SID of the environment with the Log resource to fetch. + :param sid: The SID of the Log resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Environments/{environment_sid}/Logs/{sid}".format( + **self._solution + ) + ) + + def fetch(self) -> LogInstance: + """ + Fetch the LogInstance + + + :returns: The fetched LogInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return LogInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> LogInstance: + """ + Asynchronous coroutine to fetch the LogInstance + + + :returns: The fetched LogInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return LogInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Serverless.V1.LogContext {}>".format(context) + + +class LogPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> LogInstance: + """ + Build an instance of LogInstance + + :param payload: Payload response from the API + """ + return LogInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1.LogPage>" + + +class LogList(ListResource): + + def __init__(self, version: Version, service_sid: str, environment_sid: str): + """ + Initialize the LogList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Log resource from. + :param environment_sid: The SID of the environment with the Log resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + } + self._uri = ( + "/Services/{service_sid}/Environments/{environment_sid}/Logs".format( + **self._solution + ) + ) + + def stream( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[LogInstance]: + """ + Streams LogInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str function_sid: The SID of the function whose invocation produced the Log resources to read. + :param datetime start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param datetime end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[LogInstance]: + """ + Asynchronously streams LogInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str function_sid: The SID of the function whose invocation produced the Log resources to read. + :param datetime start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param datetime end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LogInstance]: + """ + Lists LogInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str function_sid: The SID of the function whose invocation produced the Log resources to read. + :param datetime start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param datetime end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[LogInstance]: + """ + Asynchronously lists LogInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str function_sid: The SID of the function whose invocation produced the Log resources to read. + :param datetime start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param datetime end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + function_sid=function_sid, + start_date=start_date, + end_date=end_date, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LogPage: + """ + Retrieve a single page of LogInstance records from the API. + Request is executed immediately + + :param function_sid: The SID of the function whose invocation produced the Log resources to read. + :param start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LogInstance + """ + data = values.of( + { + "FunctionSid": function_sid, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LogPage(self._version, response, self._solution) + + async def page_async( + self, + function_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> LogPage: + """ + Asynchronously retrieve a single page of LogInstance records from the API. + Request is executed immediately + + :param function_sid: The SID of the function whose invocation produced the Log resources to read. + :param start_date: The date/time (in GMT, ISO 8601) after which the Log resources must have been created. Defaults to 1 day prior to current date/time. + :param end_date: The date/time (in GMT, ISO 8601) before which the Log resources must have been created. Defaults to current date/time. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of LogInstance + """ + data = values.of( + { + "FunctionSid": function_sid, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return LogPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> LogPage: + """ + Retrieve a specific page of LogInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of LogInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return LogPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> LogPage: + """ + Asynchronously retrieve a specific page of LogInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of LogInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return LogPage(self._version, response, self._solution) + + def get(self, sid: str) -> LogContext: + """ + Constructs a LogContext + + :param sid: The SID of the Log resource to fetch. + """ + return LogContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> LogContext: + """ + Constructs a LogContext + + :param sid: The SID of the Log resource to fetch. + """ + return LogContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1.LogList>" diff --git a/twilio/rest/serverless/v1/service/environment/variable.py b/twilio/rest/serverless/v1/service/environment/variable.py new file mode 100644 index 0000000000..fbc6b48ac8 --- /dev/null +++ b/twilio/rest/serverless/v1/service/environment/variable.py @@ -0,0 +1,690 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class VariableInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Variable resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Variable resource. + :ivar service_sid: The SID of the Service that the Variable resource is associated with. + :ivar environment_sid: The SID of the Environment in which the Variable exists. + :ivar key: A string by which the Variable resource can be referenced. + :ivar value: A string that contains the actual value of the Variable. + :ivar date_created: The date and time in GMT when the Variable resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Variable resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Variable resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + environment_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.environment_sid: Optional[str] = payload.get("environment_sid") + self.key: Optional[str] = payload.get("key") + self.value: Optional[str] = payload.get("value") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + "sid": sid or self.sid, + } + self._context: Optional[VariableContext] = None + + @property + def _proxy(self) -> "VariableContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: VariableContext for this VariableInstance + """ + if self._context is None: + self._context = VariableContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the VariableInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the VariableInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "VariableInstance": + """ + Fetch the VariableInstance + + + :returns: The fetched VariableInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "VariableInstance": + """ + Asynchronous coroutine to fetch the VariableInstance + + + :returns: The fetched VariableInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> "VariableInstance": + """ + Update the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: The updated VariableInstance + """ + return self._proxy.update( + key=key, + value=value, + ) + + async def update_async( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> "VariableInstance": + """ + Asynchronous coroutine to update the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: The updated VariableInstance + """ + return await self._proxy.update_async( + key=key, + value=value, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Serverless.V1.VariableInstance {}>".format(context) + + +class VariableContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, environment_sid: str, sid: str + ): + """ + Initialize the VariableContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to update the Variable resource under. + :param environment_sid: The SID of the Environment with the Variable resource to update. + :param sid: The SID of the Variable resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Environments/{environment_sid}/Variables/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the VariableInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the VariableInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> VariableInstance: + """ + Fetch the VariableInstance + + + :returns: The fetched VariableInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> VariableInstance: + """ + Asynchronous coroutine to fetch the VariableInstance + + + :returns: The fetched VariableInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> VariableInstance: + """ + Update the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: The updated VariableInstance + """ + + data = values.of( + { + "Key": key, + "Value": value, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + key: Union[str, object] = values.unset, + value: Union[str, object] = values.unset, + ) -> VariableInstance: + """ + Asynchronous coroutine to update the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: The updated VariableInstance + """ + + data = values.of( + { + "Key": key, + "Value": value, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Serverless.V1.VariableContext {}>".format(context) + + +class VariablePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> VariableInstance: + """ + Build an instance of VariableInstance + + :param payload: Payload response from the API + """ + return VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1.VariablePage>" + + +class VariableList(ListResource): + + def __init__(self, version: Version, service_sid: str, environment_sid: str): + """ + Initialize the VariableList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Variable resources from. + :param environment_sid: The SID of the Environment with the Variable resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "environment_sid": environment_sid, + } + self._uri = ( + "/Services/{service_sid}/Environments/{environment_sid}/Variables".format( + **self._solution + ) + ) + + def create(self, key: str, value: str) -> VariableInstance: + """ + Create the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: The created VariableInstance + """ + + data = values.of( + { + "Key": key, + "Value": value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + + async def create_async(self, key: str, value: str) -> VariableInstance: + """ + Asynchronously create the VariableInstance + + :param key: A string by which the Variable resource can be referenced. It can be a maximum of 128 characters. + :param value: A string that contains the actual value of the Variable. It can be a maximum of 450 bytes in size. + + :returns: The created VariableInstance + """ + + data = values.of( + { + "Key": key, + "Value": value, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[VariableInstance]: + """ + Streams VariableInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[VariableInstance]: + """ + Asynchronously streams VariableInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[VariableInstance]: + """ + Lists VariableInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[VariableInstance]: + """ + Asynchronously lists VariableInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> VariablePage: + """ + Retrieve a single page of VariableInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of VariableInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return VariablePage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> VariablePage: + """ + Asynchronously retrieve a single page of VariableInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of VariableInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return VariablePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> VariablePage: + """ + Retrieve a specific page of VariableInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of VariableInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return VariablePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> VariablePage: + """ + Asynchronously retrieve a specific page of VariableInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of VariableInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return VariablePage(self._version, response, self._solution) + + def get(self, sid: str) -> VariableContext: + """ + Constructs a VariableContext + + :param sid: The SID of the Variable resource to update. + """ + return VariableContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> VariableContext: + """ + Constructs a VariableContext + + :param sid: The SID of the Variable resource to update. + """ + return VariableContext( + self._version, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1.VariableList>" diff --git a/twilio/rest/serverless/v1/service/function/__init__.py b/twilio/rest/serverless/v1/service/function/__init__.py new file mode 100644 index 0000000000..7697587e60 --- /dev/null +++ b/twilio/rest/serverless/v1/service/function/__init__.py @@ -0,0 +1,651 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.serverless.v1.service.function.function_version import ( + FunctionVersionList, +) + + +class FunctionInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Function resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Function resource. + :ivar service_sid: The SID of the Service that the Function resource is associated with. + :ivar friendly_name: The string that you assigned to describe the Function resource. It can be a maximum of 255 characters. + :ivar date_created: The date and time in GMT when the Function resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Function resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Function resource. + :ivar links: The URLs of nested resources of the Function resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[FunctionContext] = None + + @property + def _proxy(self) -> "FunctionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FunctionContext for this FunctionInstance + """ + if self._context is None: + self._context = FunctionContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the FunctionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FunctionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "FunctionInstance": + """ + Fetch the FunctionInstance + + + :returns: The fetched FunctionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FunctionInstance": + """ + Asynchronous coroutine to fetch the FunctionInstance + + + :returns: The fetched FunctionInstance + """ + return await self._proxy.fetch_async() + + def update(self, friendly_name: str) -> "FunctionInstance": + """ + Update the FunctionInstance + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: The updated FunctionInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async(self, friendly_name: str) -> "FunctionInstance": + """ + Asynchronous coroutine to update the FunctionInstance + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: The updated FunctionInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + @property + def function_versions(self) -> FunctionVersionList: + """ + Access the function_versions + """ + return self._proxy.function_versions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Serverless.V1.FunctionInstance {}>".format(context) + + +class FunctionContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the FunctionContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to update the Function resource from. + :param sid: The SID of the Function resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Functions/{sid}".format(**self._solution) + + self._function_versions: Optional[FunctionVersionList] = None + + def delete(self) -> bool: + """ + Deletes the FunctionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FunctionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> FunctionInstance: + """ + Fetch the FunctionInstance + + + :returns: The fetched FunctionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FunctionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> FunctionInstance: + """ + Asynchronous coroutine to fetch the FunctionInstance + + + :returns: The fetched FunctionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FunctionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update(self, friendly_name: str) -> FunctionInstance: + """ + Update the FunctionInstance + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: The updated FunctionInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FunctionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self, friendly_name: str) -> FunctionInstance: + """ + Asynchronous coroutine to update the FunctionInstance + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: The updated FunctionInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FunctionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def function_versions(self) -> FunctionVersionList: + """ + Access the function_versions + """ + if self._function_versions is None: + self._function_versions = FunctionVersionList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._function_versions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Serverless.V1.FunctionContext {}>".format(context) + + +class FunctionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FunctionInstance: + """ + Build an instance of FunctionInstance + + :param payload: Payload response from the API + """ + return FunctionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1.FunctionPage>" + + +class FunctionList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the FunctionList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Function resources from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Functions".format(**self._solution) + + def create(self, friendly_name: str) -> FunctionInstance: + """ + Create the FunctionInstance + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: The created FunctionInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FunctionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async(self, friendly_name: str) -> FunctionInstance: + """ + Asynchronously create the FunctionInstance + + :param friendly_name: A descriptive string that you create to describe the Function resource. It can be a maximum of 255 characters. + + :returns: The created FunctionInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FunctionInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FunctionInstance]: + """ + Streams FunctionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FunctionInstance]: + """ + Asynchronously streams FunctionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FunctionInstance]: + """ + Lists FunctionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FunctionInstance]: + """ + Asynchronously lists FunctionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FunctionPage: + """ + Retrieve a single page of FunctionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FunctionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FunctionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FunctionPage: + """ + Asynchronously retrieve a single page of FunctionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FunctionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FunctionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> FunctionPage: + """ + Retrieve a specific page of FunctionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FunctionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FunctionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> FunctionPage: + """ + Asynchronously retrieve a specific page of FunctionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FunctionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FunctionPage(self._version, response, self._solution) + + def get(self, sid: str) -> FunctionContext: + """ + Constructs a FunctionContext + + :param sid: The SID of the Function resource to update. + """ + return FunctionContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> FunctionContext: + """ + Constructs a FunctionContext + + :param sid: The SID of the Function resource to update. + """ + return FunctionContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1.FunctionList>" diff --git a/twilio/rest/serverless/v1/service/function/function_version/__init__.py b/twilio/rest/serverless/v1/service/function/function_version/__init__.py new file mode 100644 index 0000000000..88b666208c --- /dev/null +++ b/twilio/rest/serverless/v1/service/function/function_version/__init__.py @@ -0,0 +1,498 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.serverless.v1.service.function.function_version.function_version_content import ( + FunctionVersionContentList, +) + + +class FunctionVersionInstance(InstanceResource): + + class Visibility(object): + PUBLIC = "public" + PRIVATE = "private" + PROTECTED = "protected" + + """ + :ivar sid: The unique string that we created to identify the Function Version resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Function Version resource. + :ivar service_sid: The SID of the Service that the Function Version resource is associated with. + :ivar function_sid: The SID of the Function resource that is the parent of the Function Version resource. + :ivar path: The URL-friendly string by which the Function Version resource can be referenced. It can be a maximum of 255 characters. All paths begin with a forward slash ('/'). If a Function Version creation request is submitted with a path not containing a leading slash, the path will automatically be prepended with one. + :ivar visibility: + :ivar date_created: The date and time in GMT when the Function Version resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Function Version resource. + :ivar links: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + function_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.function_sid: Optional[str] = payload.get("function_sid") + self.path: Optional[str] = payload.get("path") + self.visibility: Optional["FunctionVersionInstance.Visibility"] = payload.get( + "visibility" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + "sid": sid or self.sid, + } + self._context: Optional[FunctionVersionContext] = None + + @property + def _proxy(self) -> "FunctionVersionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FunctionVersionContext for this FunctionVersionInstance + """ + if self._context is None: + self._context = FunctionVersionContext( + self._version, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "FunctionVersionInstance": + """ + Fetch the FunctionVersionInstance + + + :returns: The fetched FunctionVersionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FunctionVersionInstance": + """ + Asynchronous coroutine to fetch the FunctionVersionInstance + + + :returns: The fetched FunctionVersionInstance + """ + return await self._proxy.fetch_async() + + @property + def function_version_content(self) -> FunctionVersionContentList: + """ + Access the function_version_content + """ + return self._proxy.function_version_content + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Serverless.V1.FunctionVersionInstance {}>".format(context) + + +class FunctionVersionContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, function_sid: str, sid: str): + """ + Initialize the FunctionVersionContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Function Version resource from. + :param function_sid: The SID of the function that is the parent of the Function Version resource to fetch. + :param sid: The SID of the Function Version resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Functions/{function_sid}/Versions/{sid}".format( + **self._solution + ) + ) + + self._function_version_content: Optional[FunctionVersionContentList] = None + + def fetch(self) -> FunctionVersionInstance: + """ + Fetch the FunctionVersionInstance + + + :returns: The fetched FunctionVersionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FunctionVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> FunctionVersionInstance: + """ + Asynchronous coroutine to fetch the FunctionVersionInstance + + + :returns: The fetched FunctionVersionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FunctionVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + + @property + def function_version_content(self) -> FunctionVersionContentList: + """ + Access the function_version_content + """ + if self._function_version_content is None: + self._function_version_content = FunctionVersionContentList( + self._version, + self._solution["service_sid"], + self._solution["function_sid"], + self._solution["sid"], + ) + return self._function_version_content + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Serverless.V1.FunctionVersionContext {}>".format(context) + + +class FunctionVersionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FunctionVersionInstance: + """ + Build an instance of FunctionVersionInstance + + :param payload: Payload response from the API + """ + return FunctionVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1.FunctionVersionPage>" + + +class FunctionVersionList(ListResource): + + def __init__(self, version: Version, service_sid: str, function_sid: str): + """ + Initialize the FunctionVersionList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to read the Function Version resources from. + :param function_sid: The SID of the function that is the parent of the Function Version resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + } + self._uri = "/Services/{service_sid}/Functions/{function_sid}/Versions".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FunctionVersionInstance]: + """ + Streams FunctionVersionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FunctionVersionInstance]: + """ + Asynchronously streams FunctionVersionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FunctionVersionInstance]: + """ + Lists FunctionVersionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FunctionVersionInstance]: + """ + Asynchronously lists FunctionVersionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FunctionVersionPage: + """ + Retrieve a single page of FunctionVersionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FunctionVersionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FunctionVersionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FunctionVersionPage: + """ + Asynchronously retrieve a single page of FunctionVersionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FunctionVersionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FunctionVersionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> FunctionVersionPage: + """ + Retrieve a specific page of FunctionVersionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FunctionVersionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FunctionVersionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> FunctionVersionPage: + """ + Asynchronously retrieve a specific page of FunctionVersionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FunctionVersionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FunctionVersionPage(self._version, response, self._solution) + + def get(self, sid: str) -> FunctionVersionContext: + """ + Constructs a FunctionVersionContext + + :param sid: The SID of the Function Version resource to fetch. + """ + return FunctionVersionContext( + self._version, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> FunctionVersionContext: + """ + Constructs a FunctionVersionContext + + :param sid: The SID of the Function Version resource to fetch. + """ + return FunctionVersionContext( + self._version, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1.FunctionVersionList>" diff --git a/twilio/rest/serverless/v1/service/function/function_version/function_version_content.py b/twilio/rest/serverless/v1/service/function/function_version/function_version_content.py new file mode 100644 index 0000000000..f16833da2a --- /dev/null +++ b/twilio/rest/serverless/v1/service/function/function_version/function_version_content.py @@ -0,0 +1,234 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Serverless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class FunctionVersionContentInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Function Version resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Function Version resource. + :ivar service_sid: The SID of the Service that the Function Version resource is associated with. + :ivar function_sid: The SID of the Function that is the parent of the Function Version. + :ivar content: The content of the Function Version resource. + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + function_sid: str, + sid: str, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.function_sid: Optional[str] = payload.get("function_sid") + self.content: Optional[str] = payload.get("content") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + "sid": sid, + } + self._context: Optional[FunctionVersionContentContext] = None + + @property + def _proxy(self) -> "FunctionVersionContentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FunctionVersionContentContext for this FunctionVersionContentInstance + """ + if self._context is None: + self._context = FunctionVersionContentContext( + self._version, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "FunctionVersionContentInstance": + """ + Fetch the FunctionVersionContentInstance + + + :returns: The fetched FunctionVersionContentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FunctionVersionContentInstance": + """ + Asynchronous coroutine to fetch the FunctionVersionContentInstance + + + :returns: The fetched FunctionVersionContentInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Serverless.V1.FunctionVersionContentInstance {}>".format( + context + ) + + +class FunctionVersionContentContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, function_sid: str, sid: str): + """ + Initialize the FunctionVersionContentContext + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Function Version content from. + :param function_sid: The SID of the Function that is the parent of the Function Version content to fetch. + :param sid: The SID of the Function Version content to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Functions/{function_sid}/Versions/{sid}/Content".format( + **self._solution + ) + + def fetch(self) -> FunctionVersionContentInstance: + """ + Fetch the FunctionVersionContentInstance + + + :returns: The fetched FunctionVersionContentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FunctionVersionContentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> FunctionVersionContentInstance: + """ + Asynchronous coroutine to fetch the FunctionVersionContentInstance + + + :returns: The fetched FunctionVersionContentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FunctionVersionContentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Serverless.V1.FunctionVersionContentContext {}>".format(context) + + +class FunctionVersionContentList(ListResource): + + def __init__(self, version: Version, service_sid: str, function_sid: str, sid: str): + """ + Initialize the FunctionVersionContentList + + :param version: Version that contains the resource + :param service_sid: The SID of the Service to fetch the Function Version content from. + :param function_sid: The SID of the Function that is the parent of the Function Version content to fetch. + :param sid: The SID of the Function Version content to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "function_sid": function_sid, + "sid": sid, + } + + def get(self) -> FunctionVersionContentContext: + """ + Constructs a FunctionVersionContentContext + + """ + return FunctionVersionContentContext( + self._version, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + + def __call__(self) -> FunctionVersionContentContext: + """ + Constructs a FunctionVersionContentContext + + """ + return FunctionVersionContentContext( + self._version, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Serverless.V1.FunctionVersionContentList>" diff --git a/twilio/rest/studio/StudioBase.py b/twilio/rest/studio/StudioBase.py new file mode 100644 index 0000000000..3b218775c8 --- /dev/null +++ b/twilio/rest/studio/StudioBase.py @@ -0,0 +1,55 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.studio.v1 import V1 +from twilio.rest.studio.v2 import V2 + + +class StudioBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Studio Domain + + :returns: Domain for Studio + """ + super().__init__(twilio, "https://studio.twilio.com") + self._v1: Optional[V1] = None + self._v2: Optional[V2] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Studio + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Studio + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Studio>" diff --git a/twilio/rest/studio/__init__.py b/twilio/rest/studio/__init__.py new file mode 100644 index 0000000000..986e694221 --- /dev/null +++ b/twilio/rest/studio/__init__.py @@ -0,0 +1,25 @@ +from warnings import warn + +from twilio.rest.studio.StudioBase import StudioBase +from twilio.rest.studio.v2.flow import FlowList +from twilio.rest.studio.v2.flow_validate import FlowValidateList + + +class Studio(StudioBase): + @property + def flows(self) -> FlowList: + warn( + "flows is deprecated. Use v2.flows instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.flows + + @property + def flow_validate(self) -> FlowValidateList: + warn( + "flow_validate is deprecated. Use v2.flow_validate instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.flow_validate diff --git a/twilio/rest/studio/v1/__init__.py b/twilio/rest/studio/v1/__init__.py new file mode 100644 index 0000000000..8ab7d71b6c --- /dev/null +++ b/twilio/rest/studio/v1/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.studio.v1.flow import FlowList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Studio + + :param domain: The Twilio.studio domain + """ + super().__init__(domain, "v1") + self._flows: Optional[FlowList] = None + + @property + def flows(self) -> FlowList: + if self._flows is None: + self._flows = FlowList(self) + return self._flows + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V1>" diff --git a/twilio/rest/studio/v1/flow/__init__.py b/twilio/rest/studio/v1/flow/__init__.py new file mode 100644 index 0000000000..533c1a45f5 --- /dev/null +++ b/twilio/rest/studio/v1/flow/__init__.py @@ -0,0 +1,513 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.studio.v1.flow.engagement import EngagementList +from twilio.rest.studio.v1.flow.execution import ExecutionList + + +class FlowInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PUBLISHED = "published" + + """ + :ivar sid: The unique string that we created to identify the Flow resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flow resource. + :ivar friendly_name: The string that you assigned to describe the Flow. + :ivar status: + :ivar version: The latest version number of the Flow's definition. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of the Flow's nested resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["FlowInstance.Status"] = payload.get("status") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[FlowContext] = None + + @property + def _proxy(self) -> "FlowContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FlowContext for this FlowInstance + """ + if self._context is None: + self._context = FlowContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the FlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "FlowInstance": + """ + Fetch the FlowInstance + + + :returns: The fetched FlowInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FlowInstance": + """ + Asynchronous coroutine to fetch the FlowInstance + + + :returns: The fetched FlowInstance + """ + return await self._proxy.fetch_async() + + @property + def engagements(self) -> EngagementList: + """ + Access the engagements + """ + return self._proxy.engagements + + @property + def executions(self) -> ExecutionList: + """ + Access the executions + """ + return self._proxy.executions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V1.FlowInstance {}>".format(context) + + +class FlowContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the FlowContext + + :param version: Version that contains the resource + :param sid: The SID of the Flow resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Flows/{sid}".format(**self._solution) + + self._engagements: Optional[EngagementList] = None + self._executions: Optional[ExecutionList] = None + + def delete(self) -> bool: + """ + Deletes the FlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> FlowInstance: + """ + Fetch the FlowInstance + + + :returns: The fetched FlowInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> FlowInstance: + """ + Asynchronous coroutine to fetch the FlowInstance + + + :returns: The fetched FlowInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + @property + def engagements(self) -> EngagementList: + """ + Access the engagements + """ + if self._engagements is None: + self._engagements = EngagementList( + self._version, + self._solution["sid"], + ) + return self._engagements + + @property + def executions(self) -> ExecutionList: + """ + Access the executions + """ + if self._executions is None: + self._executions = ExecutionList( + self._version, + self._solution["sid"], + ) + return self._executions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V1.FlowContext {}>".format(context) + + +class FlowPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FlowInstance: + """ + Build an instance of FlowInstance + + :param payload: Payload response from the API + """ + return FlowInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V1.FlowPage>" + + +class FlowList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the FlowList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Flows" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FlowInstance]: + """ + Streams FlowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FlowInstance]: + """ + Asynchronously streams FlowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlowInstance]: + """ + Lists FlowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlowInstance]: + """ + Asynchronously lists FlowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FlowPage: + """ + Retrieve a single page of FlowInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FlowInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlowPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FlowPage: + """ + Asynchronously retrieve a single page of FlowInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FlowInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlowPage(self._version, response) + + def get_page(self, target_url: str) -> FlowPage: + """ + Retrieve a specific page of FlowInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FlowInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FlowPage(self._version, response) + + async def get_page_async(self, target_url: str) -> FlowPage: + """ + Asynchronously retrieve a specific page of FlowInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FlowInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FlowPage(self._version, response) + + def get(self, sid: str) -> FlowContext: + """ + Constructs a FlowContext + + :param sid: The SID of the Flow resource to fetch. + """ + return FlowContext(self._version, sid=sid) + + def __call__(self, sid: str) -> FlowContext: + """ + Constructs a FlowContext + + :param sid: The SID of the Flow resource to fetch. + """ + return FlowContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V1.FlowList>" diff --git a/twilio/rest/studio/v1/flow/engagement/__init__.py b/twilio/rest/studio/v1/flow/engagement/__init__.py new file mode 100644 index 0000000000..759d92506c --- /dev/null +++ b/twilio/rest/studio/v1/flow/engagement/__init__.py @@ -0,0 +1,612 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.studio.v1.flow.engagement.engagement_context import ( + EngagementContextList, +) +from twilio.rest.studio.v1.flow.engagement.step import StepList + + +class EngagementInstance(InstanceResource): + + class Status(object): + ACTIVE = "active" + ENDED = "ended" + + """ + :ivar sid: The unique string that we created to identify the Engagement resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Engagement resource. + :ivar flow_sid: The SID of the Flow. + :ivar contact_sid: The SID of the Contact. + :ivar contact_channel_address: The phone number, SIP address or Client identifier that triggered this Engagement. Phone numbers are in E.164 format (+16175551212). SIP addresses are formatted as `name@company.com`. Client identifiers are formatted `client:name`. + :ivar context: The current state of the execution flow. As your flow executes, we save the state in a flow context. Your widgets can access the data in the flow context as variables, either in configuration fields or in text areas as variable substitution. + :ivar status: + :ivar date_created: The date and time in GMT when the Engagement was created in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the Engagement was updated in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of the Engagement's nested resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.contact_sid: Optional[str] = payload.get("contact_sid") + self.contact_channel_address: Optional[str] = payload.get( + "contact_channel_address" + ) + self.context: Optional[Dict[str, object]] = payload.get("context") + self.status: Optional["EngagementInstance.Status"] = payload.get("status") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "flow_sid": flow_sid, + "sid": sid or self.sid, + } + self._context: Optional[EngagementContext] = None + + @property + def _proxy(self) -> "EngagementContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EngagementContext for this EngagementInstance + """ + if self._context is None: + self._context = EngagementContext( + self._version, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the EngagementInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EngagementInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "EngagementInstance": + """ + Fetch the EngagementInstance + + + :returns: The fetched EngagementInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EngagementInstance": + """ + Asynchronous coroutine to fetch the EngagementInstance + + + :returns: The fetched EngagementInstance + """ + return await self._proxy.fetch_async() + + @property + def engagement_context(self) -> EngagementContextList: + """ + Access the engagement_context + """ + return self._proxy.engagement_context + + @property + def steps(self) -> StepList: + """ + Access the steps + """ + return self._proxy.steps + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V1.EngagementInstance {}>".format(context) + + +class EngagementContext(InstanceContext): + + def __init__(self, version: Version, flow_sid: str, sid: str): + """ + Initialize the EngagementContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow. + :param sid: The SID of the Engagement resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "sid": sid, + } + self._uri = "/Flows/{flow_sid}/Engagements/{sid}".format(**self._solution) + + self._engagement_context: Optional[EngagementContextList] = None + self._steps: Optional[StepList] = None + + def delete(self) -> bool: + """ + Deletes the EngagementInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EngagementInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> EngagementInstance: + """ + Fetch the EngagementInstance + + + :returns: The fetched EngagementInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EngagementInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EngagementInstance: + """ + Asynchronous coroutine to fetch the EngagementInstance + + + :returns: The fetched EngagementInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EngagementInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + @property + def engagement_context(self) -> EngagementContextList: + """ + Access the engagement_context + """ + if self._engagement_context is None: + self._engagement_context = EngagementContextList( + self._version, + self._solution["flow_sid"], + self._solution["sid"], + ) + return self._engagement_context + + @property + def steps(self) -> StepList: + """ + Access the steps + """ + if self._steps is None: + self._steps = StepList( + self._version, + self._solution["flow_sid"], + self._solution["sid"], + ) + return self._steps + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V1.EngagementContext {}>".format(context) + + +class EngagementPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EngagementInstance: + """ + Build an instance of EngagementInstance + + :param payload: Payload response from the API + """ + return EngagementInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V1.EngagementPage>" + + +class EngagementList(ListResource): + + def __init__(self, version: Version, flow_sid: str): + """ + Initialize the EngagementList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow to read Engagements from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + } + self._uri = "/Flows/{flow_sid}/Engagements".format(**self._solution) + + def create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> EngagementInstance: + """ + Create the EngagementInstance + + :param to: The Contact phone number to start a Studio Flow Engagement, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow Engagement. Available as variable `{{flow.channel.address}}` + :param parameters: A JSON string we will add to your flow's context and that you can access as variables inside your flow. For example, if you pass in `Parameters={'name':'Zeke'}` then inside a widget you can reference the variable `{{flow.data.name}}` which will return the string 'Zeke'. Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode your JSON string. + + :returns: The created EngagementInstance + """ + + data = values.of( + { + "To": to, + "From": from_, + "Parameters": serialize.object(parameters), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EngagementInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + async def create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> EngagementInstance: + """ + Asynchronously create the EngagementInstance + + :param to: The Contact phone number to start a Studio Flow Engagement, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow Engagement. Available as variable `{{flow.channel.address}}` + :param parameters: A JSON string we will add to your flow's context and that you can access as variables inside your flow. For example, if you pass in `Parameters={'name':'Zeke'}` then inside a widget you can reference the variable `{{flow.data.name}}` which will return the string 'Zeke'. Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode your JSON string. + + :returns: The created EngagementInstance + """ + + data = values.of( + { + "To": to, + "From": from_, + "Parameters": serialize.object(parameters), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EngagementInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EngagementInstance]: + """ + Streams EngagementInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EngagementInstance]: + """ + Asynchronously streams EngagementInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EngagementInstance]: + """ + Lists EngagementInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EngagementInstance]: + """ + Asynchronously lists EngagementInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EngagementPage: + """ + Retrieve a single page of EngagementInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EngagementInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EngagementPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EngagementPage: + """ + Asynchronously retrieve a single page of EngagementInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EngagementInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EngagementPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> EngagementPage: + """ + Retrieve a specific page of EngagementInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EngagementInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EngagementPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> EngagementPage: + """ + Asynchronously retrieve a specific page of EngagementInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EngagementInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EngagementPage(self._version, response, self._solution) + + def get(self, sid: str) -> EngagementContext: + """ + Constructs a EngagementContext + + :param sid: The SID of the Engagement resource to fetch. + """ + return EngagementContext( + self._version, flow_sid=self._solution["flow_sid"], sid=sid + ) + + def __call__(self, sid: str) -> EngagementContext: + """ + Constructs a EngagementContext + + :param sid: The SID of the Engagement resource to fetch. + """ + return EngagementContext( + self._version, flow_sid=self._solution["flow_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V1.EngagementList>" diff --git a/twilio/rest/studio/v1/flow/engagement/engagement_context.py b/twilio/rest/studio/v1/flow/engagement/engagement_context.py new file mode 100644 index 0000000000..73161011eb --- /dev/null +++ b/twilio/rest/studio/v1/flow/engagement/engagement_context.py @@ -0,0 +1,219 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class EngagementContextInstance(InstanceResource): + """ + :ivar account_sid: The SID of the Account. + :ivar context: As your flow executes, we save the state in what's called the Flow Context. Any data in the flow context can be accessed by your widgets as variables, either in configuration fields or in text areas as variable substitution. + :ivar engagement_sid: The SID of the Engagement. + :ivar flow_sid: The SID of the Flow. + :ivar url: The URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + engagement_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.engagement_sid: Optional[str] = payload.get("engagement_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + } + self._context: Optional[EngagementContextContext] = None + + @property + def _proxy(self) -> "EngagementContextContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EngagementContextContext for this EngagementContextInstance + """ + if self._context is None: + self._context = EngagementContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) + return self._context + + def fetch(self) -> "EngagementContextInstance": + """ + Fetch the EngagementContextInstance + + + :returns: The fetched EngagementContextInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EngagementContextInstance": + """ + Asynchronous coroutine to fetch the EngagementContextInstance + + + :returns: The fetched EngagementContextInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V1.EngagementContextInstance {}>".format(context) + + +class EngagementContextContext(InstanceContext): + + def __init__(self, version: Version, flow_sid: str, engagement_sid: str): + """ + Initialize the EngagementContextContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow. + :param engagement_sid: The SID of the Engagement. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + } + self._uri = "/Flows/{flow_sid}/Engagements/{engagement_sid}/Context".format( + **self._solution + ) + + def fetch(self) -> EngagementContextInstance: + """ + Fetch the EngagementContextInstance + + + :returns: The fetched EngagementContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EngagementContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) + + async def fetch_async(self) -> EngagementContextInstance: + """ + Asynchronous coroutine to fetch the EngagementContextInstance + + + :returns: The fetched EngagementContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EngagementContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V1.EngagementContextContext {}>".format(context) + + +class EngagementContextList(ListResource): + + def __init__(self, version: Version, flow_sid: str, engagement_sid: str): + """ + Initialize the EngagementContextList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow. + :param engagement_sid: The SID of the Engagement. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + } + + def get(self) -> EngagementContextContext: + """ + Constructs a EngagementContextContext + + """ + return EngagementContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) + + def __call__(self) -> EngagementContextContext: + """ + Constructs a EngagementContextContext + + """ + return EngagementContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V1.EngagementContextList>" diff --git a/twilio/rest/studio/v1/flow/engagement/step/__init__.py b/twilio/rest/studio/v1/flow/engagement/step/__init__.py new file mode 100644 index 0000000000..a5017c3313 --- /dev/null +++ b/twilio/rest/studio/v1/flow/engagement/step/__init__.py @@ -0,0 +1,496 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.studio.v1.flow.engagement.step.step_context import StepContextList + + +class StepInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Step resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Step resource. + :ivar flow_sid: The SID of the Flow. + :ivar engagement_sid: The SID of the Engagement. + :ivar name: The event that caused the Flow to transition to the Step. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar parent_step_sid: The SID of the parent Step. + :ivar transitioned_from: The Widget that preceded the Widget for the Step. + :ivar transitioned_to: The Widget that will follow the Widget for the Step. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + engagement_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.engagement_sid: Optional[str] = payload.get("engagement_sid") + self.name: Optional[str] = payload.get("name") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.parent_step_sid: Optional[str] = payload.get("parent_step_sid") + self.transitioned_from: Optional[str] = payload.get("transitioned_from") + self.transitioned_to: Optional[str] = payload.get("transitioned_to") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + "sid": sid or self.sid, + } + self._context: Optional[StepContext] = None + + @property + def _proxy(self) -> "StepContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: StepContext for this StepInstance + """ + if self._context is None: + self._context = StepContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "StepInstance": + """ + Fetch the StepInstance + + + :returns: The fetched StepInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "StepInstance": + """ + Asynchronous coroutine to fetch the StepInstance + + + :returns: The fetched StepInstance + """ + return await self._proxy.fetch_async() + + @property + def step_context(self) -> StepContextList: + """ + Access the step_context + """ + return self._proxy.step_context + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V1.StepInstance {}>".format(context) + + +class StepContext(InstanceContext): + + def __init__(self, version: Version, flow_sid: str, engagement_sid: str, sid: str): + """ + Initialize the StepContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param engagement_sid: The SID of the Engagement with the Step to fetch. + :param sid: The SID of the Step resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + "sid": sid, + } + self._uri = "/Flows/{flow_sid}/Engagements/{engagement_sid}/Steps/{sid}".format( + **self._solution + ) + + self._step_context: Optional[StepContextList] = None + + def fetch(self) -> StepInstance: + """ + Fetch the StepInstance + + + :returns: The fetched StepInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return StepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> StepInstance: + """ + Asynchronous coroutine to fetch the StepInstance + + + :returns: The fetched StepInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return StepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=self._solution["sid"], + ) + + @property + def step_context(self) -> StepContextList: + """ + Access the step_context + """ + if self._step_context is None: + self._step_context = StepContextList( + self._version, + self._solution["flow_sid"], + self._solution["engagement_sid"], + self._solution["sid"], + ) + return self._step_context + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V1.StepContext {}>".format(context) + + +class StepPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> StepInstance: + """ + Build an instance of StepInstance + + :param payload: Payload response from the API + """ + return StepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V1.StepPage>" + + +class StepList(ListResource): + + def __init__(self, version: Version, flow_sid: str, engagement_sid: str): + """ + Initialize the StepList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to read. + :param engagement_sid: The SID of the Engagement with the Step to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + } + self._uri = "/Flows/{flow_sid}/Engagements/{engagement_sid}/Steps".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[StepInstance]: + """ + Streams StepInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[StepInstance]: + """ + Asynchronously streams StepInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[StepInstance]: + """ + Lists StepInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[StepInstance]: + """ + Asynchronously lists StepInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> StepPage: + """ + Retrieve a single page of StepInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of StepInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return StepPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> StepPage: + """ + Asynchronously retrieve a single page of StepInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of StepInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return StepPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> StepPage: + """ + Retrieve a specific page of StepInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of StepInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return StepPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> StepPage: + """ + Asynchronously retrieve a specific page of StepInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of StepInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return StepPage(self._version, response, self._solution) + + def get(self, sid: str) -> StepContext: + """ + Constructs a StepContext + + :param sid: The SID of the Step resource to fetch. + """ + return StepContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> StepContext: + """ + Constructs a StepContext + + :param sid: The SID of the Step resource to fetch. + """ + return StepContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V1.StepList>" diff --git a/twilio/rest/studio/v1/flow/engagement/step/step_context.py b/twilio/rest/studio/v1/flow/engagement/step/step_context.py new file mode 100644 index 0000000000..6b299ebe5d --- /dev/null +++ b/twilio/rest/studio/v1/flow/engagement/step/step_context.py @@ -0,0 +1,236 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class StepContextInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the StepContext resource. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar engagement_sid: The SID of the Engagement. + :ivar flow_sid: The SID of the Flow. + :ivar step_sid: The SID of the Step the context is associated with. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + engagement_sid: str, + step_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.engagement_sid: Optional[str] = payload.get("engagement_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.step_sid: Optional[str] = payload.get("step_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + "step_sid": step_sid, + } + self._context: Optional[StepContextContext] = None + + @property + def _proxy(self) -> "StepContextContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: StepContextContext for this StepContextInstance + """ + if self._context is None: + self._context = StepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], + ) + return self._context + + def fetch(self) -> "StepContextInstance": + """ + Fetch the StepContextInstance + + + :returns: The fetched StepContextInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "StepContextInstance": + """ + Asynchronous coroutine to fetch the StepContextInstance + + + :returns: The fetched StepContextInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V1.StepContextInstance {}>".format(context) + + +class StepContextContext(InstanceContext): + + def __init__( + self, version: Version, flow_sid: str, engagement_sid: str, step_sid: str + ): + """ + Initialize the StepContextContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param engagement_sid: The SID of the Engagement with the Step to fetch. + :param step_sid: The SID of the Step to fetch + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + "step_sid": step_sid, + } + self._uri = "/Flows/{flow_sid}/Engagements/{engagement_sid}/Steps/{step_sid}/Context".format( + **self._solution + ) + + def fetch(self) -> StepContextInstance: + """ + Fetch the StepContextInstance + + + :returns: The fetched StepContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return StepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], + ) + + async def fetch_async(self) -> StepContextInstance: + """ + Asynchronous coroutine to fetch the StepContextInstance + + + :returns: The fetched StepContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return StepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V1.StepContextContext {}>".format(context) + + +class StepContextList(ListResource): + + def __init__( + self, version: Version, flow_sid: str, engagement_sid: str, step_sid: str + ): + """ + Initialize the StepContextList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param engagement_sid: The SID of the Engagement with the Step to fetch. + :param step_sid: The SID of the Step to fetch + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "engagement_sid": engagement_sid, + "step_sid": step_sid, + } + + def get(self) -> StepContextContext: + """ + Constructs a StepContextContext + + """ + return StepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], + ) + + def __call__(self) -> StepContextContext: + """ + Constructs a StepContextContext + + """ + return StepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V1.StepContextList>" diff --git a/twilio/rest/studio/v1/flow/execution/__init__.py b/twilio/rest/studio/v1/flow/execution/__init__.py new file mode 100644 index 0000000000..624b381768 --- /dev/null +++ b/twilio/rest/studio/v1/flow/execution/__init__.py @@ -0,0 +1,740 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.studio.v1.flow.execution.execution_context import ExecutionContextList +from twilio.rest.studio.v1.flow.execution.execution_step import ExecutionStepList + + +class ExecutionInstance(InstanceResource): + + class Status(object): + ACTIVE = "active" + ENDED = "ended" + + """ + :ivar sid: The unique string that we created to identify the Execution resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Execution resource. + :ivar flow_sid: The SID of the Flow. + :ivar contact_sid: The SID of the Contact. + :ivar contact_channel_address: The phone number, SIP address or Client identifier that triggered the Execution. Phone numbers are in E.164 format (e.g. +16175551212). SIP addresses are formatted as `name@company.com`. Client identifiers are formatted `client:name`. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar status: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of nested resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.contact_sid: Optional[str] = payload.get("contact_sid") + self.contact_channel_address: Optional[str] = payload.get( + "contact_channel_address" + ) + self.context: Optional[Dict[str, object]] = payload.get("context") + self.status: Optional["ExecutionInstance.Status"] = payload.get("status") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "flow_sid": flow_sid, + "sid": sid or self.sid, + } + self._context: Optional[ExecutionContext] = None + + @property + def _proxy(self) -> "ExecutionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ExecutionContext for this ExecutionInstance + """ + if self._context is None: + self._context = ExecutionContext( + self._version, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ExecutionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ExecutionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ExecutionInstance": + """ + Fetch the ExecutionInstance + + + :returns: The fetched ExecutionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExecutionInstance": + """ + Asynchronous coroutine to fetch the ExecutionInstance + + + :returns: The fetched ExecutionInstance + """ + return await self._proxy.fetch_async() + + def update(self, status: "ExecutionInstance.Status") -> "ExecutionInstance": + """ + Update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + return self._proxy.update( + status=status, + ) + + async def update_async( + self, status: "ExecutionInstance.Status" + ) -> "ExecutionInstance": + """ + Asynchronous coroutine to update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + return await self._proxy.update_async( + status=status, + ) + + @property + def execution_context(self) -> ExecutionContextList: + """ + Access the execution_context + """ + return self._proxy.execution_context + + @property + def steps(self) -> ExecutionStepList: + """ + Access the steps + """ + return self._proxy.steps + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V1.ExecutionInstance {}>".format(context) + + +class ExecutionContext(InstanceContext): + + def __init__(self, version: Version, flow_sid: str, sid: str): + """ + Initialize the ExecutionContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution resources to update. + :param sid: The SID of the Execution resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "sid": sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{sid}".format(**self._solution) + + self._execution_context: Optional[ExecutionContextList] = None + self._steps: Optional[ExecutionStepList] = None + + def delete(self) -> bool: + """ + Deletes the ExecutionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ExecutionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ExecutionInstance: + """ + Fetch the ExecutionInstance + + + :returns: The fetched ExecutionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ExecutionInstance: + """ + Asynchronous coroutine to fetch the ExecutionInstance + + + :returns: The fetched ExecutionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + def update(self, status: "ExecutionInstance.Status") -> ExecutionInstance: + """ + Update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, status: "ExecutionInstance.Status" + ) -> ExecutionInstance: + """ + Asynchronous coroutine to update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + @property + def execution_context(self) -> ExecutionContextList: + """ + Access the execution_context + """ + if self._execution_context is None: + self._execution_context = ExecutionContextList( + self._version, + self._solution["flow_sid"], + self._solution["sid"], + ) + return self._execution_context + + @property + def steps(self) -> ExecutionStepList: + """ + Access the steps + """ + if self._steps is None: + self._steps = ExecutionStepList( + self._version, + self._solution["flow_sid"], + self._solution["sid"], + ) + return self._steps + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V1.ExecutionContext {}>".format(context) + + +class ExecutionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ExecutionInstance: + """ + Build an instance of ExecutionInstance + + :param payload: Payload response from the API + """ + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V1.ExecutionPage>" + + +class ExecutionList(ListResource): + + def __init__(self, version: Version, flow_sid: str): + """ + Initialize the ExecutionList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + } + self._uri = "/Flows/{flow_sid}/Executions".format(**self._solution) + + def create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: + """ + Create the ExecutionInstance + + :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. + :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + + :returns: The created ExecutionInstance + """ + + data = values.of( + { + "To": to, + "From": from_, + "Parameters": serialize.object(parameters), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + async def create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: + """ + Asynchronously create the ExecutionInstance + + :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. + :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + + :returns: The created ExecutionInstance + """ + + data = values.of( + { + "To": to, + "From": from_, + "Parameters": serialize.object(parameters), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + def stream( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ExecutionInstance]: + """ + Streams ExecutionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + date_created_from=date_created_from, + date_created_to=date_created_to, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ExecutionInstance]: + """ + Asynchronously streams ExecutionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + date_created_from=date_created_from, + date_created_to=date_created_to, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExecutionInstance]: + """ + Lists ExecutionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + date_created_from=date_created_from, + date_created_to=date_created_to, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExecutionInstance]: + """ + Asynchronously lists ExecutionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + date_created_from=date_created_from, + date_created_to=date_created_to, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExecutionPage: + """ + Retrieve a single page of ExecutionInstance records from the API. + Request is executed immediately + + :param date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExecutionInstance + """ + data = values.of( + { + "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), + "DateCreatedTo": serialize.iso8601_datetime(date_created_to), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionPage(self._version, response, self._solution) + + async def page_async( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExecutionPage: + """ + Asynchronously retrieve a single page of ExecutionInstance records from the API. + Request is executed immediately + + :param date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExecutionInstance + """ + data = values.of( + { + "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), + "DateCreatedTo": serialize.iso8601_datetime(date_created_to), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ExecutionPage: + """ + Retrieve a specific page of ExecutionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExecutionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ExecutionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ExecutionPage: + """ + Asynchronously retrieve a specific page of ExecutionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExecutionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ExecutionPage(self._version, response, self._solution) + + def get(self, sid: str) -> ExecutionContext: + """ + Constructs a ExecutionContext + + :param sid: The SID of the Execution resource to update. + """ + return ExecutionContext( + self._version, flow_sid=self._solution["flow_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ExecutionContext: + """ + Constructs a ExecutionContext + + :param sid: The SID of the Execution resource to update. + """ + return ExecutionContext( + self._version, flow_sid=self._solution["flow_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V1.ExecutionList>" diff --git a/twilio/rest/studio/v1/flow/execution/execution_context.py b/twilio/rest/studio/v1/flow/execution/execution_context.py new file mode 100644 index 0000000000..0841a9ef24 --- /dev/null +++ b/twilio/rest/studio/v1/flow/execution/execution_context.py @@ -0,0 +1,219 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ExecutionContextInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionContext resource. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar flow_sid: The SID of the Flow. + :ivar execution_sid: The SID of the context's Execution resource. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + execution_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.execution_sid: Optional[str] = payload.get("execution_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + self._context: Optional[ExecutionContextContext] = None + + @property + def _proxy(self) -> "ExecutionContextContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ExecutionContextContext for this ExecutionContextInstance + """ + if self._context is None: + self._context = ExecutionContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + return self._context + + def fetch(self) -> "ExecutionContextInstance": + """ + Fetch the ExecutionContextInstance + + + :returns: The fetched ExecutionContextInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExecutionContextInstance": + """ + Asynchronous coroutine to fetch the ExecutionContextInstance + + + :returns: The fetched ExecutionContextInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V1.ExecutionContextInstance {}>".format(context) + + +class ExecutionContextContext(InstanceContext): + + def __init__(self, version: Version, flow_sid: str, execution_sid: str): + """ + Initialize the ExecutionContextContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution context to fetch. + :param execution_sid: The SID of the Execution context to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Context".format( + **self._solution + ) + + def fetch(self) -> ExecutionContextInstance: + """ + Fetch the ExecutionContextInstance + + + :returns: The fetched ExecutionContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + + async def fetch_async(self) -> ExecutionContextInstance: + """ + Asynchronous coroutine to fetch the ExecutionContextInstance + + + :returns: The fetched ExecutionContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V1.ExecutionContextContext {}>".format(context) + + +class ExecutionContextList(ListResource): + + def __init__(self, version: Version, flow_sid: str, execution_sid: str): + """ + Initialize the ExecutionContextList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution context to fetch. + :param execution_sid: The SID of the Execution context to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + + def get(self) -> ExecutionContextContext: + """ + Constructs a ExecutionContextContext + + """ + return ExecutionContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + + def __call__(self) -> ExecutionContextContext: + """ + Constructs a ExecutionContextContext + + """ + return ExecutionContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V1.ExecutionContextList>" diff --git a/twilio/rest/studio/v1/flow/execution/execution_step/__init__.py b/twilio/rest/studio/v1/flow/execution/execution_step/__init__.py new file mode 100644 index 0000000000..50a1e2371d --- /dev/null +++ b/twilio/rest/studio/v1/flow/execution/execution_step/__init__.py @@ -0,0 +1,498 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.studio.v1.flow.execution.execution_step.execution_step_context import ( + ExecutionStepContextList, +) + + +class ExecutionStepInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the ExecutionStep resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionStep resource. + :ivar flow_sid: The SID of the Flow. + :ivar execution_sid: The SID of the Step's Execution resource. + :ivar parent_step_sid: This field shows the Step SID of the Widget in the parent Flow that started the Subflow. If this Step is not part of a Subflow execution, the value is null. + :ivar name: The event that caused the Flow to transition to the Step. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar transitioned_from: The Widget that preceded the Widget for the Step. + :ivar transitioned_to: The Widget that will follow the Widget for the Step. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + execution_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.execution_sid: Optional[str] = payload.get("execution_sid") + self.parent_step_sid: Optional[str] = payload.get("parent_step_sid") + self.name: Optional[str] = payload.get("name") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.transitioned_from: Optional[str] = payload.get("transitioned_from") + self.transitioned_to: Optional[str] = payload.get("transitioned_to") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "sid": sid or self.sid, + } + self._context: Optional[ExecutionStepContext] = None + + @property + def _proxy(self) -> "ExecutionStepContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ExecutionStepContext for this ExecutionStepInstance + """ + if self._context is None: + self._context = ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ExecutionStepInstance": + """ + Fetch the ExecutionStepInstance + + + :returns: The fetched ExecutionStepInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExecutionStepInstance": + """ + Asynchronous coroutine to fetch the ExecutionStepInstance + + + :returns: The fetched ExecutionStepInstance + """ + return await self._proxy.fetch_async() + + @property + def step_context(self) -> ExecutionStepContextList: + """ + Access the step_context + """ + return self._proxy.step_context + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V1.ExecutionStepInstance {}>".format(context) + + +class ExecutionStepContext(InstanceContext): + + def __init__(self, version: Version, flow_sid: str, execution_sid: str, sid: str): + """ + Initialize the ExecutionStepContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param execution_sid: The SID of the Execution resource with the Step to fetch. + :param sid: The SID of the ExecutionStep resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "sid": sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Steps/{sid}".format( + **self._solution + ) + + self._step_context: Optional[ExecutionStepContextList] = None + + def fetch(self) -> ExecutionStepInstance: + """ + Fetch the ExecutionStepInstance + + + :returns: The fetched ExecutionStepInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ExecutionStepInstance: + """ + Asynchronous coroutine to fetch the ExecutionStepInstance + + + :returns: The fetched ExecutionStepInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) + + @property + def step_context(self) -> ExecutionStepContextList: + """ + Access the step_context + """ + if self._step_context is None: + self._step_context = ExecutionStepContextList( + self._version, + self._solution["flow_sid"], + self._solution["execution_sid"], + self._solution["sid"], + ) + return self._step_context + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V1.ExecutionStepContext {}>".format(context) + + +class ExecutionStepPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ExecutionStepInstance: + """ + Build an instance of ExecutionStepInstance + + :param payload: Payload response from the API + """ + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V1.ExecutionStepPage>" + + +class ExecutionStepList(ListResource): + + def __init__(self, version: Version, flow_sid: str, execution_sid: str): + """ + Initialize the ExecutionStepList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Steps to read. + :param execution_sid: The SID of the Execution with the Steps to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Steps".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ExecutionStepInstance]: + """ + Streams ExecutionStepInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ExecutionStepInstance]: + """ + Asynchronously streams ExecutionStepInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExecutionStepInstance]: + """ + Lists ExecutionStepInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExecutionStepInstance]: + """ + Asynchronously lists ExecutionStepInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExecutionStepPage: + """ + Retrieve a single page of ExecutionStepInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExecutionStepInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionStepPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExecutionStepPage: + """ + Asynchronously retrieve a single page of ExecutionStepInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExecutionStepInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionStepPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ExecutionStepPage: + """ + Retrieve a specific page of ExecutionStepInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExecutionStepInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ExecutionStepPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ExecutionStepPage: + """ + Asynchronously retrieve a specific page of ExecutionStepInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExecutionStepInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ExecutionStepPage(self._version, response, self._solution) + + def get(self, sid: str) -> ExecutionStepContext: + """ + Constructs a ExecutionStepContext + + :param sid: The SID of the ExecutionStep resource to fetch. + """ + return ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ExecutionStepContext: + """ + Constructs a ExecutionStepContext + + :param sid: The SID of the ExecutionStep resource to fetch. + """ + return ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V1.ExecutionStepList>" diff --git a/twilio/rest/studio/v1/flow/execution/execution_step/execution_step_context.py b/twilio/rest/studio/v1/flow/execution/execution_step/execution_step_context.py new file mode 100644 index 0000000000..78249a9562 --- /dev/null +++ b/twilio/rest/studio/v1/flow/execution/execution_step/execution_step_context.py @@ -0,0 +1,236 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ExecutionStepContextInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionStepContext resource. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar execution_sid: The SID of the context's Execution resource. + :ivar flow_sid: The SID of the Flow. + :ivar step_sid: The SID of the Step that the context is associated with. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + execution_sid: str, + step_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.execution_sid: Optional[str] = payload.get("execution_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.step_sid: Optional[str] = payload.get("step_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "step_sid": step_sid, + } + self._context: Optional[ExecutionStepContextContext] = None + + @property + def _proxy(self) -> "ExecutionStepContextContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ExecutionStepContextContext for this ExecutionStepContextInstance + """ + if self._context is None: + self._context = ExecutionStepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + return self._context + + def fetch(self) -> "ExecutionStepContextInstance": + """ + Fetch the ExecutionStepContextInstance + + + :returns: The fetched ExecutionStepContextInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExecutionStepContextInstance": + """ + Asynchronous coroutine to fetch the ExecutionStepContextInstance + + + :returns: The fetched ExecutionStepContextInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V1.ExecutionStepContextInstance {}>".format(context) + + +class ExecutionStepContextContext(InstanceContext): + + def __init__( + self, version: Version, flow_sid: str, execution_sid: str, step_sid: str + ): + """ + Initialize the ExecutionStepContextContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param execution_sid: The SID of the Execution resource with the Step to fetch. + :param step_sid: The SID of the Step to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "step_sid": step_sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Steps/{step_sid}/Context".format( + **self._solution + ) + + def fetch(self) -> ExecutionStepContextInstance: + """ + Fetch the ExecutionStepContextInstance + + + :returns: The fetched ExecutionStepContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + + async def fetch_async(self) -> ExecutionStepContextInstance: + """ + Asynchronous coroutine to fetch the ExecutionStepContextInstance + + + :returns: The fetched ExecutionStepContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V1.ExecutionStepContextContext {}>".format(context) + + +class ExecutionStepContextList(ListResource): + + def __init__( + self, version: Version, flow_sid: str, execution_sid: str, step_sid: str + ): + """ + Initialize the ExecutionStepContextList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param execution_sid: The SID of the Execution resource with the Step to fetch. + :param step_sid: The SID of the Step to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "step_sid": step_sid, + } + + def get(self) -> ExecutionStepContextContext: + """ + Constructs a ExecutionStepContextContext + + """ + return ExecutionStepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + + def __call__(self) -> ExecutionStepContextContext: + """ + Constructs a ExecutionStepContextContext + + """ + return ExecutionStepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V1.ExecutionStepContextList>" diff --git a/twilio/rest/studio/v2/__init__.py b/twilio/rest/studio/v2/__init__.py new file mode 100644 index 0000000000..83ccc8e0a9 --- /dev/null +++ b/twilio/rest/studio/v2/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.studio.v2.flow import FlowList +from twilio.rest.studio.v2.flow_validate import FlowValidateList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Studio + + :param domain: The Twilio.studio domain + """ + super().__init__(domain, "v2") + self._flows: Optional[FlowList] = None + self._flow_validate: Optional[FlowValidateList] = None + + @property + def flows(self) -> FlowList: + if self._flows is None: + self._flows = FlowList(self) + return self._flows + + @property + def flow_validate(self) -> FlowValidateList: + if self._flow_validate is None: + self._flow_validate = FlowValidateList(self) + return self._flow_validate + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V2>" diff --git a/twilio/rest/studio/v2/flow/__init__.py b/twilio/rest/studio/v2/flow/__init__.py new file mode 100644 index 0000000000..b4c542fdc0 --- /dev/null +++ b/twilio/rest/studio/v2/flow/__init__.py @@ -0,0 +1,746 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.studio.v2.flow.execution import ExecutionList +from twilio.rest.studio.v2.flow.flow_revision import FlowRevisionList +from twilio.rest.studio.v2.flow.flow_test_user import FlowTestUserList + + +class FlowInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PUBLISHED = "published" + + """ + :ivar sid: The unique string that we created to identify the Flow resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flow resource. + :ivar friendly_name: The string that you assigned to describe the Flow. + :ivar definition: JSON representation of flow definition. + :ivar status: + :ivar revision: The latest revision number of the Flow's definition. + :ivar commit_message: Description of change made in the revision. + :ivar valid: Boolean if the flow definition is valid. + :ivar errors: List of error in the flow definition. + :ivar warnings: List of warnings in the flow definition. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar webhook_url: + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of the Flow's nested resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.definition: Optional[Dict[str, object]] = payload.get("definition") + self.status: Optional["FlowInstance.Status"] = payload.get("status") + self.revision: Optional[int] = deserialize.integer(payload.get("revision")) + self.commit_message: Optional[str] = payload.get("commit_message") + self.valid: Optional[bool] = payload.get("valid") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") + self.warnings: Optional[List[Dict[str, object]]] = payload.get("warnings") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.webhook_url: Optional[str] = payload.get("webhook_url") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[FlowContext] = None + + @property + def _proxy(self) -> "FlowContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FlowContext for this FlowInstance + """ + if self._context is None: + self._context = FlowContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the FlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "FlowInstance": + """ + Fetch the FlowInstance + + + :returns: The fetched FlowInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FlowInstance": + """ + Asynchronous coroutine to fetch the FlowInstance + + + :returns: The fetched FlowInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + status: "FlowInstance.Status", + friendly_name: Union[str, object] = values.unset, + definition: Union[object, object] = values.unset, + commit_message: Union[str, object] = values.unset, + ) -> "FlowInstance": + """ + Update the FlowInstance + + :param status: + :param friendly_name: The string that you assigned to describe the Flow. + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: The updated FlowInstance + """ + return self._proxy.update( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + ) + + async def update_async( + self, + status: "FlowInstance.Status", + friendly_name: Union[str, object] = values.unset, + definition: Union[object, object] = values.unset, + commit_message: Union[str, object] = values.unset, + ) -> "FlowInstance": + """ + Asynchronous coroutine to update the FlowInstance + + :param status: + :param friendly_name: The string that you assigned to describe the Flow. + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: The updated FlowInstance + """ + return await self._proxy.update_async( + status=status, + friendly_name=friendly_name, + definition=definition, + commit_message=commit_message, + ) + + @property + def executions(self) -> ExecutionList: + """ + Access the executions + """ + return self._proxy.executions + + @property + def revisions(self) -> FlowRevisionList: + """ + Access the revisions + """ + return self._proxy.revisions + + @property + def test_users(self) -> FlowTestUserList: + """ + Access the test_users + """ + return self._proxy.test_users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V2.FlowInstance {}>".format(context) + + +class FlowContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the FlowContext + + :param version: Version that contains the resource + :param sid: The SID of the Flow resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Flows/{sid}".format(**self._solution) + + self._executions: Optional[ExecutionList] = None + self._revisions: Optional[FlowRevisionList] = None + self._test_users: Optional[FlowTestUserList] = None + + def delete(self) -> bool: + """ + Deletes the FlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FlowInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> FlowInstance: + """ + Fetch the FlowInstance + + + :returns: The fetched FlowInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> FlowInstance: + """ + Asynchronous coroutine to fetch the FlowInstance + + + :returns: The fetched FlowInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FlowInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + status: "FlowInstance.Status", + friendly_name: Union[str, object] = values.unset, + definition: Union[object, object] = values.unset, + commit_message: Union[str, object] = values.unset, + ) -> FlowInstance: + """ + Update the FlowInstance + + :param status: + :param friendly_name: The string that you assigned to describe the Flow. + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: The updated FlowInstance + """ + + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "Definition": serialize.object(definition), + "CommitMessage": commit_message, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlowInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + status: "FlowInstance.Status", + friendly_name: Union[str, object] = values.unset, + definition: Union[object, object] = values.unset, + commit_message: Union[str, object] = values.unset, + ) -> FlowInstance: + """ + Asynchronous coroutine to update the FlowInstance + + :param status: + :param friendly_name: The string that you assigned to describe the Flow. + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: The updated FlowInstance + """ + + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "Definition": serialize.object(definition), + "CommitMessage": commit_message, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlowInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def executions(self) -> ExecutionList: + """ + Access the executions + """ + if self._executions is None: + self._executions = ExecutionList( + self._version, + self._solution["sid"], + ) + return self._executions + + @property + def revisions(self) -> FlowRevisionList: + """ + Access the revisions + """ + if self._revisions is None: + self._revisions = FlowRevisionList( + self._version, + self._solution["sid"], + ) + return self._revisions + + @property + def test_users(self) -> FlowTestUserList: + """ + Access the test_users + """ + if self._test_users is None: + self._test_users = FlowTestUserList( + self._version, + self._solution["sid"], + ) + return self._test_users + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V2.FlowContext {}>".format(context) + + +class FlowPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FlowInstance: + """ + Build an instance of FlowInstance + + :param payload: Payload response from the API + """ + return FlowInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V2.FlowPage>" + + +class FlowList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the FlowList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Flows" + + def create( + self, + friendly_name: str, + status: "FlowInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> FlowInstance: + """ + Create the FlowInstance + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: The created FlowInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "Definition": serialize.object(definition), + "CommitMessage": commit_message, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlowInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + status: "FlowInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> FlowInstance: + """ + Asynchronously create the FlowInstance + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: The created FlowInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "Definition": serialize.object(definition), + "CommitMessage": commit_message, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlowInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FlowInstance]: + """ + Streams FlowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FlowInstance]: + """ + Asynchronously streams FlowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlowInstance]: + """ + Lists FlowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlowInstance]: + """ + Asynchronously lists FlowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FlowPage: + """ + Retrieve a single page of FlowInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FlowInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlowPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FlowPage: + """ + Asynchronously retrieve a single page of FlowInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FlowInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlowPage(self._version, response) + + def get_page(self, target_url: str) -> FlowPage: + """ + Retrieve a specific page of FlowInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FlowInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FlowPage(self._version, response) + + async def get_page_async(self, target_url: str) -> FlowPage: + """ + Asynchronously retrieve a specific page of FlowInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FlowInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FlowPage(self._version, response) + + def get(self, sid: str) -> FlowContext: + """ + Constructs a FlowContext + + :param sid: The SID of the Flow resource to fetch. + """ + return FlowContext(self._version, sid=sid) + + def __call__(self, sid: str) -> FlowContext: + """ + Constructs a FlowContext + + :param sid: The SID of the Flow resource to fetch. + """ + return FlowContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V2.FlowList>" diff --git a/twilio/rest/studio/v2/flow/execution/__init__.py b/twilio/rest/studio/v2/flow/execution/__init__.py new file mode 100644 index 0000000000..c47a3fbbc0 --- /dev/null +++ b/twilio/rest/studio/v2/flow/execution/__init__.py @@ -0,0 +1,738 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.studio.v2.flow.execution.execution_context import ExecutionContextList +from twilio.rest.studio.v2.flow.execution.execution_step import ExecutionStepList + + +class ExecutionInstance(InstanceResource): + + class Status(object): + ACTIVE = "active" + ENDED = "ended" + + """ + :ivar sid: The unique string that we created to identify the Execution resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Execution resource. + :ivar flow_sid: The SID of the Flow. + :ivar contact_channel_address: The phone number, SIP address or Client identifier that triggered the Execution. Phone numbers are in E.164 format (e.g. +16175551212). SIP addresses are formatted as `name@company.com`. Client identifiers are formatted `client:name`. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar status: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of nested resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.contact_channel_address: Optional[str] = payload.get( + "contact_channel_address" + ) + self.context: Optional[Dict[str, object]] = payload.get("context") + self.status: Optional["ExecutionInstance.Status"] = payload.get("status") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "flow_sid": flow_sid, + "sid": sid or self.sid, + } + self._context: Optional[ExecutionContext] = None + + @property + def _proxy(self) -> "ExecutionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ExecutionContext for this ExecutionInstance + """ + if self._context is None: + self._context = ExecutionContext( + self._version, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ExecutionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ExecutionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ExecutionInstance": + """ + Fetch the ExecutionInstance + + + :returns: The fetched ExecutionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExecutionInstance": + """ + Asynchronous coroutine to fetch the ExecutionInstance + + + :returns: The fetched ExecutionInstance + """ + return await self._proxy.fetch_async() + + def update(self, status: "ExecutionInstance.Status") -> "ExecutionInstance": + """ + Update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + return self._proxy.update( + status=status, + ) + + async def update_async( + self, status: "ExecutionInstance.Status" + ) -> "ExecutionInstance": + """ + Asynchronous coroutine to update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + return await self._proxy.update_async( + status=status, + ) + + @property + def execution_context(self) -> ExecutionContextList: + """ + Access the execution_context + """ + return self._proxy.execution_context + + @property + def steps(self) -> ExecutionStepList: + """ + Access the steps + """ + return self._proxy.steps + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V2.ExecutionInstance {}>".format(context) + + +class ExecutionContext(InstanceContext): + + def __init__(self, version: Version, flow_sid: str, sid: str): + """ + Initialize the ExecutionContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution resources to update. + :param sid: The SID of the Execution resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "sid": sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{sid}".format(**self._solution) + + self._execution_context: Optional[ExecutionContextList] = None + self._steps: Optional[ExecutionStepList] = None + + def delete(self) -> bool: + """ + Deletes the ExecutionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ExecutionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ExecutionInstance: + """ + Fetch the ExecutionInstance + + + :returns: The fetched ExecutionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ExecutionInstance: + """ + Asynchronous coroutine to fetch the ExecutionInstance + + + :returns: The fetched ExecutionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + def update(self, status: "ExecutionInstance.Status") -> ExecutionInstance: + """ + Update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, status: "ExecutionInstance.Status" + ) -> ExecutionInstance: + """ + Asynchronous coroutine to update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], + ) + + @property + def execution_context(self) -> ExecutionContextList: + """ + Access the execution_context + """ + if self._execution_context is None: + self._execution_context = ExecutionContextList( + self._version, + self._solution["flow_sid"], + self._solution["sid"], + ) + return self._execution_context + + @property + def steps(self) -> ExecutionStepList: + """ + Access the steps + """ + if self._steps is None: + self._steps = ExecutionStepList( + self._version, + self._solution["flow_sid"], + self._solution["sid"], + ) + return self._steps + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V2.ExecutionContext {}>".format(context) + + +class ExecutionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ExecutionInstance: + """ + Build an instance of ExecutionInstance + + :param payload: Payload response from the API + """ + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V2.ExecutionPage>" + + +class ExecutionList(ListResource): + + def __init__(self, version: Version, flow_sid: str): + """ + Initialize the ExecutionList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + } + self._uri = "/Flows/{flow_sid}/Executions".format(**self._solution) + + def create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: + """ + Create the ExecutionInstance + + :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. + :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + + :returns: The created ExecutionInstance + """ + + data = values.of( + { + "To": to, + "From": from_, + "Parameters": serialize.object(parameters), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + async def create_async( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ExecutionInstance: + """ + Asynchronously create the ExecutionInstance + + :param to: The Contact phone number to start a Studio Flow Execution, available as variable `{{contact.channel.address}}`. + :param from_: The Twilio phone number to send messages or initiate calls from during the Flow's Execution. Available as variable `{{flow.channel.address}}`. For SMS, this can also be a Messaging Service SID. + :param parameters: JSON data that will be added to the Flow's context and that can be accessed as variables inside your Flow. For example, if you pass in `Parameters={\\\"name\\\":\\\"Zeke\\\"}`, a widget in your Flow can reference the variable `{{flow.data.name}}`, which returns \\\"Zeke\\\". Note: the JSON value must explicitly be passed as a string, not as a hash object. Depending on your particular HTTP library, you may need to add quotes or URL encode the JSON string. + + :returns: The created ExecutionInstance + """ + + data = values.of( + { + "To": to, + "From": from_, + "Parameters": serialize.object(parameters), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + def stream( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ExecutionInstance]: + """ + Streams ExecutionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + date_created_from=date_created_from, + date_created_to=date_created_to, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ExecutionInstance]: + """ + Asynchronously streams ExecutionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + date_created_from=date_created_from, + date_created_to=date_created_to, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExecutionInstance]: + """ + Lists ExecutionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + date_created_from=date_created_from, + date_created_to=date_created_to, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExecutionInstance]: + """ + Asynchronously lists ExecutionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param datetime date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + date_created_from=date_created_from, + date_created_to=date_created_to, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExecutionPage: + """ + Retrieve a single page of ExecutionInstance records from the API. + Request is executed immediately + + :param date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExecutionInstance + """ + data = values.of( + { + "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), + "DateCreatedTo": serialize.iso8601_datetime(date_created_to), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionPage(self._version, response, self._solution) + + async def page_async( + self, + date_created_from: Union[datetime, object] = values.unset, + date_created_to: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExecutionPage: + """ + Asynchronously retrieve a single page of ExecutionInstance records from the API. + Request is executed immediately + + :param date_created_from: Only show Execution resources starting on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param date_created_to: Only show Execution resources starting before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time, given as `YYYY-MM-DDThh:mm:ss-hh:mm`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExecutionInstance + """ + data = values.of( + { + "DateCreatedFrom": serialize.iso8601_datetime(date_created_from), + "DateCreatedTo": serialize.iso8601_datetime(date_created_to), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ExecutionPage: + """ + Retrieve a specific page of ExecutionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExecutionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ExecutionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ExecutionPage: + """ + Asynchronously retrieve a specific page of ExecutionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExecutionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ExecutionPage(self._version, response, self._solution) + + def get(self, sid: str) -> ExecutionContext: + """ + Constructs a ExecutionContext + + :param sid: The SID of the Execution resource to update. + """ + return ExecutionContext( + self._version, flow_sid=self._solution["flow_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ExecutionContext: + """ + Constructs a ExecutionContext + + :param sid: The SID of the Execution resource to update. + """ + return ExecutionContext( + self._version, flow_sid=self._solution["flow_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V2.ExecutionList>" diff --git a/twilio/rest/studio/v2/flow/execution/execution_context.py b/twilio/rest/studio/v2/flow/execution/execution_context.py new file mode 100644 index 0000000000..4c18f81d11 --- /dev/null +++ b/twilio/rest/studio/v2/flow/execution/execution_context.py @@ -0,0 +1,219 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ExecutionContextInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionContext resource. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar flow_sid: The SID of the Flow. + :ivar execution_sid: The SID of the context's Execution resource. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + execution_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.execution_sid: Optional[str] = payload.get("execution_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + self._context: Optional[ExecutionContextContext] = None + + @property + def _proxy(self) -> "ExecutionContextContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ExecutionContextContext for this ExecutionContextInstance + """ + if self._context is None: + self._context = ExecutionContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + return self._context + + def fetch(self) -> "ExecutionContextInstance": + """ + Fetch the ExecutionContextInstance + + + :returns: The fetched ExecutionContextInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExecutionContextInstance": + """ + Asynchronous coroutine to fetch the ExecutionContextInstance + + + :returns: The fetched ExecutionContextInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V2.ExecutionContextInstance {}>".format(context) + + +class ExecutionContextContext(InstanceContext): + + def __init__(self, version: Version, flow_sid: str, execution_sid: str): + """ + Initialize the ExecutionContextContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution context to fetch. + :param execution_sid: The SID of the Execution context to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Context".format( + **self._solution + ) + + def fetch(self) -> ExecutionContextInstance: + """ + Fetch the ExecutionContextInstance + + + :returns: The fetched ExecutionContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + + async def fetch_async(self) -> ExecutionContextInstance: + """ + Asynchronous coroutine to fetch the ExecutionContextInstance + + + :returns: The fetched ExecutionContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V2.ExecutionContextContext {}>".format(context) + + +class ExecutionContextList(ListResource): + + def __init__(self, version: Version, flow_sid: str, execution_sid: str): + """ + Initialize the ExecutionContextList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Execution context to fetch. + :param execution_sid: The SID of the Execution context to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + + def get(self) -> ExecutionContextContext: + """ + Constructs a ExecutionContextContext + + """ + return ExecutionContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + + def __call__(self) -> ExecutionContextContext: + """ + Constructs a ExecutionContextContext + + """ + return ExecutionContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V2.ExecutionContextList>" diff --git a/twilio/rest/studio/v2/flow/execution/execution_step/__init__.py b/twilio/rest/studio/v2/flow/execution/execution_step/__init__.py new file mode 100644 index 0000000000..9ffb2502e6 --- /dev/null +++ b/twilio/rest/studio/v2/flow/execution/execution_step/__init__.py @@ -0,0 +1,498 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.studio.v2.flow.execution.execution_step.execution_step_context import ( + ExecutionStepContextList, +) + + +class ExecutionStepInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the ExecutionStep resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionStep resource. + :ivar flow_sid: The SID of the Flow. + :ivar execution_sid: The SID of the Step's Execution resource. + :ivar parent_step_sid: The SID of the parent Step. + :ivar name: The event that caused the Flow to transition to the Step. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar transitioned_from: The Widget that preceded the Widget for the Step. + :ivar transitioned_to: The Widget that will follow the Widget for the Step. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + execution_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.execution_sid: Optional[str] = payload.get("execution_sid") + self.parent_step_sid: Optional[str] = payload.get("parent_step_sid") + self.name: Optional[str] = payload.get("name") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.transitioned_from: Optional[str] = payload.get("transitioned_from") + self.transitioned_to: Optional[str] = payload.get("transitioned_to") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "sid": sid or self.sid, + } + self._context: Optional[ExecutionStepContext] = None + + @property + def _proxy(self) -> "ExecutionStepContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ExecutionStepContext for this ExecutionStepInstance + """ + if self._context is None: + self._context = ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ExecutionStepInstance": + """ + Fetch the ExecutionStepInstance + + + :returns: The fetched ExecutionStepInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExecutionStepInstance": + """ + Asynchronous coroutine to fetch the ExecutionStepInstance + + + :returns: The fetched ExecutionStepInstance + """ + return await self._proxy.fetch_async() + + @property + def step_context(self) -> ExecutionStepContextList: + """ + Access the step_context + """ + return self._proxy.step_context + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V2.ExecutionStepInstance {}>".format(context) + + +class ExecutionStepContext(InstanceContext): + + def __init__(self, version: Version, flow_sid: str, execution_sid: str, sid: str): + """ + Initialize the ExecutionStepContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param execution_sid: The SID of the Execution resource with the Step to fetch. + :param sid: The SID of the ExecutionStep resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "sid": sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Steps/{sid}".format( + **self._solution + ) + + self._step_context: Optional[ExecutionStepContextList] = None + + def fetch(self) -> ExecutionStepInstance: + """ + Fetch the ExecutionStepInstance + + + :returns: The fetched ExecutionStepInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ExecutionStepInstance: + """ + Asynchronous coroutine to fetch the ExecutionStepInstance + + + :returns: The fetched ExecutionStepInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], + ) + + @property + def step_context(self) -> ExecutionStepContextList: + """ + Access the step_context + """ + if self._step_context is None: + self._step_context = ExecutionStepContextList( + self._version, + self._solution["flow_sid"], + self._solution["execution_sid"], + self._solution["sid"], + ) + return self._step_context + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V2.ExecutionStepContext {}>".format(context) + + +class ExecutionStepPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ExecutionStepInstance: + """ + Build an instance of ExecutionStepInstance + + :param payload: Payload response from the API + """ + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V2.ExecutionStepPage>" + + +class ExecutionStepList(ListResource): + + def __init__(self, version: Version, flow_sid: str, execution_sid: str): + """ + Initialize the ExecutionStepList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Steps to read. + :param execution_sid: The SID of the Execution with the Steps to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Steps".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ExecutionStepInstance]: + """ + Streams ExecutionStepInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ExecutionStepInstance]: + """ + Asynchronously streams ExecutionStepInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExecutionStepInstance]: + """ + Lists ExecutionStepInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ExecutionStepInstance]: + """ + Asynchronously lists ExecutionStepInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExecutionStepPage: + """ + Retrieve a single page of ExecutionStepInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExecutionStepInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionStepPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ExecutionStepPage: + """ + Asynchronously retrieve a single page of ExecutionStepInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ExecutionStepInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ExecutionStepPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ExecutionStepPage: + """ + Retrieve a specific page of ExecutionStepInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExecutionStepInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ExecutionStepPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ExecutionStepPage: + """ + Asynchronously retrieve a specific page of ExecutionStepInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ExecutionStepInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ExecutionStepPage(self._version, response, self._solution) + + def get(self, sid: str) -> ExecutionStepContext: + """ + Constructs a ExecutionStepContext + + :param sid: The SID of the ExecutionStep resource to fetch. + """ + return ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ExecutionStepContext: + """ + Constructs a ExecutionStepContext + + :param sid: The SID of the ExecutionStep resource to fetch. + """ + return ExecutionStepContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V2.ExecutionStepList>" diff --git a/twilio/rest/studio/v2/flow/execution/execution_step/execution_step_context.py b/twilio/rest/studio/v2/flow/execution/execution_step/execution_step_context.py new file mode 100644 index 0000000000..7f00e0d180 --- /dev/null +++ b/twilio/rest/studio/v2/flow/execution/execution_step/execution_step_context.py @@ -0,0 +1,236 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ExecutionStepContextInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionStepContext resource. + :ivar context: The current state of the Flow's Execution. As a flow executes, we save its state in this context. We save data that your widgets can access as variables in configuration fields or in text areas as variable substitution. + :ivar execution_sid: The SID of the context's Execution resource. + :ivar flow_sid: The SID of the Flow. + :ivar step_sid: The SID of the Step that the context is associated with. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + flow_sid: str, + execution_sid: str, + step_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.context: Optional[Dict[str, object]] = payload.get("context") + self.execution_sid: Optional[str] = payload.get("execution_sid") + self.flow_sid: Optional[str] = payload.get("flow_sid") + self.step_sid: Optional[str] = payload.get("step_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "step_sid": step_sid, + } + self._context: Optional[ExecutionStepContextContext] = None + + @property + def _proxy(self) -> "ExecutionStepContextContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ExecutionStepContextContext for this ExecutionStepContextInstance + """ + if self._context is None: + self._context = ExecutionStepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + return self._context + + def fetch(self) -> "ExecutionStepContextInstance": + """ + Fetch the ExecutionStepContextInstance + + + :returns: The fetched ExecutionStepContextInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ExecutionStepContextInstance": + """ + Asynchronous coroutine to fetch the ExecutionStepContextInstance + + + :returns: The fetched ExecutionStepContextInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V2.ExecutionStepContextInstance {}>".format(context) + + +class ExecutionStepContextContext(InstanceContext): + + def __init__( + self, version: Version, flow_sid: str, execution_sid: str, step_sid: str + ): + """ + Initialize the ExecutionStepContextContext + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param execution_sid: The SID of the Execution resource with the Step to fetch. + :param step_sid: The SID of the Step to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "step_sid": step_sid, + } + self._uri = "/Flows/{flow_sid}/Executions/{execution_sid}/Steps/{step_sid}/Context".format( + **self._solution + ) + + def fetch(self) -> ExecutionStepContextInstance: + """ + Fetch the ExecutionStepContextInstance + + + :returns: The fetched ExecutionStepContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + + async def fetch_async(self) -> ExecutionStepContextInstance: + """ + Asynchronous coroutine to fetch the ExecutionStepContextInstance + + + :returns: The fetched ExecutionStepContextInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V2.ExecutionStepContextContext {}>".format(context) + + +class ExecutionStepContextList(ListResource): + + def __init__( + self, version: Version, flow_sid: str, execution_sid: str, step_sid: str + ): + """ + Initialize the ExecutionStepContextList + + :param version: Version that contains the resource + :param flow_sid: The SID of the Flow with the Step to fetch. + :param execution_sid: The SID of the Execution resource with the Step to fetch. + :param step_sid: The SID of the Step to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "flow_sid": flow_sid, + "execution_sid": execution_sid, + "step_sid": step_sid, + } + + def get(self) -> ExecutionStepContextContext: + """ + Constructs a ExecutionStepContextContext + + """ + return ExecutionStepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + + def __call__(self) -> ExecutionStepContextContext: + """ + Constructs a ExecutionStepContextContext + + """ + return ExecutionStepContextContext( + self._version, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V2.ExecutionStepContextList>" diff --git a/twilio/rest/studio/v2/flow/flow_revision.py b/twilio/rest/studio/v2/flow/flow_revision.py new file mode 100644 index 0000000000..aa065074d1 --- /dev/null +++ b/twilio/rest/studio/v2/flow/flow_revision.py @@ -0,0 +1,451 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class FlowRevisionInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PUBLISHED = "published" + + """ + :ivar sid: The unique string that we created to identify the Flow resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flow resource. + :ivar friendly_name: The string that you assigned to describe the Flow. + :ivar definition: JSON representation of flow definition. + :ivar status: + :ivar revision: The latest revision number of the Flow's definition. + :ivar commit_message: Description of change made in the revision. + :ivar valid: Boolean if the flow definition is valid. + :ivar errors: List of error in the flow definition. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + sid: str, + revision: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.definition: Optional[Dict[str, object]] = payload.get("definition") + self.status: Optional["FlowRevisionInstance.Status"] = payload.get("status") + self.revision: Optional[int] = deserialize.integer(payload.get("revision")) + self.commit_message: Optional[str] = payload.get("commit_message") + self.valid: Optional[bool] = payload.get("valid") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid, + "revision": revision or self.revision, + } + self._context: Optional[FlowRevisionContext] = None + + @property + def _proxy(self) -> "FlowRevisionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FlowRevisionContext for this FlowRevisionInstance + """ + if self._context is None: + self._context = FlowRevisionContext( + self._version, + sid=self._solution["sid"], + revision=self._solution["revision"], + ) + return self._context + + def fetch(self) -> "FlowRevisionInstance": + """ + Fetch the FlowRevisionInstance + + + :returns: The fetched FlowRevisionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FlowRevisionInstance": + """ + Asynchronous coroutine to fetch the FlowRevisionInstance + + + :returns: The fetched FlowRevisionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V2.FlowRevisionInstance {}>".format(context) + + +class FlowRevisionContext(InstanceContext): + + def __init__(self, version: Version, sid: str, revision: str): + """ + Initialize the FlowRevisionContext + + :param version: Version that contains the resource + :param sid: The SID of the Flow resource to fetch. + :param revision: Specific Revision number or can be `LatestPublished` and `LatestRevision`. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + "revision": revision, + } + self._uri = "/Flows/{sid}/Revisions/{revision}".format(**self._solution) + + def fetch(self) -> FlowRevisionInstance: + """ + Fetch the FlowRevisionInstance + + + :returns: The fetched FlowRevisionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FlowRevisionInstance( + self._version, + payload, + sid=self._solution["sid"], + revision=self._solution["revision"], + ) + + async def fetch_async(self) -> FlowRevisionInstance: + """ + Asynchronous coroutine to fetch the FlowRevisionInstance + + + :returns: The fetched FlowRevisionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FlowRevisionInstance( + self._version, + payload, + sid=self._solution["sid"], + revision=self._solution["revision"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V2.FlowRevisionContext {}>".format(context) + + +class FlowRevisionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FlowRevisionInstance: + """ + Build an instance of FlowRevisionInstance + + :param payload: Payload response from the API + """ + return FlowRevisionInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V2.FlowRevisionPage>" + + +class FlowRevisionList(ListResource): + + def __init__(self, version: Version, sid: str): + """ + Initialize the FlowRevisionList + + :param version: Version that contains the resource + :param sid: The SID of the Flow resource to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Flows/{sid}/Revisions".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FlowRevisionInstance]: + """ + Streams FlowRevisionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FlowRevisionInstance]: + """ + Asynchronously streams FlowRevisionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlowRevisionInstance]: + """ + Lists FlowRevisionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FlowRevisionInstance]: + """ + Asynchronously lists FlowRevisionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FlowRevisionPage: + """ + Retrieve a single page of FlowRevisionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FlowRevisionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlowRevisionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FlowRevisionPage: + """ + Asynchronously retrieve a single page of FlowRevisionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FlowRevisionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FlowRevisionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> FlowRevisionPage: + """ + Retrieve a specific page of FlowRevisionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FlowRevisionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FlowRevisionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> FlowRevisionPage: + """ + Asynchronously retrieve a specific page of FlowRevisionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FlowRevisionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FlowRevisionPage(self._version, response, self._solution) + + def get(self, revision: str) -> FlowRevisionContext: + """ + Constructs a FlowRevisionContext + + :param revision: Specific Revision number or can be `LatestPublished` and `LatestRevision`. + """ + return FlowRevisionContext( + self._version, sid=self._solution["sid"], revision=revision + ) + + def __call__(self, revision: str) -> FlowRevisionContext: + """ + Constructs a FlowRevisionContext + + :param revision: Specific Revision number or can be `LatestPublished` and `LatestRevision`. + """ + return FlowRevisionContext( + self._version, sid=self._solution["sid"], revision=revision + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V2.FlowRevisionList>" diff --git a/twilio/rest/studio/v2/flow/flow_test_user.py b/twilio/rest/studio/v2/flow/flow_test_user.py new file mode 100644 index 0000000000..cff41cd7e2 --- /dev/null +++ b/twilio/rest/studio/v2/flow/flow_test_user.py @@ -0,0 +1,267 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class FlowTestUserInstance(InstanceResource): + """ + :ivar sid: Unique identifier of the flow. + :ivar test_users: List of test user identities that can test draft versions of the flow. + :ivar url: The URL of this resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.test_users: Optional[List[str]] = payload.get("test_users") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid, + } + self._context: Optional[FlowTestUserContext] = None + + @property + def _proxy(self) -> "FlowTestUserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FlowTestUserContext for this FlowTestUserInstance + """ + if self._context is None: + self._context = FlowTestUserContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "FlowTestUserInstance": + """ + Fetch the FlowTestUserInstance + + + :returns: The fetched FlowTestUserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FlowTestUserInstance": + """ + Asynchronous coroutine to fetch the FlowTestUserInstance + + + :returns: The fetched FlowTestUserInstance + """ + return await self._proxy.fetch_async() + + def update(self, test_users: List[str]) -> "FlowTestUserInstance": + """ + Update the FlowTestUserInstance + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: The updated FlowTestUserInstance + """ + return self._proxy.update( + test_users=test_users, + ) + + async def update_async(self, test_users: List[str]) -> "FlowTestUserInstance": + """ + Asynchronous coroutine to update the FlowTestUserInstance + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: The updated FlowTestUserInstance + """ + return await self._proxy.update_async( + test_users=test_users, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V2.FlowTestUserInstance {}>".format(context) + + +class FlowTestUserContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the FlowTestUserContext + + :param version: Version that contains the resource + :param sid: Unique identifier of the flow. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Flows/{sid}/TestUsers".format(**self._solution) + + def fetch(self) -> FlowTestUserInstance: + """ + Fetch the FlowTestUserInstance + + + :returns: The fetched FlowTestUserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FlowTestUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> FlowTestUserInstance: + """ + Asynchronous coroutine to fetch the FlowTestUserInstance + + + :returns: The fetched FlowTestUserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FlowTestUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update(self, test_users: List[str]) -> FlowTestUserInstance: + """ + Update the FlowTestUserInstance + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: The updated FlowTestUserInstance + """ + + data = values.of( + { + "TestUsers": serialize.map(test_users, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlowTestUserInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async(self, test_users: List[str]) -> FlowTestUserInstance: + """ + Asynchronous coroutine to update the FlowTestUserInstance + + :param test_users: List of test user identities that can test draft versions of the flow. + + :returns: The updated FlowTestUserInstance + """ + + data = values.of( + { + "TestUsers": serialize.map(test_users, lambda e: e), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlowTestUserInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Studio.V2.FlowTestUserContext {}>".format(context) + + +class FlowTestUserList(ListResource): + + def __init__(self, version: Version, sid: str): + """ + Initialize the FlowTestUserList + + :param version: Version that contains the resource + :param sid: Unique identifier of the flow. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + + def get(self) -> FlowTestUserContext: + """ + Constructs a FlowTestUserContext + + """ + return FlowTestUserContext(self._version, sid=self._solution["sid"]) + + def __call__(self) -> FlowTestUserContext: + """ + Constructs a FlowTestUserContext + + """ + return FlowTestUserContext(self._version, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V2.FlowTestUserList>" diff --git a/twilio/rest/studio/v2/flow_validate.py b/twilio/rest/studio/v2/flow_validate.py new file mode 100644 index 0000000000..5f8b308547 --- /dev/null +++ b/twilio/rest/studio/v2/flow_validate.py @@ -0,0 +1,143 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Studio + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class FlowValidateInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PUBLISHED = "published" + + """ + :ivar valid: Boolean if the flow definition is valid. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.valid: Optional[bool] = payload.get("valid") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Studio.V2.FlowValidateInstance>" + + +class FlowValidateList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the FlowValidateList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Flows/Validate" + + def update( + self, + friendly_name: str, + status: "FlowValidateInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> FlowValidateInstance: + """ + Update the FlowValidateInstance + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: The created FlowValidateInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "Definition": serialize.object(definition), + "CommitMessage": commit_message, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlowValidateInstance(self._version, payload) + + async def update_async( + self, + friendly_name: str, + status: "FlowValidateInstance.Status", + definition: object, + commit_message: Union[str, object] = values.unset, + ) -> FlowValidateInstance: + """ + Asynchronously update the FlowValidateInstance + + :param friendly_name: The string that you assigned to describe the Flow. + :param status: + :param definition: JSON representation of flow definition. + :param commit_message: Description of change made in the revision. + + :returns: The created FlowValidateInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "Definition": serialize.object(definition), + "CommitMessage": commit_message, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FlowValidateInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Studio.V2.FlowValidateList>" diff --git a/twilio/rest/supersim/SupersimBase.py b/twilio/rest/supersim/SupersimBase.py new file mode 100644 index 0000000000..dd73d12223 --- /dev/null +++ b/twilio/rest/supersim/SupersimBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.supersim.v1 import V1 + + +class SupersimBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Supersim Domain + + :returns: Domain for Supersim + """ + super().__init__(twilio, "https://supersim.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Supersim + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Supersim>" diff --git a/twilio/rest/supersim/__init__.py b/twilio/rest/supersim/__init__.py new file mode 100644 index 0000000000..98928dad6a --- /dev/null +++ b/twilio/rest/supersim/__init__.py @@ -0,0 +1,93 @@ +from warnings import warn + +from twilio.rest.supersim.SupersimBase import SupersimBase +from twilio.rest.supersim.v1.esim_profile import EsimProfileList +from twilio.rest.supersim.v1.fleet import FleetList +from twilio.rest.supersim.v1.ip_command import IpCommandList +from twilio.rest.supersim.v1.network import NetworkList +from twilio.rest.supersim.v1.network_access_profile import NetworkAccessProfileList +from twilio.rest.supersim.v1.settings_update import SettingsUpdateList +from twilio.rest.supersim.v1.sim import SimList +from twilio.rest.supersim.v1.sms_command import SmsCommandList +from twilio.rest.supersim.v1.usage_record import UsageRecordList + + +class Supersim(SupersimBase): + @property + def esim_profiles(self) -> EsimProfileList: + warn( + "esim_profiles is deprecated. Use v1.esim_profiles instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.esim_profiles + + @property + def fleets(self) -> FleetList: + warn( + "fleets is deprecated. Use v1.fleets instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.fleets + + @property + def ip_commands(self) -> IpCommandList: + warn( + "ip_commands is deprecated. Use v1.ip_commands instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.ip_commands + + @property + def networks(self) -> NetworkList: + warn( + "networks is deprecated. Use v1.networks instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.networks + + @property + def network_access_profiles(self) -> NetworkAccessProfileList: + warn( + "network_access_profiles is deprecated. Use v1.network_access_profiles instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.network_access_profiles + + @property + def settings_updates(self) -> SettingsUpdateList: + warn( + "settings_updates is deprecated. Use v1.settings_updates instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.settings_updates + + @property + def sims(self) -> SimList: + warn( + "sims is deprecated. Use v1.sims instead.", DeprecationWarning, stacklevel=2 + ) + return self.v1.sims + + @property + def sms_commands(self) -> SmsCommandList: + warn( + "sms_commands is deprecated. Use v1.sms_commands instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.sms_commands + + @property + def usage_records(self) -> UsageRecordList: + warn( + "usage_records is deprecated. Use v1.usage_records instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.usage_records diff --git a/twilio/rest/supersim/v1/__init__.py b/twilio/rest/supersim/v1/__init__.py new file mode 100644 index 0000000000..2336da2616 --- /dev/null +++ b/twilio/rest/supersim/v1/__init__.py @@ -0,0 +1,107 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.supersim.v1.esim_profile import EsimProfileList +from twilio.rest.supersim.v1.fleet import FleetList +from twilio.rest.supersim.v1.ip_command import IpCommandList +from twilio.rest.supersim.v1.network import NetworkList +from twilio.rest.supersim.v1.network_access_profile import NetworkAccessProfileList +from twilio.rest.supersim.v1.settings_update import SettingsUpdateList +from twilio.rest.supersim.v1.sim import SimList +from twilio.rest.supersim.v1.sms_command import SmsCommandList +from twilio.rest.supersim.v1.usage_record import UsageRecordList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Supersim + + :param domain: The Twilio.supersim domain + """ + super().__init__(domain, "v1") + self._esim_profiles: Optional[EsimProfileList] = None + self._fleets: Optional[FleetList] = None + self._ip_commands: Optional[IpCommandList] = None + self._networks: Optional[NetworkList] = None + self._network_access_profiles: Optional[NetworkAccessProfileList] = None + self._settings_updates: Optional[SettingsUpdateList] = None + self._sims: Optional[SimList] = None + self._sms_commands: Optional[SmsCommandList] = None + self._usage_records: Optional[UsageRecordList] = None + + @property + def esim_profiles(self) -> EsimProfileList: + if self._esim_profiles is None: + self._esim_profiles = EsimProfileList(self) + return self._esim_profiles + + @property + def fleets(self) -> FleetList: + if self._fleets is None: + self._fleets = FleetList(self) + return self._fleets + + @property + def ip_commands(self) -> IpCommandList: + if self._ip_commands is None: + self._ip_commands = IpCommandList(self) + return self._ip_commands + + @property + def networks(self) -> NetworkList: + if self._networks is None: + self._networks = NetworkList(self) + return self._networks + + @property + def network_access_profiles(self) -> NetworkAccessProfileList: + if self._network_access_profiles is None: + self._network_access_profiles = NetworkAccessProfileList(self) + return self._network_access_profiles + + @property + def settings_updates(self) -> SettingsUpdateList: + if self._settings_updates is None: + self._settings_updates = SettingsUpdateList(self) + return self._settings_updates + + @property + def sims(self) -> SimList: + if self._sims is None: + self._sims = SimList(self) + return self._sims + + @property + def sms_commands(self) -> SmsCommandList: + if self._sms_commands is None: + self._sms_commands = SmsCommandList(self) + return self._sms_commands + + @property + def usage_records(self) -> UsageRecordList: + if self._usage_records is None: + self._usage_records = UsageRecordList(self) + return self._usage_records + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1>" diff --git a/twilio/rest/supersim/v1/esim_profile.py b/twilio/rest/supersim/v1/esim_profile.py new file mode 100644 index 0000000000..d12bb9b73f --- /dev/null +++ b/twilio/rest/supersim/v1/esim_profile.py @@ -0,0 +1,568 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EsimProfileInstance(InstanceResource): + + class Status(object): + NEW = "new" + RESERVING = "reserving" + AVAILABLE = "available" + DOWNLOADED = "downloaded" + INSTALLED = "installed" + FAILED = "failed" + + """ + :ivar sid: The unique string that we created to identify the eSIM Profile resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the eSIM Profile resource belongs. + :ivar iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with the Sim resource. + :ivar sim_sid: The SID of the [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource that this eSIM Profile controls. + :ivar status: + :ivar eid: Identifier of the eUICC that can claim the eSIM Profile. + :ivar smdp_plus_address: Address of the SM-DP+ server from which the Profile will be downloaded. The URL will appear once the eSIM Profile reaches the status `available`. + :ivar matching_id: Unique identifier of the eSIM profile that can be used to identify and download the eSIM profile from the SM-DP+ server. Populated if `generate_matching_id` is set to `true` when creating the eSIM profile reservation. + :ivar activation_code: Combined machine-readable activation code for acquiring an eSIM Profile with the Activation Code download method. Can be used in a QR code to download an eSIM profile. + :ivar error_code: Code indicating the failure if the download of the SIM Profile failed and the eSIM Profile is in `failed` state. + :ivar error_message: Error message describing the failure if the download of the SIM Profile failed and the eSIM Profile is in `failed` state. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the eSIM Profile resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.iccid: Optional[str] = payload.get("iccid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.status: Optional["EsimProfileInstance.Status"] = payload.get("status") + self.eid: Optional[str] = payload.get("eid") + self.smdp_plus_address: Optional[str] = payload.get("smdp_plus_address") + self.matching_id: Optional[str] = payload.get("matching_id") + self.activation_code: Optional[str] = payload.get("activation_code") + self.error_code: Optional[str] = payload.get("error_code") + self.error_message: Optional[str] = payload.get("error_message") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[EsimProfileContext] = None + + @property + def _proxy(self) -> "EsimProfileContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EsimProfileContext for this EsimProfileInstance + """ + if self._context is None: + self._context = EsimProfileContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "EsimProfileInstance": + """ + Fetch the EsimProfileInstance + + + :returns: The fetched EsimProfileInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EsimProfileInstance": + """ + Asynchronous coroutine to fetch the EsimProfileInstance + + + :returns: The fetched EsimProfileInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Supersim.V1.EsimProfileInstance {}>".format(context) + + +class EsimProfileContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the EsimProfileContext + + :param version: Version that contains the resource + :param sid: The SID of the eSIM Profile resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/ESimProfiles/{sid}".format(**self._solution) + + def fetch(self) -> EsimProfileInstance: + """ + Fetch the EsimProfileInstance + + + :returns: The fetched EsimProfileInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EsimProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EsimProfileInstance: + """ + Asynchronous coroutine to fetch the EsimProfileInstance + + + :returns: The fetched EsimProfileInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EsimProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Supersim.V1.EsimProfileContext {}>".format(context) + + +class EsimProfilePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EsimProfileInstance: + """ + Build an instance of EsimProfileInstance + + :param payload: Payload response from the API + """ + return EsimProfileInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.EsimProfilePage>" + + +class EsimProfileList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the EsimProfileList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ESimProfiles" + + def create( + self, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + generate_matching_id: Union[bool, object] = values.unset, + eid: Union[str, object] = values.unset, + ) -> EsimProfileInstance: + """ + Create the EsimProfileInstance + + :param callback_url: The URL we should call using the `callback_method` when the status of the eSIM Profile changes. At this stage of the eSIM Profile pilot, the a request to the URL will only be called when the ESimProfile resource changes from `reserving` to `available`. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param generate_matching_id: When set to `true`, a value for `Eid` does not need to be provided. Instead, when the eSIM profile is reserved, a matching ID will be generated and returned via the `matching_id` property. This identifies the specific eSIM profile that can be used by any capable device to claim and download the profile. + :param eid: Identifier of the eUICC that will claim the eSIM Profile. + + :returns: The created EsimProfileInstance + """ + + data = values.of( + { + "CallbackUrl": callback_url, + "CallbackMethod": callback_method, + "GenerateMatchingId": serialize.boolean_to_string(generate_matching_id), + "Eid": eid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EsimProfileInstance(self._version, payload) + + async def create_async( + self, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + generate_matching_id: Union[bool, object] = values.unset, + eid: Union[str, object] = values.unset, + ) -> EsimProfileInstance: + """ + Asynchronously create the EsimProfileInstance + + :param callback_url: The URL we should call using the `callback_method` when the status of the eSIM Profile changes. At this stage of the eSIM Profile pilot, the a request to the URL will only be called when the ESimProfile resource changes from `reserving` to `available`. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param generate_matching_id: When set to `true`, a value for `Eid` does not need to be provided. Instead, when the eSIM profile is reserved, a matching ID will be generated and returned via the `matching_id` property. This identifies the specific eSIM profile that can be used by any capable device to claim and download the profile. + :param eid: Identifier of the eUICC that will claim the eSIM Profile. + + :returns: The created EsimProfileInstance + """ + + data = values.of( + { + "CallbackUrl": callback_url, + "CallbackMethod": callback_method, + "GenerateMatchingId": serialize.boolean_to_string(generate_matching_id), + "Eid": eid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EsimProfileInstance(self._version, payload) + + def stream( + self, + eid: Union[str, object] = values.unset, + sim_sid: Union[str, object] = values.unset, + status: Union["EsimProfileInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EsimProfileInstance]: + """ + Streams EsimProfileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str eid: List the eSIM Profiles that have been associated with an EId. + :param str sim_sid: Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :param "EsimProfileInstance.Status" status: List the eSIM Profiles that are in a given status. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + eid=eid, sim_sid=sim_sid, status=status, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + eid: Union[str, object] = values.unset, + sim_sid: Union[str, object] = values.unset, + status: Union["EsimProfileInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EsimProfileInstance]: + """ + Asynchronously streams EsimProfileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str eid: List the eSIM Profiles that have been associated with an EId. + :param str sim_sid: Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :param "EsimProfileInstance.Status" status: List the eSIM Profiles that are in a given status. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + eid=eid, sim_sid=sim_sid, status=status, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + eid: Union[str, object] = values.unset, + sim_sid: Union[str, object] = values.unset, + status: Union["EsimProfileInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EsimProfileInstance]: + """ + Lists EsimProfileInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str eid: List the eSIM Profiles that have been associated with an EId. + :param str sim_sid: Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :param "EsimProfileInstance.Status" status: List the eSIM Profiles that are in a given status. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + eid=eid, + sim_sid=sim_sid, + status=status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + eid: Union[str, object] = values.unset, + sim_sid: Union[str, object] = values.unset, + status: Union["EsimProfileInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EsimProfileInstance]: + """ + Asynchronously lists EsimProfileInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str eid: List the eSIM Profiles that have been associated with an EId. + :param str sim_sid: Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :param "EsimProfileInstance.Status" status: List the eSIM Profiles that are in a given status. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + eid=eid, + sim_sid=sim_sid, + status=status, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + eid: Union[str, object] = values.unset, + sim_sid: Union[str, object] = values.unset, + status: Union["EsimProfileInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EsimProfilePage: + """ + Retrieve a single page of EsimProfileInstance records from the API. + Request is executed immediately + + :param eid: List the eSIM Profiles that have been associated with an EId. + :param sim_sid: Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :param status: List the eSIM Profiles that are in a given status. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EsimProfileInstance + """ + data = values.of( + { + "Eid": eid, + "SimSid": sim_sid, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EsimProfilePage(self._version, response) + + async def page_async( + self, + eid: Union[str, object] = values.unset, + sim_sid: Union[str, object] = values.unset, + status: Union["EsimProfileInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EsimProfilePage: + """ + Asynchronously retrieve a single page of EsimProfileInstance records from the API. + Request is executed immediately + + :param eid: List the eSIM Profiles that have been associated with an EId. + :param sim_sid: Find the eSIM Profile resource related to a [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :param status: List the eSIM Profiles that are in a given status. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EsimProfileInstance + """ + data = values.of( + { + "Eid": eid, + "SimSid": sim_sid, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EsimProfilePage(self._version, response) + + def get_page(self, target_url: str) -> EsimProfilePage: + """ + Retrieve a specific page of EsimProfileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EsimProfileInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EsimProfilePage(self._version, response) + + async def get_page_async(self, target_url: str) -> EsimProfilePage: + """ + Asynchronously retrieve a specific page of EsimProfileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EsimProfileInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EsimProfilePage(self._version, response) + + def get(self, sid: str) -> EsimProfileContext: + """ + Constructs a EsimProfileContext + + :param sid: The SID of the eSIM Profile resource to fetch. + """ + return EsimProfileContext(self._version, sid=sid) + + def __call__(self, sid: str) -> EsimProfileContext: + """ + Constructs a EsimProfileContext + + :param sid: The SID of the eSIM Profile resource to fetch. + """ + return EsimProfileContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.EsimProfileList>" diff --git a/twilio/rest/supersim/v1/fleet.py b/twilio/rest/supersim/v1/fleet.py new file mode 100644 index 0000000000..3ea067cff2 --- /dev/null +++ b/twilio/rest/supersim/v1/fleet.py @@ -0,0 +1,727 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class FleetInstance(InstanceResource): + + class DataMetering(object): + PAYG = "payg" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Fleet resource. + :ivar sid: The unique string that we created to identify the Fleet resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Fleet resource. + :ivar data_enabled: Defines whether SIMs in the Fleet are capable of using 2G/3G/4G/LTE/CAT-M data connectivity. Defaults to `true`. + :ivar data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 250MB. + :ivar data_metering: + :ivar sms_commands_enabled: Defines whether SIMs in the Fleet are capable of sending and receiving machine-to-machine SMS via Commands. Defaults to `false`. + :ivar sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :ivar sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :ivar network_access_profile_sid: The SID of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :ivar ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :ivar ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.data_enabled: Optional[bool] = payload.get("data_enabled") + self.data_limit: Optional[int] = deserialize.integer(payload.get("data_limit")) + self.data_metering: Optional["FleetInstance.DataMetering"] = payload.get( + "data_metering" + ) + self.sms_commands_enabled: Optional[bool] = payload.get("sms_commands_enabled") + self.sms_commands_url: Optional[str] = payload.get("sms_commands_url") + self.sms_commands_method: Optional[str] = payload.get("sms_commands_method") + self.network_access_profile_sid: Optional[str] = payload.get( + "network_access_profile_sid" + ) + self.ip_commands_url: Optional[str] = payload.get("ip_commands_url") + self.ip_commands_method: Optional[str] = payload.get("ip_commands_method") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[FleetContext] = None + + @property + def _proxy(self) -> "FleetContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FleetContext for this FleetInstance + """ + if self._context is None: + self._context = FleetContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "FleetInstance": + """ + Fetch the FleetInstance + + + :returns: The fetched FleetInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FleetInstance": + """ + Asynchronous coroutine to fetch the FleetInstance + + + :returns: The fetched FleetInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + unique_name: Union[str, object] = values.unset, + network_access_profile: Union[str, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ) -> "FleetInstance": + """ + Update the FleetInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + + :returns: The updated FleetInstance + """ + return self._proxy.update( + unique_name=unique_name, + network_access_profile=network_access_profile, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + data_limit=data_limit, + ) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + network_access_profile: Union[str, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ) -> "FleetInstance": + """ + Asynchronous coroutine to update the FleetInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + + :returns: The updated FleetInstance + """ + return await self._proxy.update_async( + unique_name=unique_name, + network_access_profile=network_access_profile, + ip_commands_url=ip_commands_url, + ip_commands_method=ip_commands_method, + sms_commands_url=sms_commands_url, + sms_commands_method=sms_commands_method, + data_limit=data_limit, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Supersim.V1.FleetInstance {}>".format(context) + + +class FleetContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the FleetContext + + :param version: Version that contains the resource + :param sid: The SID of the Fleet resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Fleets/{sid}".format(**self._solution) + + def fetch(self) -> FleetInstance: + """ + Fetch the FleetInstance + + + :returns: The fetched FleetInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FleetInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> FleetInstance: + """ + Asynchronous coroutine to fetch the FleetInstance + + + :returns: The fetched FleetInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FleetInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + unique_name: Union[str, object] = values.unset, + network_access_profile: Union[str, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ) -> FleetInstance: + """ + Update the FleetInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + + :returns: The updated FleetInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "NetworkAccessProfile": network_access_profile, + "IpCommandsUrl": ip_commands_url, + "IpCommandsMethod": ip_commands_method, + "SmsCommandsUrl": sms_commands_url, + "SmsCommandsMethod": sms_commands_method, + "DataLimit": data_limit, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FleetInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + network_access_profile: Union[str, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ) -> FleetInstance: + """ + Asynchronous coroutine to update the FleetInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + + :returns: The updated FleetInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "NetworkAccessProfile": network_access_profile, + "IpCommandsUrl": ip_commands_url, + "IpCommandsMethod": ip_commands_method, + "SmsCommandsUrl": sms_commands_url, + "SmsCommandsMethod": sms_commands_method, + "DataLimit": data_limit, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FleetInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Supersim.V1.FleetContext {}>".format(context) + + +class FleetPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FleetInstance: + """ + Build an instance of FleetInstance + + :param payload: Payload response from the API + """ + return FleetInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.FleetPage>" + + +class FleetList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the FleetList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Fleets" + + def create( + self, + network_access_profile: str, + unique_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_enabled: Union[bool, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + ) -> FleetInstance: + """ + Create the FleetInstance + + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param data_enabled: Defines whether SIMs in the Fleet are capable of using 2G/3G/4G/LTE/CAT-M data connectivity. Defaults to `true`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_enabled: Defines whether SIMs in the Fleet are capable of sending and receiving machine-to-machine SMS via Commands. Defaults to `true`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + + :returns: The created FleetInstance + """ + + data = values.of( + { + "NetworkAccessProfile": network_access_profile, + "UniqueName": unique_name, + "DataEnabled": serialize.boolean_to_string(data_enabled), + "DataLimit": data_limit, + "IpCommandsUrl": ip_commands_url, + "IpCommandsMethod": ip_commands_method, + "SmsCommandsEnabled": serialize.boolean_to_string(sms_commands_enabled), + "SmsCommandsUrl": sms_commands_url, + "SmsCommandsMethod": sms_commands_method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FleetInstance(self._version, payload) + + async def create_async( + self, + network_access_profile: str, + unique_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + ip_commands_url: Union[str, object] = values.unset, + ip_commands_method: Union[str, object] = values.unset, + sms_commands_enabled: Union[bool, object] = values.unset, + sms_commands_url: Union[str, object] = values.unset, + sms_commands_method: Union[str, object] = values.unset, + ) -> FleetInstance: + """ + Asynchronously create the FleetInstance + + :param network_access_profile: The SID or unique name of the Network Access Profile that will control which cellular networks the Fleet's SIMs can connect to. + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param data_enabled: Defines whether SIMs in the Fleet are capable of using 2G/3G/4G/LTE/CAT-M data connectivity. Defaults to `true`. + :param data_limit: The total data usage (download and upload combined) in Megabytes that each Super SIM assigned to the Fleet can consume during a billing period (normally one month). Value must be between 1MB (1) and 2TB (2,000,000). Defaults to 1GB (1,000). + :param ip_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an IP Command from your device to a special IP address. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param ip_commands_method: A string representing the HTTP method to use when making a request to `ip_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + :param sms_commands_enabled: Defines whether SIMs in the Fleet are capable of sending and receiving machine-to-machine SMS via Commands. Defaults to `true`. + :param sms_commands_url: The URL that will receive a webhook when a Super SIM in the Fleet is used to send an SMS from your device to the SMS Commands number. Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :param sms_commands_method: A string representing the HTTP method to use when making a request to `sms_commands_url`. Can be one of `POST` or `GET`. Defaults to `POST`. + + :returns: The created FleetInstance + """ + + data = values.of( + { + "NetworkAccessProfile": network_access_profile, + "UniqueName": unique_name, + "DataEnabled": serialize.boolean_to_string(data_enabled), + "DataLimit": data_limit, + "IpCommandsUrl": ip_commands_url, + "IpCommandsMethod": ip_commands_method, + "SmsCommandsEnabled": serialize.boolean_to_string(sms_commands_enabled), + "SmsCommandsUrl": sms_commands_url, + "SmsCommandsMethod": sms_commands_method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FleetInstance(self._version, payload) + + def stream( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FleetInstance]: + """ + Streams FleetInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + network_access_profile=network_access_profile, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FleetInstance]: + """ + Asynchronously streams FleetInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + network_access_profile=network_access_profile, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FleetInstance]: + """ + Lists FleetInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + network_access_profile=network_access_profile, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + network_access_profile: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FleetInstance]: + """ + Asynchronously lists FleetInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + network_access_profile=network_access_profile, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + network_access_profile: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FleetPage: + """ + Retrieve a single page of FleetInstance records from the API. + Request is executed immediately + + :param network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FleetInstance + """ + data = values.of( + { + "NetworkAccessProfile": network_access_profile, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FleetPage(self._version, response) + + async def page_async( + self, + network_access_profile: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FleetPage: + """ + Asynchronously retrieve a single page of FleetInstance records from the API. + Request is executed immediately + + :param network_access_profile: The SID or unique name of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FleetInstance + """ + data = values.of( + { + "NetworkAccessProfile": network_access_profile, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FleetPage(self._version, response) + + def get_page(self, target_url: str) -> FleetPage: + """ + Retrieve a specific page of FleetInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FleetInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FleetPage(self._version, response) + + async def get_page_async(self, target_url: str) -> FleetPage: + """ + Asynchronously retrieve a specific page of FleetInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FleetInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FleetPage(self._version, response) + + def get(self, sid: str) -> FleetContext: + """ + Constructs a FleetContext + + :param sid: The SID of the Fleet resource to update. + """ + return FleetContext(self._version, sid=sid) + + def __call__(self, sid: str) -> FleetContext: + """ + Constructs a FleetContext + + :param sid: The SID of the Fleet resource to update. + """ + return FleetContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.FleetList>" diff --git a/twilio/rest/supersim/v1/ip_command.py b/twilio/rest/supersim/v1/ip_command.py new file mode 100644 index 0000000000..72bf78297f --- /dev/null +++ b/twilio/rest/supersim/v1/ip_command.py @@ -0,0 +1,614 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class IpCommandInstance(InstanceResource): + + class Direction(object): + TO_SIM = "to_sim" + FROM_SIM = "from_sim" + + class PayloadType(object): + TEXT = "text" + BINARY = "binary" + + class Status(object): + QUEUED = "queued" + SENT = "sent" + RECEIVED = "received" + FAILED = "failed" + + """ + :ivar sid: The unique string that we created to identify the IP Command resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IP Command resource. + :ivar sim_sid: The SID of the [Super SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) that this IP Command was sent to or from. + :ivar sim_iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) of the [Super SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) that this IP Command was sent to or from. + :ivar status: + :ivar direction: + :ivar device_ip: The IP address of the device that the IP Command was sent to or received from. For an IP Command sent to a Super SIM, `device_ip` starts out as `null`, and once the IP Command is “sent”, the `device_ip` will be filled out. An IP Command sent from a Super SIM have its `device_ip` always set. + :ivar device_port: For an IP Command sent to a Super SIM, it would be the destination port of the IP message. For an IP Command sent from a Super SIM, it would be the source port of the IP message. + :ivar payload_type: + :ivar payload: The payload that is carried in the IP/UDP message. The payload can be encoded in either text or binary format. For text payload, UTF-8 encoding must be used. For an IP Command sent to a Super SIM, the payload is appended to the IP/UDP message “as is”. The payload should not exceed 1300 bytes. For an IP Command sent from a Super SIM, the payload from the received IP/UDP message is extracted and sent in binary encoding. For an IP Command sent from a Super SIM, the payload should not exceed 1300 bytes. If it is larger than 1300 bytes, there might be fragmentation on the upstream and the message may appear truncated. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the IP Command resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.sim_iccid: Optional[str] = payload.get("sim_iccid") + self.status: Optional["IpCommandInstance.Status"] = payload.get("status") + self.direction: Optional["IpCommandInstance.Direction"] = payload.get( + "direction" + ) + self.device_ip: Optional[str] = payload.get("device_ip") + self.device_port: Optional[int] = deserialize.integer( + payload.get("device_port") + ) + self.payload_type: Optional["IpCommandInstance.PayloadType"] = payload.get( + "payload_type" + ) + self.payload: Optional[str] = payload.get("payload") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[IpCommandContext] = None + + @property + def _proxy(self) -> "IpCommandContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: IpCommandContext for this IpCommandInstance + """ + if self._context is None: + self._context = IpCommandContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "IpCommandInstance": + """ + Fetch the IpCommandInstance + + + :returns: The fetched IpCommandInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "IpCommandInstance": + """ + Asynchronous coroutine to fetch the IpCommandInstance + + + :returns: The fetched IpCommandInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Supersim.V1.IpCommandInstance {}>".format(context) + + +class IpCommandContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the IpCommandContext + + :param version: Version that contains the resource + :param sid: The SID of the IP Command resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/IpCommands/{sid}".format(**self._solution) + + def fetch(self) -> IpCommandInstance: + """ + Fetch the IpCommandInstance + + + :returns: The fetched IpCommandInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return IpCommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> IpCommandInstance: + """ + Asynchronous coroutine to fetch the IpCommandInstance + + + :returns: The fetched IpCommandInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return IpCommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Supersim.V1.IpCommandContext {}>".format(context) + + +class IpCommandPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> IpCommandInstance: + """ + Build an instance of IpCommandInstance + + :param payload: Payload response from the API + """ + return IpCommandInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.IpCommandPage>" + + +class IpCommandList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the IpCommandList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/IpCommands" + + def create( + self, + sim: str, + payload: str, + device_port: int, + payload_type: Union["IpCommandInstance.PayloadType", object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + ) -> IpCommandInstance: + """ + Create the IpCommandInstance + + :param sim: The `sid` or `unique_name` of the [Super SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the IP Command to. + :param payload: The data that will be sent to the device. The payload cannot exceed 1300 bytes. If the PayloadType is set to text, the payload is encoded in UTF-8. If PayloadType is set to binary, the payload is encoded in Base64. + :param device_port: The device port to which the IP Command will be sent. + :param payload_type: + :param callback_url: The URL we should call using the `callback_method` after we have sent the IP Command. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be `GET` or `POST`, and the default is `POST`. + + :returns: The created IpCommandInstance + """ + + data = values.of( + { + "Sim": sim, + "Payload": payload, + "DevicePort": device_port, + "PayloadType": payload_type, + "CallbackUrl": callback_url, + "CallbackMethod": callback_method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpCommandInstance(self._version, payload) + + async def create_async( + self, + sim: str, + payload: str, + device_port: int, + payload_type: Union["IpCommandInstance.PayloadType", object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + ) -> IpCommandInstance: + """ + Asynchronously create the IpCommandInstance + + :param sim: The `sid` or `unique_name` of the [Super SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the IP Command to. + :param payload: The data that will be sent to the device. The payload cannot exceed 1300 bytes. If the PayloadType is set to text, the payload is encoded in UTF-8. If PayloadType is set to binary, the payload is encoded in Base64. + :param device_port: The device port to which the IP Command will be sent. + :param payload_type: + :param callback_url: The URL we should call using the `callback_method` after we have sent the IP Command. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be `GET` or `POST`, and the default is `POST`. + + :returns: The created IpCommandInstance + """ + + data = values.of( + { + "Sim": sim, + "Payload": payload, + "DevicePort": device_port, + "PayloadType": payload_type, + "CallbackUrl": callback_url, + "CallbackMethod": callback_method, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpCommandInstance(self._version, payload) + + def stream( + self, + sim: Union[str, object] = values.unset, + sim_iccid: Union[str, object] = values.unset, + status: Union["IpCommandInstance.Status", object] = values.unset, + direction: Union["IpCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[IpCommandInstance]: + """ + Streams IpCommandInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sim: The SID or unique name of the Sim resource that IP Command was sent to or from. + :param str sim_iccid: The ICCID of the Sim resource that IP Command was sent to or from. + :param "IpCommandInstance.Status" status: The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. + :param "IpCommandInstance.Direction" direction: The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + sim=sim, + sim_iccid=sim_iccid, + status=status, + direction=direction, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + sim: Union[str, object] = values.unset, + sim_iccid: Union[str, object] = values.unset, + status: Union["IpCommandInstance.Status", object] = values.unset, + direction: Union["IpCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpCommandInstance]: + """ + Asynchronously streams IpCommandInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sim: The SID or unique name of the Sim resource that IP Command was sent to or from. + :param str sim_iccid: The ICCID of the Sim resource that IP Command was sent to or from. + :param "IpCommandInstance.Status" status: The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. + :param "IpCommandInstance.Direction" direction: The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + sim=sim, + sim_iccid=sim_iccid, + status=status, + direction=direction, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + sim: Union[str, object] = values.unset, + sim_iccid: Union[str, object] = values.unset, + status: Union["IpCommandInstance.Status", object] = values.unset, + direction: Union["IpCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpCommandInstance]: + """ + Lists IpCommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: The SID or unique name of the Sim resource that IP Command was sent to or from. + :param str sim_iccid: The ICCID of the Sim resource that IP Command was sent to or from. + :param "IpCommandInstance.Status" status: The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. + :param "IpCommandInstance.Direction" direction: The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + sim=sim, + sim_iccid=sim_iccid, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + sim: Union[str, object] = values.unset, + sim_iccid: Union[str, object] = values.unset, + status: Union["IpCommandInstance.Status", object] = values.unset, + direction: Union["IpCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpCommandInstance]: + """ + Asynchronously lists IpCommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: The SID or unique name of the Sim resource that IP Command was sent to or from. + :param str sim_iccid: The ICCID of the Sim resource that IP Command was sent to or from. + :param "IpCommandInstance.Status" status: The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. + :param "IpCommandInstance.Direction" direction: The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + sim=sim, + sim_iccid=sim_iccid, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + sim: Union[str, object] = values.unset, + sim_iccid: Union[str, object] = values.unset, + status: Union["IpCommandInstance.Status", object] = values.unset, + direction: Union["IpCommandInstance.Direction", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpCommandPage: + """ + Retrieve a single page of IpCommandInstance records from the API. + Request is executed immediately + + :param sim: The SID or unique name of the Sim resource that IP Command was sent to or from. + :param sim_iccid: The ICCID of the Sim resource that IP Command was sent to or from. + :param status: The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. + :param direction: The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpCommandInstance + """ + data = values.of( + { + "Sim": sim, + "SimIccid": sim_iccid, + "Status": status, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpCommandPage(self._version, response) + + async def page_async( + self, + sim: Union[str, object] = values.unset, + sim_iccid: Union[str, object] = values.unset, + status: Union["IpCommandInstance.Status", object] = values.unset, + direction: Union["IpCommandInstance.Direction", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpCommandPage: + """ + Asynchronously retrieve a single page of IpCommandInstance records from the API. + Request is executed immediately + + :param sim: The SID or unique name of the Sim resource that IP Command was sent to or from. + :param sim_iccid: The ICCID of the Sim resource that IP Command was sent to or from. + :param status: The status of the IP Command. Can be: `queued`, `sent`, `received` or `failed`. See the [IP Command Status Values](https://www.twilio.com/docs/iot/supersim/api/ipcommand-resource#status-values) for a description of each. + :param direction: The direction of the IP Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpCommandInstance + """ + data = values.of( + { + "Sim": sim, + "SimIccid": sim_iccid, + "Status": status, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpCommandPage(self._version, response) + + def get_page(self, target_url: str) -> IpCommandPage: + """ + Retrieve a specific page of IpCommandInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpCommandInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return IpCommandPage(self._version, response) + + async def get_page_async(self, target_url: str) -> IpCommandPage: + """ + Asynchronously retrieve a specific page of IpCommandInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpCommandInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpCommandPage(self._version, response) + + def get(self, sid: str) -> IpCommandContext: + """ + Constructs a IpCommandContext + + :param sid: The SID of the IP Command resource to fetch. + """ + return IpCommandContext(self._version, sid=sid) + + def __call__(self, sid: str) -> IpCommandContext: + """ + Constructs a IpCommandContext + + :param sid: The SID of the IP Command resource to fetch. + """ + return IpCommandContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.IpCommandList>" diff --git a/twilio/rest/supersim/v1/network.py b/twilio/rest/supersim/v1/network.py new file mode 100644 index 0000000000..211068d075 --- /dev/null +++ b/twilio/rest/supersim/v1/network.py @@ -0,0 +1,460 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class NetworkInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Network resource. + :ivar friendly_name: A human readable identifier of this resource. + :ivar url: The absolute URL of the Network resource. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resource. + :ivar identifiers: Array of objects identifying the [MCC-MNCs](https://en.wikipedia.org/wiki/Mobile_country_code) that are included in the Network resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.url: Optional[str] = payload.get("url") + self.iso_country: Optional[str] = payload.get("iso_country") + self.identifiers: Optional[List[Dict[str, object]]] = payload.get("identifiers") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[NetworkContext] = None + + @property + def _proxy(self) -> "NetworkContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NetworkContext for this NetworkInstance + """ + if self._context is None: + self._context = NetworkContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "NetworkInstance": + """ + Fetch the NetworkInstance + + + :returns: The fetched NetworkInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "NetworkInstance": + """ + Asynchronous coroutine to fetch the NetworkInstance + + + :returns: The fetched NetworkInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Supersim.V1.NetworkInstance {}>".format(context) + + +class NetworkContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the NetworkContext + + :param version: Version that contains the resource + :param sid: The SID of the Network resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Networks/{sid}".format(**self._solution) + + def fetch(self) -> NetworkInstance: + """ + Fetch the NetworkInstance + + + :returns: The fetched NetworkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return NetworkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> NetworkInstance: + """ + Asynchronous coroutine to fetch the NetworkInstance + + + :returns: The fetched NetworkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return NetworkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Supersim.V1.NetworkContext {}>".format(context) + + +class NetworkPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> NetworkInstance: + """ + Build an instance of NetworkInstance + + :param payload: Payload response from the API + """ + return NetworkInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.NetworkPage>" + + +class NetworkList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the NetworkList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Networks" + + def stream( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[NetworkInstance]: + """ + Streams NetworkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param str mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param str mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + iso_country=iso_country, mcc=mcc, mnc=mnc, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[NetworkInstance]: + """ + Asynchronously streams NetworkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param str mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param str mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + iso_country=iso_country, mcc=mcc, mnc=mnc, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NetworkInstance]: + """ + Lists NetworkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param str mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param str mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + iso_country=iso_country, + mcc=mcc, + mnc=mnc, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NetworkInstance]: + """ + Asynchronously lists NetworkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param str mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param str mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + iso_country=iso_country, + mcc=mcc, + mnc=mnc, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NetworkPage: + """ + Retrieve a single page of NetworkInstance records from the API. + Request is executed immediately + + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NetworkInstance + """ + data = values.of( + { + "IsoCountry": iso_country, + "Mcc": mcc, + "Mnc": mnc, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NetworkPage(self._version, response) + + async def page_async( + self, + iso_country: Union[str, object] = values.unset, + mcc: Union[str, object] = values.unset, + mnc: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NetworkPage: + """ + Asynchronously retrieve a single page of NetworkInstance records from the API. + Request is executed immediately + + :param iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resources to read. + :param mcc: The 'mobile country code' of a country. Network resources with this `mcc` in their `identifiers` will be read. + :param mnc: The 'mobile network code' of a mobile operator network. Network resources with this `mnc` in their `identifiers` will be read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NetworkInstance + """ + data = values.of( + { + "IsoCountry": iso_country, + "Mcc": mcc, + "Mnc": mnc, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NetworkPage(self._version, response) + + def get_page(self, target_url: str) -> NetworkPage: + """ + Retrieve a specific page of NetworkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NetworkInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return NetworkPage(self._version, response) + + async def get_page_async(self, target_url: str) -> NetworkPage: + """ + Asynchronously retrieve a specific page of NetworkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NetworkInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return NetworkPage(self._version, response) + + def get(self, sid: str) -> NetworkContext: + """ + Constructs a NetworkContext + + :param sid: The SID of the Network resource to fetch. + """ + return NetworkContext(self._version, sid=sid) + + def __call__(self, sid: str) -> NetworkContext: + """ + Constructs a NetworkContext + + :param sid: The SID of the Network resource to fetch. + """ + return NetworkContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.NetworkList>" diff --git a/twilio/rest/supersim/v1/network_access_profile/__init__.py b/twilio/rest/supersim/v1/network_access_profile/__init__.py new file mode 100644 index 0000000000..15b0cc5695 --- /dev/null +++ b/twilio/rest/supersim/v1/network_access_profile/__init__.py @@ -0,0 +1,593 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.supersim.v1.network_access_profile.network_access_profile_network import ( + NetworkAccessProfileNetworkList, +) + + +class NetworkAccessProfileInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies the Network Access Profile resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the Network Access Profile belongs to. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Network Access Profile resource. + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[NetworkAccessProfileContext] = None + + @property + def _proxy(self) -> "NetworkAccessProfileContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NetworkAccessProfileContext for this NetworkAccessProfileInstance + """ + if self._context is None: + self._context = NetworkAccessProfileContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "NetworkAccessProfileInstance": + """ + Fetch the NetworkAccessProfileInstance + + + :returns: The fetched NetworkAccessProfileInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "NetworkAccessProfileInstance": + """ + Asynchronous coroutine to fetch the NetworkAccessProfileInstance + + + :returns: The fetched NetworkAccessProfileInstance + """ + return await self._proxy.fetch_async() + + def update( + self, unique_name: Union[str, object] = values.unset + ) -> "NetworkAccessProfileInstance": + """ + Update the NetworkAccessProfileInstance + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: The updated NetworkAccessProfileInstance + """ + return self._proxy.update( + unique_name=unique_name, + ) + + async def update_async( + self, unique_name: Union[str, object] = values.unset + ) -> "NetworkAccessProfileInstance": + """ + Asynchronous coroutine to update the NetworkAccessProfileInstance + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: The updated NetworkAccessProfileInstance + """ + return await self._proxy.update_async( + unique_name=unique_name, + ) + + @property + def networks(self) -> NetworkAccessProfileNetworkList: + """ + Access the networks + """ + return self._proxy.networks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Supersim.V1.NetworkAccessProfileInstance {}>".format(context) + + +class NetworkAccessProfileContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the NetworkAccessProfileContext + + :param version: Version that contains the resource + :param sid: The SID of the Network Access Profile to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/NetworkAccessProfiles/{sid}".format(**self._solution) + + self._networks: Optional[NetworkAccessProfileNetworkList] = None + + def fetch(self) -> NetworkAccessProfileInstance: + """ + Fetch the NetworkAccessProfileInstance + + + :returns: The fetched NetworkAccessProfileInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return NetworkAccessProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> NetworkAccessProfileInstance: + """ + Asynchronous coroutine to fetch the NetworkAccessProfileInstance + + + :returns: The fetched NetworkAccessProfileInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return NetworkAccessProfileInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, unique_name: Union[str, object] = values.unset + ) -> NetworkAccessProfileInstance: + """ + Update the NetworkAccessProfileInstance + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: The updated NetworkAccessProfileInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NetworkAccessProfileInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, unique_name: Union[str, object] = values.unset + ) -> NetworkAccessProfileInstance: + """ + Asynchronous coroutine to update the NetworkAccessProfileInstance + + :param unique_name: The new unique name of the Network Access Profile. + + :returns: The updated NetworkAccessProfileInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NetworkAccessProfileInstance( + self._version, payload, sid=self._solution["sid"] + ) + + @property + def networks(self) -> NetworkAccessProfileNetworkList: + """ + Access the networks + """ + if self._networks is None: + self._networks = NetworkAccessProfileNetworkList( + self._version, + self._solution["sid"], + ) + return self._networks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Supersim.V1.NetworkAccessProfileContext {}>".format(context) + + +class NetworkAccessProfilePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> NetworkAccessProfileInstance: + """ + Build an instance of NetworkAccessProfileInstance + + :param payload: Payload response from the API + """ + return NetworkAccessProfileInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.NetworkAccessProfilePage>" + + +class NetworkAccessProfileList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the NetworkAccessProfileList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/NetworkAccessProfiles" + + def create( + self, + unique_name: Union[str, object] = values.unset, + networks: Union[List[str], object] = values.unset, + ) -> NetworkAccessProfileInstance: + """ + Create the NetworkAccessProfileInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param networks: List of Network SIDs that this Network Access Profile will allow connections to. + + :returns: The created NetworkAccessProfileInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Networks": serialize.map(networks, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NetworkAccessProfileInstance(self._version, payload) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + networks: Union[List[str], object] = values.unset, + ) -> NetworkAccessProfileInstance: + """ + Asynchronously create the NetworkAccessProfileInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param networks: List of Network SIDs that this Network Access Profile will allow connections to. + + :returns: The created NetworkAccessProfileInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Networks": serialize.map(networks, lambda e: e), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NetworkAccessProfileInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[NetworkAccessProfileInstance]: + """ + Streams NetworkAccessProfileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[NetworkAccessProfileInstance]: + """ + Asynchronously streams NetworkAccessProfileInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NetworkAccessProfileInstance]: + """ + Lists NetworkAccessProfileInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NetworkAccessProfileInstance]: + """ + Asynchronously lists NetworkAccessProfileInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NetworkAccessProfilePage: + """ + Retrieve a single page of NetworkAccessProfileInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NetworkAccessProfileInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NetworkAccessProfilePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NetworkAccessProfilePage: + """ + Asynchronously retrieve a single page of NetworkAccessProfileInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NetworkAccessProfileInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NetworkAccessProfilePage(self._version, response) + + def get_page(self, target_url: str) -> NetworkAccessProfilePage: + """ + Retrieve a specific page of NetworkAccessProfileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NetworkAccessProfileInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return NetworkAccessProfilePage(self._version, response) + + async def get_page_async(self, target_url: str) -> NetworkAccessProfilePage: + """ + Asynchronously retrieve a specific page of NetworkAccessProfileInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NetworkAccessProfileInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return NetworkAccessProfilePage(self._version, response) + + def get(self, sid: str) -> NetworkAccessProfileContext: + """ + Constructs a NetworkAccessProfileContext + + :param sid: The SID of the Network Access Profile to update. + """ + return NetworkAccessProfileContext(self._version, sid=sid) + + def __call__(self, sid: str) -> NetworkAccessProfileContext: + """ + Constructs a NetworkAccessProfileContext + + :param sid: The SID of the Network Access Profile to update. + """ + return NetworkAccessProfileContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.NetworkAccessProfileList>" diff --git a/twilio/rest/supersim/v1/network_access_profile/network_access_profile_network.py b/twilio/rest/supersim/v1/network_access_profile/network_access_profile_network.py new file mode 100644 index 0000000000..c7099b8a7a --- /dev/null +++ b/twilio/rest/supersim/v1/network_access_profile/network_access_profile_network.py @@ -0,0 +1,557 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class NetworkAccessProfileNetworkInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies the Network resource. + :ivar network_access_profile_sid: The unique string that identifies the Network resource's Network Access Profile resource. + :ivar friendly_name: A human readable identifier of the Network this resource refers to. + :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the Network resource. + :ivar identifiers: Array of objects identifying the [MCC-MNCs](https://en.wikipedia.org/wiki/Mobile_country_code) that are included in the Network resource. + :ivar url: The absolute URL of the Network resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + network_access_profile_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.network_access_profile_sid: Optional[str] = payload.get( + "network_access_profile_sid" + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.iso_country: Optional[str] = payload.get("iso_country") + self.identifiers: Optional[List[Dict[str, object]]] = payload.get("identifiers") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "network_access_profile_sid": network_access_profile_sid, + "sid": sid or self.sid, + } + self._context: Optional[NetworkAccessProfileNetworkContext] = None + + @property + def _proxy(self) -> "NetworkAccessProfileNetworkContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: NetworkAccessProfileNetworkContext for this NetworkAccessProfileNetworkInstance + """ + if self._context is None: + self._context = NetworkAccessProfileNetworkContext( + self._version, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the NetworkAccessProfileNetworkInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the NetworkAccessProfileNetworkInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "NetworkAccessProfileNetworkInstance": + """ + Fetch the NetworkAccessProfileNetworkInstance + + + :returns: The fetched NetworkAccessProfileNetworkInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "NetworkAccessProfileNetworkInstance": + """ + Asynchronous coroutine to fetch the NetworkAccessProfileNetworkInstance + + + :returns: The fetched NetworkAccessProfileNetworkInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Supersim.V1.NetworkAccessProfileNetworkInstance {}>".format( + context + ) + + +class NetworkAccessProfileNetworkContext(InstanceContext): + + def __init__(self, version: Version, network_access_profile_sid: str, sid: str): + """ + Initialize the NetworkAccessProfileNetworkContext + + :param version: Version that contains the resource + :param network_access_profile_sid: The unique string that identifies the Network Access Profile resource. + :param sid: The SID of the Network resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "network_access_profile_sid": network_access_profile_sid, + "sid": sid, + } + self._uri = ( + "/NetworkAccessProfiles/{network_access_profile_sid}/Networks/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the NetworkAccessProfileNetworkInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the NetworkAccessProfileNetworkInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> NetworkAccessProfileNetworkInstance: + """ + Fetch the NetworkAccessProfileNetworkInstance + + + :returns: The fetched NetworkAccessProfileNetworkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> NetworkAccessProfileNetworkInstance: + """ + Asynchronous coroutine to fetch the NetworkAccessProfileNetworkInstance + + + :returns: The fetched NetworkAccessProfileNetworkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Supersim.V1.NetworkAccessProfileNetworkContext {}>".format( + context + ) + + +class NetworkAccessProfileNetworkPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> NetworkAccessProfileNetworkInstance: + """ + Build an instance of NetworkAccessProfileNetworkInstance + + :param payload: Payload response from the API + """ + return NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.NetworkAccessProfileNetworkPage>" + + +class NetworkAccessProfileNetworkList(ListResource): + + def __init__(self, version: Version, network_access_profile_sid: str): + """ + Initialize the NetworkAccessProfileNetworkList + + :param version: Version that contains the resource + :param network_access_profile_sid: The unique string that identifies the Network Access Profile resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "network_access_profile_sid": network_access_profile_sid, + } + self._uri = ( + "/NetworkAccessProfiles/{network_access_profile_sid}/Networks".format( + **self._solution + ) + ) + + def create(self, network: str) -> NetworkAccessProfileNetworkInstance: + """ + Create the NetworkAccessProfileNetworkInstance + + :param network: The SID of the Network resource to be added to the Network Access Profile resource. + + :returns: The created NetworkAccessProfileNetworkInstance + """ + + data = values.of( + { + "Network": network, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + ) + + async def create_async(self, network: str) -> NetworkAccessProfileNetworkInstance: + """ + Asynchronously create the NetworkAccessProfileNetworkInstance + + :param network: The SID of the Network resource to be added to the Network Access Profile resource. + + :returns: The created NetworkAccessProfileNetworkInstance + """ + + data = values.of( + { + "Network": network, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[NetworkAccessProfileNetworkInstance]: + """ + Streams NetworkAccessProfileNetworkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[NetworkAccessProfileNetworkInstance]: + """ + Asynchronously streams NetworkAccessProfileNetworkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NetworkAccessProfileNetworkInstance]: + """ + Lists NetworkAccessProfileNetworkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[NetworkAccessProfileNetworkInstance]: + """ + Asynchronously lists NetworkAccessProfileNetworkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NetworkAccessProfileNetworkPage: + """ + Retrieve a single page of NetworkAccessProfileNetworkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NetworkAccessProfileNetworkInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NetworkAccessProfileNetworkPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> NetworkAccessProfileNetworkPage: + """ + Asynchronously retrieve a single page of NetworkAccessProfileNetworkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of NetworkAccessProfileNetworkInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return NetworkAccessProfileNetworkPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> NetworkAccessProfileNetworkPage: + """ + Retrieve a specific page of NetworkAccessProfileNetworkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NetworkAccessProfileNetworkInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return NetworkAccessProfileNetworkPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> NetworkAccessProfileNetworkPage: + """ + Asynchronously retrieve a specific page of NetworkAccessProfileNetworkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of NetworkAccessProfileNetworkInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return NetworkAccessProfileNetworkPage(self._version, response, self._solution) + + def get(self, sid: str) -> NetworkAccessProfileNetworkContext: + """ + Constructs a NetworkAccessProfileNetworkContext + + :param sid: The SID of the Network resource to fetch. + """ + return NetworkAccessProfileNetworkContext( + self._version, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> NetworkAccessProfileNetworkContext: + """ + Constructs a NetworkAccessProfileNetworkContext + + :param sid: The SID of the Network resource to fetch. + """ + return NetworkAccessProfileNetworkContext( + self._version, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.NetworkAccessProfileNetworkList>" diff --git a/twilio/rest/supersim/v1/settings_update.py b/twilio/rest/supersim/v1/settings_update.py new file mode 100644 index 0000000000..294e1102ce --- /dev/null +++ b/twilio/rest/supersim/v1/settings_update.py @@ -0,0 +1,337 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SettingsUpdateInstance(InstanceResource): + + class Status(object): + SCHEDULED = "scheduled" + IN_PROGRESS = "in-progress" + SUCCESSFUL = "successful" + FAILED = "failed" + + """ + :ivar sid: The unique identifier of this Settings Update. + :ivar iccid: The [ICCID](https://en.wikipedia.org/wiki/SIM_card#ICCID) associated with the SIM. + :ivar sim_sid: The SID of the Super SIM to which this Settings Update was applied. + :ivar status: + :ivar packages: Array containing the different Settings Packages that will be applied to the SIM after the update completes. Each object within the array indicates the name and the version of the Settings Package that will be on the SIM if the update is successful. + :ivar date_completed: The time, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format, when the update successfully completed and the new settings were applied to the SIM. + :ivar date_created: The date that this Settings Update was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this Settings Update was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.iccid: Optional[str] = payload.get("iccid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.status: Optional["SettingsUpdateInstance.Status"] = payload.get("status") + self.packages: Optional[List[Dict[str, object]]] = payload.get("packages") + self.date_completed: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_completed") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Supersim.V1.SettingsUpdateInstance>" + + +class SettingsUpdatePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SettingsUpdateInstance: + """ + Build an instance of SettingsUpdateInstance + + :param payload: Payload response from the API + """ + return SettingsUpdateInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.SettingsUpdatePage>" + + +class SettingsUpdateList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SettingsUpdateList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SettingsUpdates" + + def stream( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SettingsUpdateInstance]: + """ + Streams SettingsUpdateInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param "SettingsUpdateInstance.Status" status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(sim=sim, status=status, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SettingsUpdateInstance]: + """ + Asynchronously streams SettingsUpdateInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param "SettingsUpdateInstance.Status" status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + sim=sim, status=status, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SettingsUpdateInstance]: + """ + Lists SettingsUpdateInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param "SettingsUpdateInstance.Status" status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + sim=sim, + status=status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SettingsUpdateInstance]: + """ + Asynchronously lists SettingsUpdateInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param "SettingsUpdateInstance.Status" status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + sim=sim, + status=status, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SettingsUpdatePage: + """ + Retrieve a single page of SettingsUpdateInstance records from the API. + Request is executed immediately + + :param sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SettingsUpdateInstance + """ + data = values.of( + { + "Sim": sim, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SettingsUpdatePage(self._version, response) + + async def page_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SettingsUpdateInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SettingsUpdatePage: + """ + Asynchronously retrieve a single page of SettingsUpdateInstance records from the API. + Request is executed immediately + + :param sim: Filter the Settings Updates by a Super SIM's SID or UniqueName. + :param status: Filter the Settings Updates by status. Can be `scheduled`, `in-progress`, `successful`, or `failed`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SettingsUpdateInstance + """ + data = values.of( + { + "Sim": sim, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SettingsUpdatePage(self._version, response) + + def get_page(self, target_url: str) -> SettingsUpdatePage: + """ + Retrieve a specific page of SettingsUpdateInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SettingsUpdateInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SettingsUpdatePage(self._version, response) + + async def get_page_async(self, target_url: str) -> SettingsUpdatePage: + """ + Asynchronously retrieve a specific page of SettingsUpdateInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SettingsUpdateInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SettingsUpdatePage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.SettingsUpdateList>" diff --git a/twilio/rest/supersim/v1/sim/__init__.py b/twilio/rest/supersim/v1/sim/__init__.py new file mode 100644 index 0000000000..fa878a16df --- /dev/null +++ b/twilio/rest/supersim/v1/sim/__init__.py @@ -0,0 +1,735 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.supersim.v1.sim.billing_period import BillingPeriodList +from twilio.rest.supersim.v1.sim.sim_ip_address import SimIpAddressList + + +class SimInstance(InstanceResource): + + class Status(object): + NEW = "new" + READY = "ready" + ACTIVE = "active" + INACTIVE = "inactive" + SCHEDULED = "scheduled" + + class StatusUpdate(object): + READY = "ready" + ACTIVE = "active" + INACTIVE = "inactive" + + """ + :ivar sid: The unique string that identifies the Sim resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the Super SIM belongs to. + :ivar iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with the SIM. + :ivar status: + :ivar fleet_sid: The unique ID of the Fleet configured for this SIM. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Sim Resource. + :ivar links: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.iccid: Optional[str] = payload.get("iccid") + self.status: Optional["SimInstance.Status"] = payload.get("status") + self.fleet_sid: Optional[str] = payload.get("fleet_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SimContext] = None + + @property + def _proxy(self) -> "SimContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SimContext for this SimInstance + """ + if self._context is None: + self._context = SimContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "SimInstance": + """ + Fetch the SimInstance + + + :returns: The fetched SimInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SimInstance": + """ + Asynchronous coroutine to fetch the SimInstance + + + :returns: The fetched SimInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + unique_name: Union[str, object] = values.unset, + status: Union["SimInstance.StatusUpdate", object] = values.unset, + fleet: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> "SimInstance": + """ + Update the SimInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param status: + :param fleet: The SID or unique name of the Fleet to which the SIM resource should be assigned. + :param callback_url: The URL we should call using the `callback_method` after an asynchronous update has finished. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param account_sid: The SID of the Account to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a Subaccount of the requesting Account. Only valid when the Sim resource's status is new. + + :returns: The updated SimInstance + """ + return self._proxy.update( + unique_name=unique_name, + status=status, + fleet=fleet, + callback_url=callback_url, + callback_method=callback_method, + account_sid=account_sid, + ) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + status: Union["SimInstance.StatusUpdate", object] = values.unset, + fleet: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> "SimInstance": + """ + Asynchronous coroutine to update the SimInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param status: + :param fleet: The SID or unique name of the Fleet to which the SIM resource should be assigned. + :param callback_url: The URL we should call using the `callback_method` after an asynchronous update has finished. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param account_sid: The SID of the Account to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a Subaccount of the requesting Account. Only valid when the Sim resource's status is new. + + :returns: The updated SimInstance + """ + return await self._proxy.update_async( + unique_name=unique_name, + status=status, + fleet=fleet, + callback_url=callback_url, + callback_method=callback_method, + account_sid=account_sid, + ) + + @property + def billing_periods(self) -> BillingPeriodList: + """ + Access the billing_periods + """ + return self._proxy.billing_periods + + @property + def sim_ip_addresses(self) -> SimIpAddressList: + """ + Access the sim_ip_addresses + """ + return self._proxy.sim_ip_addresses + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Supersim.V1.SimInstance {}>".format(context) + + +class SimContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SimContext + + :param version: Version that contains the resource + :param sid: The SID of the Sim resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Sims/{sid}".format(**self._solution) + + self._billing_periods: Optional[BillingPeriodList] = None + self._sim_ip_addresses: Optional[SimIpAddressList] = None + + def fetch(self) -> SimInstance: + """ + Fetch the SimInstance + + + :returns: The fetched SimInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SimInstance: + """ + Asynchronous coroutine to fetch the SimInstance + + + :returns: The fetched SimInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + unique_name: Union[str, object] = values.unset, + status: Union["SimInstance.StatusUpdate", object] = values.unset, + fleet: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> SimInstance: + """ + Update the SimInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param status: + :param fleet: The SID or unique name of the Fleet to which the SIM resource should be assigned. + :param callback_url: The URL we should call using the `callback_method` after an asynchronous update has finished. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param account_sid: The SID of the Account to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a Subaccount of the requesting Account. Only valid when the Sim resource's status is new. + + :returns: The updated SimInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Status": status, + "Fleet": fleet, + "CallbackUrl": callback_url, + "CallbackMethod": callback_method, + "AccountSid": account_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + status: Union["SimInstance.StatusUpdate", object] = values.unset, + fleet: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> SimInstance: + """ + Asynchronous coroutine to update the SimInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param status: + :param fleet: The SID or unique name of the Fleet to which the SIM resource should be assigned. + :param callback_url: The URL we should call using the `callback_method` after an asynchronous update has finished. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param account_sid: The SID of the Account to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a Subaccount of the requesting Account. Only valid when the Sim resource's status is new. + + :returns: The updated SimInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Status": status, + "Fleet": fleet, + "CallbackUrl": callback_url, + "CallbackMethod": callback_method, + "AccountSid": account_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def billing_periods(self) -> BillingPeriodList: + """ + Access the billing_periods + """ + if self._billing_periods is None: + self._billing_periods = BillingPeriodList( + self._version, + self._solution["sid"], + ) + return self._billing_periods + + @property + def sim_ip_addresses(self) -> SimIpAddressList: + """ + Access the sim_ip_addresses + """ + if self._sim_ip_addresses is None: + self._sim_ip_addresses = SimIpAddressList( + self._version, + self._solution["sid"], + ) + return self._sim_ip_addresses + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Supersim.V1.SimContext {}>".format(context) + + +class SimPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SimInstance: + """ + Build an instance of SimInstance + + :param payload: Payload response from the API + """ + return SimInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.SimPage>" + + +class SimList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SimList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Sims" + + def create(self, iccid: str, registration_code: str) -> SimInstance: + """ + Create the SimInstance + + :param iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) of the Super SIM to be added to your Account. + :param registration_code: The 10-digit code required to claim the Super SIM for your Account. + + :returns: The created SimInstance + """ + + data = values.of( + { + "Iccid": iccid, + "RegistrationCode": registration_code, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SimInstance(self._version, payload) + + async def create_async(self, iccid: str, registration_code: str) -> SimInstance: + """ + Asynchronously create the SimInstance + + :param iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) of the Super SIM to be added to your Account. + :param registration_code: The 10-digit code required to claim the Super SIM for your Account. + + :returns: The created SimInstance + """ + + data = values.of( + { + "Iccid": iccid, + "RegistrationCode": registration_code, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SimInstance(self._version, payload) + + def stream( + self, + status: Union["SimInstance.Status", object] = values.unset, + fleet: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SimInstance]: + """ + Streams SimInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "SimInstance.Status" status: The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. + :param str fleet: The SID or unique name of the Fleet to which a list of Sims are assigned. + :param str iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, fleet=fleet, iccid=iccid, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["SimInstance.Status", object] = values.unset, + fleet: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SimInstance]: + """ + Asynchronously streams SimInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "SimInstance.Status" status: The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. + :param str fleet: The SID or unique name of the Fleet to which a list of Sims are assigned. + :param str iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, fleet=fleet, iccid=iccid, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["SimInstance.Status", object] = values.unset, + fleet: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SimInstance]: + """ + Lists SimInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "SimInstance.Status" status: The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. + :param str fleet: The SID or unique name of the Fleet to which a list of Sims are assigned. + :param str iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + fleet=fleet, + iccid=iccid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["SimInstance.Status", object] = values.unset, + fleet: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SimInstance]: + """ + Asynchronously lists SimInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "SimInstance.Status" status: The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. + :param str fleet: The SID or unique name of the Fleet to which a list of Sims are assigned. + :param str iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + fleet=fleet, + iccid=iccid, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["SimInstance.Status", object] = values.unset, + fleet: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SimPage: + """ + Retrieve a single page of SimInstance records from the API. + Request is executed immediately + + :param status: The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. + :param fleet: The SID or unique name of the Fleet to which a list of Sims are assigned. + :param iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SimInstance + """ + data = values.of( + { + "Status": status, + "Fleet": fleet, + "Iccid": iccid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SimPage(self._version, response) + + async def page_async( + self, + status: Union["SimInstance.Status", object] = values.unset, + fleet: Union[str, object] = values.unset, + iccid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SimPage: + """ + Asynchronously retrieve a single page of SimInstance records from the API. + Request is executed immediately + + :param status: The status of the Sim resources to read. Can be `new`, `ready`, `active`, `inactive`, or `scheduled`. + :param fleet: The SID or unique name of the Fleet to which a list of Sims are assigned. + :param iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with a Super SIM to filter the list by. Passing this parameter will always return a list containing zero or one SIMs. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SimInstance + """ + data = values.of( + { + "Status": status, + "Fleet": fleet, + "Iccid": iccid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SimPage(self._version, response) + + def get_page(self, target_url: str) -> SimPage: + """ + Retrieve a specific page of SimInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SimInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SimPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SimPage: + """ + Asynchronously retrieve a specific page of SimInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SimInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SimPage(self._version, response) + + def get(self, sid: str) -> SimContext: + """ + Constructs a SimContext + + :param sid: The SID of the Sim resource to update. + """ + return SimContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SimContext: + """ + Constructs a SimContext + + :param sid: The SID of the Sim resource to update. + """ + return SimContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.SimList>" diff --git a/twilio/rest/supersim/v1/sim/billing_period.py b/twilio/rest/supersim/v1/sim/billing_period.py new file mode 100644 index 0000000000..27cbe1222e --- /dev/null +++ b/twilio/rest/supersim/v1/sim/billing_period.py @@ -0,0 +1,316 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class BillingPeriodInstance(InstanceResource): + + class BpType(object): + READY = "ready" + ACTIVE = "active" + + """ + :ivar sid: The SID of the Billing Period. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) the Super SIM belongs to. + :ivar sim_sid: The SID of the Super SIM the Billing Period belongs to. + :ivar start_time: The start time of the Billing Period specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar end_time: The end time of the Billing Period specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar period_type: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sim_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.period_type: Optional["BillingPeriodInstance.BpType"] = payload.get( + "period_type" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "sim_sid": sim_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Supersim.V1.BillingPeriodInstance {}>".format(context) + + +class BillingPeriodPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BillingPeriodInstance: + """ + Build an instance of BillingPeriodInstance + + :param payload: Payload response from the API + """ + return BillingPeriodInstance( + self._version, payload, sim_sid=self._solution["sim_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.BillingPeriodPage>" + + +class BillingPeriodList(ListResource): + + def __init__(self, version: Version, sim_sid: str): + """ + Initialize the BillingPeriodList + + :param version: Version that contains the resource + :param sim_sid: The SID of the Super SIM to list Billing Periods for. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sim_sid": sim_sid, + } + self._uri = "/Sims/{sim_sid}/BillingPeriods".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BillingPeriodInstance]: + """ + Streams BillingPeriodInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BillingPeriodInstance]: + """ + Asynchronously streams BillingPeriodInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BillingPeriodInstance]: + """ + Lists BillingPeriodInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BillingPeriodInstance]: + """ + Asynchronously lists BillingPeriodInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BillingPeriodPage: + """ + Retrieve a single page of BillingPeriodInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BillingPeriodInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BillingPeriodPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BillingPeriodPage: + """ + Asynchronously retrieve a single page of BillingPeriodInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BillingPeriodInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BillingPeriodPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> BillingPeriodPage: + """ + Retrieve a specific page of BillingPeriodInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BillingPeriodInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BillingPeriodPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> BillingPeriodPage: + """ + Asynchronously retrieve a specific page of BillingPeriodInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BillingPeriodInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BillingPeriodPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.BillingPeriodList>" diff --git a/twilio/rest/supersim/v1/sim/sim_ip_address.py b/twilio/rest/supersim/v1/sim/sim_ip_address.py new file mode 100644 index 0000000000..0c4c3163b6 --- /dev/null +++ b/twilio/rest/supersim/v1/sim/sim_ip_address.py @@ -0,0 +1,295 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SimIpAddressInstance(InstanceResource): + + class IpAddressVersion(object): + IPV4 = "IPv4" + IPV6 = "IPv6" + + """ + :ivar ip_address: IP address assigned to the given Super SIM + :ivar ip_address_version: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sim_sid: str): + super().__init__(version) + + self.ip_address: Optional[str] = payload.get("ip_address") + self.ip_address_version: Optional["SimIpAddressInstance.IpAddressVersion"] = ( + payload.get("ip_address_version") + ) + + self._solution = { + "sim_sid": sim_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Supersim.V1.SimIpAddressInstance {}>".format(context) + + +class SimIpAddressPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SimIpAddressInstance: + """ + Build an instance of SimIpAddressInstance + + :param payload: Payload response from the API + """ + return SimIpAddressInstance( + self._version, payload, sim_sid=self._solution["sim_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.SimIpAddressPage>" + + +class SimIpAddressList(ListResource): + + def __init__(self, version: Version, sim_sid: str): + """ + Initialize the SimIpAddressList + + :param version: Version that contains the resource + :param sim_sid: The SID of the Super SIM to list IP Addresses for. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sim_sid": sim_sid, + } + self._uri = "/Sims/{sim_sid}/IpAddresses".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SimIpAddressInstance]: + """ + Streams SimIpAddressInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SimIpAddressInstance]: + """ + Asynchronously streams SimIpAddressInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SimIpAddressInstance]: + """ + Lists SimIpAddressInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SimIpAddressInstance]: + """ + Asynchronously lists SimIpAddressInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SimIpAddressPage: + """ + Retrieve a single page of SimIpAddressInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SimIpAddressInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SimIpAddressPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SimIpAddressPage: + """ + Asynchronously retrieve a single page of SimIpAddressInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SimIpAddressInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SimIpAddressPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SimIpAddressPage: + """ + Retrieve a specific page of SimIpAddressInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SimIpAddressInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SimIpAddressPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SimIpAddressPage: + """ + Asynchronously retrieve a specific page of SimIpAddressInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SimIpAddressInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SimIpAddressPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.SimIpAddressList>" diff --git a/twilio/rest/supersim/v1/sms_command.py b/twilio/rest/supersim/v1/sms_command.py new file mode 100644 index 0000000000..dd70d2425e --- /dev/null +++ b/twilio/rest/supersim/v1/sms_command.py @@ -0,0 +1,563 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SmsCommandInstance(InstanceResource): + + class Direction(object): + TO_SIM = "to_sim" + FROM_SIM = "from_sim" + + class Status(object): + QUEUED = "queued" + SENT = "sent" + DELIVERED = "delivered" + RECEIVED = "received" + FAILED = "failed" + + """ + :ivar sid: The unique string that we created to identify the SMS Command resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the SMS Command resource. + :ivar sim_sid: The SID of the [SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) that this SMS Command was sent to or from. + :ivar payload: The message body of the SMS Command sent to or from the SIM. For text mode messages, this can be up to 160 characters. + :ivar status: + :ivar direction: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the SMS Command resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.payload: Optional[str] = payload.get("payload") + self.status: Optional["SmsCommandInstance.Status"] = payload.get("status") + self.direction: Optional["SmsCommandInstance.Direction"] = payload.get( + "direction" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SmsCommandContext] = None + + @property + def _proxy(self) -> "SmsCommandContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SmsCommandContext for this SmsCommandInstance + """ + if self._context is None: + self._context = SmsCommandContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "SmsCommandInstance": + """ + Fetch the SmsCommandInstance + + + :returns: The fetched SmsCommandInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SmsCommandInstance": + """ + Asynchronous coroutine to fetch the SmsCommandInstance + + + :returns: The fetched SmsCommandInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Supersim.V1.SmsCommandInstance {}>".format(context) + + +class SmsCommandContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SmsCommandContext + + :param version: Version that contains the resource + :param sid: The SID of the SMS Command resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/SmsCommands/{sid}".format(**self._solution) + + def fetch(self) -> SmsCommandInstance: + """ + Fetch the SmsCommandInstance + + + :returns: The fetched SmsCommandInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SmsCommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SmsCommandInstance: + """ + Asynchronous coroutine to fetch the SmsCommandInstance + + + :returns: The fetched SmsCommandInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SmsCommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Supersim.V1.SmsCommandContext {}>".format(context) + + +class SmsCommandPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SmsCommandInstance: + """ + Build an instance of SmsCommandInstance + + :param payload: Payload response from the API + """ + return SmsCommandInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.SmsCommandPage>" + + +class SmsCommandList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SmsCommandList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SmsCommands" + + def create( + self, + sim: str, + payload: str, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + ) -> SmsCommandInstance: + """ + Create the SmsCommandInstance + + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the SMS Command to. + :param payload: The message body of the SMS Command. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param callback_url: The URL we should call using the `callback_method` after we have sent the command. + + :returns: The created SmsCommandInstance + """ + + data = values.of( + { + "Sim": sim, + "Payload": payload, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SmsCommandInstance(self._version, payload) + + async def create_async( + self, + sim: str, + payload: str, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + ) -> SmsCommandInstance: + """ + Asynchronously create the SmsCommandInstance + + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/supersim/api/sim-resource) to send the SMS Command to. + :param payload: The message body of the SMS Command. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `GET` or `POST` and the default is POST. + :param callback_url: The URL we should call using the `callback_method` after we have sent the command. + + :returns: The created SmsCommandInstance + """ + + data = values.of( + { + "Sim": sim, + "Payload": payload, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SmsCommandInstance(self._version, payload) + + def stream( + self, + sim: Union[str, object] = values.unset, + status: Union["SmsCommandInstance.Status", object] = values.unset, + direction: Union["SmsCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SmsCommandInstance]: + """ + Streams SmsCommandInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sim: The SID or unique name of the Sim resource that SMS Command was sent to or from. + :param "SmsCommandInstance.Status" status: The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. + :param "SmsCommandInstance.Direction" direction: The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + sim=sim, status=status, direction=direction, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SmsCommandInstance.Status", object] = values.unset, + direction: Union["SmsCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SmsCommandInstance]: + """ + Asynchronously streams SmsCommandInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sim: The SID or unique name of the Sim resource that SMS Command was sent to or from. + :param "SmsCommandInstance.Status" status: The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. + :param "SmsCommandInstance.Direction" direction: The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + sim=sim, status=status, direction=direction, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + sim: Union[str, object] = values.unset, + status: Union["SmsCommandInstance.Status", object] = values.unset, + direction: Union["SmsCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SmsCommandInstance]: + """ + Lists SmsCommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: The SID or unique name of the Sim resource that SMS Command was sent to or from. + :param "SmsCommandInstance.Status" status: The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. + :param "SmsCommandInstance.Direction" direction: The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + sim=sim, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SmsCommandInstance.Status", object] = values.unset, + direction: Union["SmsCommandInstance.Direction", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SmsCommandInstance]: + """ + Asynchronously lists SmsCommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: The SID or unique name of the Sim resource that SMS Command was sent to or from. + :param "SmsCommandInstance.Status" status: The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. + :param "SmsCommandInstance.Direction" direction: The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + sim=sim, + status=status, + direction=direction, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + sim: Union[str, object] = values.unset, + status: Union["SmsCommandInstance.Status", object] = values.unset, + direction: Union["SmsCommandInstance.Direction", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SmsCommandPage: + """ + Retrieve a single page of SmsCommandInstance records from the API. + Request is executed immediately + + :param sim: The SID or unique name of the Sim resource that SMS Command was sent to or from. + :param status: The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. + :param direction: The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SmsCommandInstance + """ + data = values.of( + { + "Sim": sim, + "Status": status, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SmsCommandPage(self._version, response) + + async def page_async( + self, + sim: Union[str, object] = values.unset, + status: Union["SmsCommandInstance.Status", object] = values.unset, + direction: Union["SmsCommandInstance.Direction", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SmsCommandPage: + """ + Asynchronously retrieve a single page of SmsCommandInstance records from the API. + Request is executed immediately + + :param sim: The SID or unique name of the Sim resource that SMS Command was sent to or from. + :param status: The status of the SMS Command. Can be: `queued`, `sent`, `delivered`, `received` or `failed`. See the [SMS Command Status Values](https://www.twilio.com/docs/iot/supersim/api/smscommand-resource#status-values) for a description of each. + :param direction: The direction of the SMS Command. Can be `to_sim` or `from_sim`. The value of `to_sim` is synonymous with the term `mobile terminated`, and `from_sim` is synonymous with the term `mobile originated`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SmsCommandInstance + """ + data = values.of( + { + "Sim": sim, + "Status": status, + "Direction": direction, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SmsCommandPage(self._version, response) + + def get_page(self, target_url: str) -> SmsCommandPage: + """ + Retrieve a specific page of SmsCommandInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SmsCommandInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SmsCommandPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SmsCommandPage: + """ + Asynchronously retrieve a specific page of SmsCommandInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SmsCommandInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SmsCommandPage(self._version, response) + + def get(self, sid: str) -> SmsCommandContext: + """ + Constructs a SmsCommandContext + + :param sid: The SID of the SMS Command resource to fetch. + """ + return SmsCommandContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SmsCommandContext: + """ + Constructs a SmsCommandContext + + :param sid: The SID of the SMS Command resource to fetch. + """ + return SmsCommandContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.SmsCommandList>" diff --git a/twilio/rest/supersim/v1/usage_record.py b/twilio/rest/supersim/v1/usage_record.py new file mode 100644 index 0000000000..94072a51fb --- /dev/null +++ b/twilio/rest/supersim/v1/usage_record.py @@ -0,0 +1,458 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Supersim + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UsageRecordInstance(InstanceResource): + + class Granularity(object): + HOUR = "hour" + DAY = "day" + ALL = "all" + + class Group(object): + SIM = "sim" + FLEET = "fleet" + NETWORK = "network" + ISOCOUNTRY = "isoCountry" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that incurred the usage. + :ivar sim_sid: SID of a Sim resource to which the UsageRecord belongs. Value will only be present when either a value for the `Sim` query parameter is provided or when UsageRecords are grouped by `sim`. Otherwise, the value will be `null`. + :ivar network_sid: SID of the Network resource the usage occurred on. Value will only be present when either a value for the `Network` query parameter is provided or when UsageRecords are grouped by `network`. Otherwise, the value will be `null`. + :ivar fleet_sid: SID of the Fleet resource the usage occurred on. Value will only be present when either a value for the `Fleet` query parameter is provided or when UsageRecords are grouped by `fleet`. Otherwise, the value will be `null`. + :ivar iso_country: Alpha-2 ISO Country Code that the usage occurred in. Value will only be present when either a value for the `IsoCountry` query parameter is provided or when UsageRecords are grouped by `isoCountry`. Otherwise, the value will be `null`. + :ivar period: The time period for which the usage is reported. The period is represented as a pair of `start_time` and `end_time` timestamps specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar data_upload: Total data uploaded in bytes, aggregated by the query parameters. + :ivar data_download: Total data downloaded in bytes, aggregated by the query parameters. + :ivar data_total: Total of data_upload and data_download. + :ivar data_total_billed: Total amount in the `billed_unit` that was charged for the data uploaded or downloaded. Will return 0 for usage prior to February 1, 2022. Value may be 0 despite `data_total` being greater than 0 if the data usage is still being processed by Twilio's billing system. Refer to [Data Usage Processing](https://www.twilio.com/docs/iot/supersim/api/usage-record-resource#data-usage-processing) for more details. + :ivar billed_unit: The currency in which the billed amounts are measured, specified in the 3 letter ISO 4127 format (e.g. `USD`, `EUR`, `JPY`). This can be null when data_toal_billed is 0 and we do not yet have billing information for the corresponding data usage. Refer to [Data Usage Processing](https://www.twilio.com/docs/iot/supersim/api/usage-record-resource#data-usage-processing) for more details. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.network_sid: Optional[str] = payload.get("network_sid") + self.fleet_sid: Optional[str] = payload.get("fleet_sid") + self.iso_country: Optional[str] = payload.get("iso_country") + self.period: Optional[Dict[str, object]] = payload.get("period") + self.data_upload: Optional[int] = payload.get("data_upload") + self.data_download: Optional[int] = payload.get("data_download") + self.data_total: Optional[int] = payload.get("data_total") + self.data_total_billed: Optional[float] = deserialize.decimal( + payload.get("data_total_billed") + ) + self.billed_unit: Optional[str] = payload.get("billed_unit") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Supersim.V1.UsageRecordInstance>" + + +class UsageRecordPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UsageRecordInstance: + """ + Build an instance of UsageRecordInstance + + :param payload: Payload response from the API + """ + return UsageRecordInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.UsageRecordPage>" + + +class UsageRecordList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the UsageRecordList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/UsageRecords" + + def stream( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UsageRecordInstance]: + """ + Streams UsageRecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param str fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param str network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param str iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param "UsageRecordInstance.Group" group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param "UsageRecordInstance.Granularity" granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param datetime start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param datetime end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + sim=sim, + fleet=fleet, + network=network, + iso_country=iso_country, + group=group, + granularity=granularity, + start_time=start_time, + end_time=end_time, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UsageRecordInstance]: + """ + Asynchronously streams UsageRecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param str fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param str network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param str iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param "UsageRecordInstance.Group" group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param "UsageRecordInstance.Granularity" granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param datetime start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param datetime end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + sim=sim, + fleet=fleet, + network=network, + iso_country=iso_country, + group=group, + granularity=granularity, + start_time=start_time, + end_time=end_time, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UsageRecordInstance]: + """ + Lists UsageRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param str fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param str network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param str iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param "UsageRecordInstance.Group" group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param "UsageRecordInstance.Granularity" granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param datetime start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param datetime end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + sim=sim, + fleet=fleet, + network=network, + iso_country=iso_country, + group=group, + granularity=granularity, + start_time=start_time, + end_time=end_time, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UsageRecordInstance]: + """ + Asynchronously lists UsageRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param str fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param str network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param str iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param "UsageRecordInstance.Group" group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param "UsageRecordInstance.Granularity" granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param datetime start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param datetime end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + sim=sim, + fleet=fleet, + network=network, + iso_country=iso_country, + group=group, + granularity=granularity, + start_time=start_time, + end_time=end_time, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UsageRecordPage: + """ + Retrieve a single page of UsageRecordInstance records from the API. + Request is executed immediately + + :param sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UsageRecordInstance + """ + data = values.of( + { + "Sim": sim, + "Fleet": fleet, + "Network": network, + "IsoCountry": iso_country, + "Group": group, + "Granularity": granularity, + "StartTime": serialize.iso8601_datetime(start_time), + "EndTime": serialize.iso8601_datetime(end_time), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response) + + async def page_async( + self, + sim: Union[str, object] = values.unset, + fleet: Union[str, object] = values.unset, + network: Union[str, object] = values.unset, + iso_country: Union[str, object] = values.unset, + group: Union["UsageRecordInstance.Group", object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + start_time: Union[datetime, object] = values.unset, + end_time: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UsageRecordPage: + """ + Asynchronously retrieve a single page of UsageRecordInstance records from the API. + Request is executed immediately + + :param sim: SID or unique name of a Sim resource. Only show UsageRecords representing usage incurred by this Super SIM. + :param fleet: SID or unique name of a Fleet resource. Only show UsageRecords representing usage for Super SIMs belonging to this Fleet resource at the time the usage occurred. + :param network: SID of a Network resource. Only show UsageRecords representing usage on this network. + :param iso_country: Alpha-2 ISO Country Code. Only show UsageRecords representing usage in this country. + :param group: Dimension over which to aggregate usage records. Can be: `sim`, `fleet`, `network`, `isoCountry`. Default is to not aggregate across any of these dimensions, UsageRecords will be aggregated into the time buckets described by the `Granularity` parameter. + :param granularity: Time-based grouping that UsageRecords should be aggregated by. Can be: `hour`, `day`, or `all`. Default is `all`. `all` returns one UsageRecord that describes the usage for the entire period. + :param start_time: Only include usage that occurred at or after this time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is one month before the `end_time`. + :param end_time: Only include usage that occurred before this time (exclusive), specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Default is the current time. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UsageRecordInstance + """ + data = values.of( + { + "Sim": sim, + "Fleet": fleet, + "Network": network, + "IsoCountry": iso_country, + "Group": group, + "Granularity": granularity, + "StartTime": serialize.iso8601_datetime(start_time), + "EndTime": serialize.iso8601_datetime(end_time), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response) + + def get_page(self, target_url: str) -> UsageRecordPage: + """ + Retrieve a specific page of UsageRecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UsageRecordInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UsageRecordPage(self._version, response) + + async def get_page_async(self, target_url: str) -> UsageRecordPage: + """ + Asynchronously retrieve a specific page of UsageRecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UsageRecordInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UsageRecordPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Supersim.V1.UsageRecordList>" diff --git a/twilio/rest/sync/SyncBase.py b/twilio/rest/sync/SyncBase.py new file mode 100644 index 0000000000..113cac0390 --- /dev/null +++ b/twilio/rest/sync/SyncBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.sync.v1 import V1 + + +class SyncBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Sync Domain + + :returns: Domain for Sync + """ + super().__init__(twilio, "https://sync.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Sync + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Sync>" diff --git a/twilio/rest/sync/__init__.py b/twilio/rest/sync/__init__.py new file mode 100644 index 0000000000..37b9ce03d6 --- /dev/null +++ b/twilio/rest/sync/__init__.py @@ -0,0 +1,15 @@ +from warnings import warn + +from twilio.rest.sync.SyncBase import SyncBase +from twilio.rest.sync.v1.service import ServiceList + + +class Sync(SyncBase): + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v1.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.services diff --git a/twilio/rest/sync/v1/__init__.py b/twilio/rest/sync/v1/__init__.py new file mode 100644 index 0000000000..e98201bd41 --- /dev/null +++ b/twilio/rest/sync/v1/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.sync.v1.service import ServiceList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Sync + + :param domain: The Twilio.sync domain + """ + super().__init__(domain, "v1") + self._services: Optional[ServiceList] = None + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1>" diff --git a/twilio/rest/sync/v1/service/__init__.py b/twilio/rest/sync/v1/service/__init__.py new file mode 100644 index 0000000000..d17491d3cb --- /dev/null +++ b/twilio/rest/sync/v1/service/__init__.py @@ -0,0 +1,846 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.sync.v1.service.document import DocumentList +from twilio.rest.sync.v1.service.sync_list import SyncListList +from twilio.rest.sync.v1.service.sync_map import SyncMapList +from twilio.rest.sync.v1.service.sync_stream import SyncStreamList + + +class ServiceInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Service resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. It is a read-only property, it cannot be assigned using REST API. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Service resource. + :ivar webhook_url: The URL we call when Sync objects are manipulated. + :ivar webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + :ivar reachability_webhooks_enabled: Whether the service instance calls `webhook_url` when client endpoints connect to Sync. The default is `false`. + :ivar acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. It is disabled (false) by default. + :ivar reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :ivar reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before `webhook_url` is called, if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the reachability event from occurring. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.webhook_url: Optional[str] = payload.get("webhook_url") + self.webhooks_from_rest_enabled: Optional[bool] = payload.get( + "webhooks_from_rest_enabled" + ) + self.reachability_webhooks_enabled: Optional[bool] = payload.get( + "reachability_webhooks_enabled" + ) + self.acl_enabled: Optional[bool] = payload.get("acl_enabled") + self.reachability_debouncing_enabled: Optional[bool] = payload.get( + "reachability_debouncing_enabled" + ) + self.reachability_debouncing_window: Optional[int] = deserialize.integer( + payload.get("reachability_debouncing_window") + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param friendly_name: A string that you assign to describe the resource. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + webhook_url=webhook_url, + friendly_name=friendly_name, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + + async def update_async( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param friendly_name: A string that you assign to describe the resource. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + webhook_url=webhook_url, + friendly_name=friendly_name, + reachability_webhooks_enabled=reachability_webhooks_enabled, + acl_enabled=acl_enabled, + reachability_debouncing_enabled=reachability_debouncing_enabled, + reachability_debouncing_window=reachability_debouncing_window, + webhooks_from_rest_enabled=webhooks_from_rest_enabled, + ) + + @property + def documents(self) -> DocumentList: + """ + Access the documents + """ + return self._proxy.documents + + @property + def sync_lists(self) -> SyncListList: + """ + Access the sync_lists + """ + return self._proxy.sync_lists + + @property + def sync_maps(self) -> SyncMapList: + """ + Access the sync_maps + """ + return self._proxy.sync_maps + + @property + def sync_streams(self) -> SyncStreamList: + """ + Access the sync_streams + """ + return self._proxy.sync_streams + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.ServiceInstance {}>".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The SID of the Service resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._documents: Optional[DocumentList] = None + self._sync_lists: Optional[SyncListList] = None + self._sync_maps: Optional[SyncMapList] = None + self._sync_streams: Optional[SyncStreamList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param friendly_name: A string that you assign to describe the resource. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "WebhookUrl": webhook_url, + "FriendlyName": friendly_name, + "ReachabilityWebhooksEnabled": serialize.boolean_to_string( + reachability_webhooks_enabled + ), + "AclEnabled": serialize.boolean_to_string(acl_enabled), + "ReachabilityDebouncingEnabled": serialize.boolean_to_string( + reachability_debouncing_enabled + ), + "ReachabilityDebouncingWindow": reachability_debouncing_window, + "WebhooksFromRestEnabled": serialize.boolean_to_string( + webhooks_from_rest_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + webhook_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param friendly_name: A string that you assign to describe the resource. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the webhook is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the webhook from being called. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "WebhookUrl": webhook_url, + "FriendlyName": friendly_name, + "ReachabilityWebhooksEnabled": serialize.boolean_to_string( + reachability_webhooks_enabled + ), + "AclEnabled": serialize.boolean_to_string(acl_enabled), + "ReachabilityDebouncingEnabled": serialize.boolean_to_string( + reachability_debouncing_enabled + ), + "ReachabilityDebouncingWindow": reachability_debouncing_window, + "WebhooksFromRestEnabled": serialize.boolean_to_string( + webhooks_from_rest_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def documents(self) -> DocumentList: + """ + Access the documents + """ + if self._documents is None: + self._documents = DocumentList( + self._version, + self._solution["sid"], + ) + return self._documents + + @property + def sync_lists(self) -> SyncListList: + """ + Access the sync_lists + """ + if self._sync_lists is None: + self._sync_lists = SyncListList( + self._version, + self._solution["sid"], + ) + return self._sync_lists + + @property + def sync_maps(self) -> SyncMapList: + """ + Access the sync_maps + """ + if self._sync_maps is None: + self._sync_maps = SyncMapList( + self._version, + self._solution["sid"], + ) + return self._sync_maps + + @property + def sync_streams(self) -> SyncStreamList: + """ + Access the sync_streams + """ + if self._sync_streams is None: + self._sync_streams = SyncStreamList( + self._version, + self._solution["sid"], + ) + return self._sync_streams + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.ServiceContext {}>".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.ServicePage>" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create( + self, + friendly_name: Union[str, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A string that you assign to describe the resource. + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the `webhook_url` is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the call to `webhook_url`. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "WebhookUrl": webhook_url, + "ReachabilityWebhooksEnabled": serialize.boolean_to_string( + reachability_webhooks_enabled + ), + "AclEnabled": serialize.boolean_to_string(acl_enabled), + "ReachabilityDebouncingEnabled": serialize.boolean_to_string( + reachability_debouncing_enabled + ), + "ReachabilityDebouncingWindow": reachability_debouncing_window, + "WebhooksFromRestEnabled": serialize.boolean_to_string( + webhooks_from_rest_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async( + self, + friendly_name: Union[str, object] = values.unset, + webhook_url: Union[str, object] = values.unset, + reachability_webhooks_enabled: Union[bool, object] = values.unset, + acl_enabled: Union[bool, object] = values.unset, + reachability_debouncing_enabled: Union[bool, object] = values.unset, + reachability_debouncing_window: Union[int, object] = values.unset, + webhooks_from_rest_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: A string that you assign to describe the resource. + :param webhook_url: The URL we should call when Sync objects are manipulated. + :param reachability_webhooks_enabled: Whether the service instance should call `webhook_url` when client endpoints connect to Sync. The default is `false`. + :param acl_enabled: Whether token identities in the Service must be granted access to Sync objects by using the [Permissions](https://www.twilio.com/docs/sync/api/sync-permissions) resource. + :param reachability_debouncing_enabled: Whether every `endpoint_disconnected` event should occur after a configurable delay. The default is `false`, where the `endpoint_disconnected` event occurs immediately after disconnection. When `true`, intervening reconnections can prevent the `endpoint_disconnected` event. + :param reachability_debouncing_window: The reachability event delay in milliseconds if `reachability_debouncing_enabled` = `true`. Must be between 1,000 and 30,000 and defaults to 5,000. This is the number of milliseconds after the last running client disconnects, and a Sync identity is declared offline, before the `webhook_url` is called if all endpoints remain offline. A reconnection from the same identity by any endpoint during this interval prevents the call to `webhook_url`. + :param webhooks_from_rest_enabled: Whether the Service instance should call `webhook_url` when the REST API is used to update Sync objects. The default is `false`. + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "WebhookUrl": webhook_url, + "ReachabilityWebhooksEnabled": serialize.boolean_to_string( + reachability_webhooks_enabled + ), + "AclEnabled": serialize.boolean_to_string(acl_enabled), + "ReachabilityDebouncingEnabled": serialize.boolean_to_string( + reachability_debouncing_enabled + ), + "ReachabilityDebouncingWindow": reachability_debouncing_window, + "WebhooksFromRestEnabled": serialize.boolean_to_string( + webhooks_from_rest_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The SID of the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The SID of the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.ServiceList>" diff --git a/twilio/rest/sync/v1/service/document/__init__.py b/twilio/rest/sync/v1/service/document/__init__.py new file mode 100644 index 0000000000..fe64f629a8 --- /dev/null +++ b/twilio/rest/sync/v1/service/document/__init__.py @@ -0,0 +1,723 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.sync.v1.service.document.document_permission import ( + DocumentPermissionList, +) + + +class DocumentInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Document resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource and can be up to 320 characters long. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Document resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar url: The absolute URL of the Document resource. + :ivar links: The URLs of resources related to the Sync Document. + :ivar revision: The current revision of the Sync Document, represented as a string. The `revision` property is used with conditional updates to ensure data consistency. + :ivar data: An arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :ivar date_expires: The date and time in GMT when the Sync Document expires and will be deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. If the Sync Document does not expire, this value is `null`. The Document resource might not be deleted immediately after it expires. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar created_by: The identity of the Sync Document's creator. If the Sync Document is created from the client SDK, the value matches the Access Token's `identity` field. If the Sync Document was created from the REST API, the value is `system`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.revision: Optional[str] = payload.get("revision") + self.data: Optional[Dict[str, object]] = payload.get("data") + self.date_expires: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expires") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[DocumentContext] = None + + @property + def _proxy(self) -> "DocumentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DocumentContext for this DocumentInstance + """ + if self._context is None: + self._context = DocumentContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the DocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "DocumentInstance": + """ + Fetch the DocumentInstance + + + :returns: The fetched DocumentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DocumentInstance": + """ + Asynchronous coroutine to fetch the DocumentInstance + + + :returns: The fetched DocumentInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> "DocumentInstance": + """ + Update the DocumentInstance + + :param if_match: The If-Match HTTP request header + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). + + :returns: The updated DocumentInstance + """ + return self._proxy.update( + if_match=if_match, + data=data, + ttl=ttl, + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> "DocumentInstance": + """ + Asynchronous coroutine to update the DocumentInstance + + :param if_match: The If-Match HTTP request header + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). + + :returns: The updated DocumentInstance + """ + return await self._proxy.update_async( + if_match=if_match, + data=data, + ttl=ttl, + ) + + @property + def document_permissions(self) -> DocumentPermissionList: + """ + Access the document_permissions + """ + return self._proxy.document_permissions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.DocumentInstance {}>".format(context) + + +class DocumentContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the DocumentContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Document resource to update. + :param sid: The SID of the Document resource to update. Can be the Document resource's `sid` or its `unique_name`. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Documents/{sid}".format(**self._solution) + + self._document_permissions: Optional[DocumentPermissionList] = None + + def delete(self) -> bool: + """ + Deletes the DocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> DocumentInstance: + """ + Fetch the DocumentInstance + + + :returns: The fetched DocumentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DocumentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> DocumentInstance: + """ + Asynchronous coroutine to fetch the DocumentInstance + + + :returns: The fetched DocumentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DocumentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> DocumentInstance: + """ + Update the DocumentInstance + + :param if_match: The If-Match HTTP request header + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). + + :returns: The updated DocumentInstance + """ + + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DocumentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> DocumentInstance: + """ + Asynchronous coroutine to update the DocumentInstance + + :param if_match: The If-Match HTTP request header + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (time-to-live). + + :returns: The updated DocumentInstance + """ + + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DocumentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def document_permissions(self) -> DocumentPermissionList: + """ + Access the document_permissions + """ + if self._document_permissions is None: + self._document_permissions = DocumentPermissionList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._document_permissions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.DocumentContext {}>".format(context) + + +class DocumentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DocumentInstance: + """ + Build an instance of DocumentInstance + + :param payload: Payload response from the API + """ + return DocumentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.DocumentPage>" + + +class DocumentList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the DocumentList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Document resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Documents".format(**self._solution) + + def create( + self, + unique_name: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> DocumentInstance: + """ + Create the DocumentInstance + + :param unique_name: An application-defined string that uniquely identifies the Sync Document + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document's time-to-live). + + :returns: The created DocumentInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Data": serialize.object(data), + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DocumentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> DocumentInstance: + """ + Asynchronously create the DocumentInstance + + :param unique_name: An application-defined string that uniquely identifies the Sync Document + :param data: A JSON string that represents an arbitrary, schema-less object that the Sync Document stores. Can be up to 16 KiB in length. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Document expires and is deleted (the Sync Document's time-to-live). + + :returns: The created DocumentInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Data": serialize.object(data), + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DocumentInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DocumentInstance]: + """ + Streams DocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DocumentInstance]: + """ + Asynchronously streams DocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DocumentInstance]: + """ + Lists DocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DocumentInstance]: + """ + Asynchronously lists DocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DocumentPage: + """ + Retrieve a single page of DocumentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DocumentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DocumentPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DocumentPage: + """ + Asynchronously retrieve a single page of DocumentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DocumentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DocumentPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DocumentPage: + """ + Retrieve a specific page of DocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DocumentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DocumentPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DocumentPage: + """ + Asynchronously retrieve a specific page of DocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DocumentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DocumentPage(self._version, response, self._solution) + + def get(self, sid: str) -> DocumentContext: + """ + Constructs a DocumentContext + + :param sid: The SID of the Document resource to update. Can be the Document resource's `sid` or its `unique_name`. + """ + return DocumentContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> DocumentContext: + """ + Constructs a DocumentContext + + :param sid: The SID of the Document resource to update. Can be the Document resource's `sid` or its `unique_name`. + """ + return DocumentContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.DocumentList>" diff --git a/twilio/rest/sync/v1/service/document/document_permission.py b/twilio/rest/sync/v1/service/document/document_permission.py new file mode 100644 index 0000000000..75a27c969a --- /dev/null +++ b/twilio/rest/sync/v1/service/document/document_permission.py @@ -0,0 +1,617 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DocumentPermissionInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Document Permission resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar document_sid: The SID of the Sync Document to which the Document Permission applies. + :ivar identity: The application-defined string that uniquely identifies the resource's User within the Service to an FPA token. + :ivar read: Whether the identity can read the Sync Document. + :ivar write: Whether the identity can update the Sync Document. + :ivar manage: Whether the identity can delete the Sync Document. + :ivar url: The absolute URL of the Sync Document Permission resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + document_sid: str, + identity: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.document_sid: Optional[str] = payload.get("document_sid") + self.identity: Optional[str] = payload.get("identity") + self.read: Optional[bool] = payload.get("read") + self.write: Optional[bool] = payload.get("write") + self.manage: Optional[bool] = payload.get("manage") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "document_sid": document_sid, + "identity": identity or self.identity, + } + self._context: Optional[DocumentPermissionContext] = None + + @property + def _proxy(self) -> "DocumentPermissionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DocumentPermissionContext for this DocumentPermissionInstance + """ + if self._context is None: + self._context = DocumentPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the DocumentPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DocumentPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "DocumentPermissionInstance": + """ + Fetch the DocumentPermissionInstance + + + :returns: The fetched DocumentPermissionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DocumentPermissionInstance": + """ + Asynchronous coroutine to fetch the DocumentPermissionInstance + + + :returns: The fetched DocumentPermissionInstance + """ + return await self._proxy.fetch_async() + + def update( + self, read: bool, write: bool, manage: bool + ) -> "DocumentPermissionInstance": + """ + Update the DocumentPermissionInstance + + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. + + :returns: The updated DocumentPermissionInstance + """ + return self._proxy.update( + read=read, + write=write, + manage=manage, + ) + + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> "DocumentPermissionInstance": + """ + Asynchronous coroutine to update the DocumentPermissionInstance + + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. + + :returns: The updated DocumentPermissionInstance + """ + return await self._proxy.update_async( + read=read, + write=write, + manage=manage, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.DocumentPermissionInstance {}>".format(context) + + +class DocumentPermissionContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, document_sid: str, identity: str + ): + """ + Initialize the DocumentPermissionContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Document Permission resource to update. + :param document_sid: The SID of the Sync Document with the Document Permission resource to update. Can be the Document resource's `sid` or its `unique_name`. + :param identity: The application-defined string that uniquely identifies the User's Document Permission resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "document_sid": document_sid, + "identity": identity, + } + self._uri = "/Services/{service_sid}/Documents/{document_sid}/Permissions/{identity}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the DocumentPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the DocumentPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> DocumentPermissionInstance: + """ + Fetch the DocumentPermissionInstance + + + :returns: The fetched DocumentPermissionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + + async def fetch_async(self) -> DocumentPermissionInstance: + """ + Asynchronous coroutine to fetch the DocumentPermissionInstance + + + :returns: The fetched DocumentPermissionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + + def update( + self, read: bool, write: bool, manage: bool + ) -> DocumentPermissionInstance: + """ + Update the DocumentPermissionInstance + + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. + + :returns: The updated DocumentPermissionInstance + """ + + data = values.of( + { + "Read": serialize.boolean_to_string(read), + "Write": serialize.boolean_to_string(write), + "Manage": serialize.boolean_to_string(manage), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> DocumentPermissionInstance: + """ + Asynchronous coroutine to update the DocumentPermissionInstance + + :param read: Whether the identity can read the Sync Document. Default value is `false`. + :param write: Whether the identity can update the Sync Document. Default value is `false`. + :param manage: Whether the identity can delete the Sync Document. Default value is `false`. + + :returns: The updated DocumentPermissionInstance + """ + + data = values.of( + { + "Read": serialize.boolean_to_string(read), + "Write": serialize.boolean_to_string(write), + "Manage": serialize.boolean_to_string(manage), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.DocumentPermissionContext {}>".format(context) + + +class DocumentPermissionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DocumentPermissionInstance: + """ + Build an instance of DocumentPermissionInstance + + :param payload: Payload response from the API + """ + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.DocumentPermissionPage>" + + +class DocumentPermissionList(ListResource): + + def __init__(self, version: Version, service_sid: str, document_sid: str): + """ + Initialize the DocumentPermissionList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Document Permission resources to read. + :param document_sid: The SID of the Sync Document with the Document Permission resources to read. Can be the Document resource's `sid` or its `unique_name`. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "document_sid": document_sid, + } + self._uri = ( + "/Services/{service_sid}/Documents/{document_sid}/Permissions".format( + **self._solution + ) + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DocumentPermissionInstance]: + """ + Streams DocumentPermissionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DocumentPermissionInstance]: + """ + Asynchronously streams DocumentPermissionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DocumentPermissionInstance]: + """ + Lists DocumentPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DocumentPermissionInstance]: + """ + Asynchronously lists DocumentPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DocumentPermissionPage: + """ + Retrieve a single page of DocumentPermissionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DocumentPermissionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DocumentPermissionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DocumentPermissionPage: + """ + Asynchronously retrieve a single page of DocumentPermissionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DocumentPermissionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DocumentPermissionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DocumentPermissionPage: + """ + Retrieve a specific page of DocumentPermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DocumentPermissionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DocumentPermissionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DocumentPermissionPage: + """ + Asynchronously retrieve a specific page of DocumentPermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DocumentPermissionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DocumentPermissionPage(self._version, response, self._solution) + + def get(self, identity: str) -> DocumentPermissionContext: + """ + Constructs a DocumentPermissionContext + + :param identity: The application-defined string that uniquely identifies the User's Document Permission resource to update. + """ + return DocumentPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=identity, + ) + + def __call__(self, identity: str) -> DocumentPermissionContext: + """ + Constructs a DocumentPermissionContext + + :param identity: The application-defined string that uniquely identifies the User's Document Permission resource to update. + """ + return DocumentPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=identity, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.DocumentPermissionList>" diff --git a/twilio/rest/sync/v1/service/sync_list/__init__.py b/twilio/rest/sync/v1/service/sync_list/__init__.py new file mode 100644 index 0000000000..1b8e54aff8 --- /dev/null +++ b/twilio/rest/sync/v1/service/sync_list/__init__.py @@ -0,0 +1,723 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.sync.v1.service.sync_list.sync_list_item import SyncListItemList +from twilio.rest.sync.v1.service.sync_list.sync_list_permission import ( + SyncListPermissionList, +) + + +class SyncListInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Sync List resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Sync List resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar url: The absolute URL of the Sync List resource. + :ivar links: The URLs of the Sync List's nested resources. + :ivar revision: The current revision of the Sync List, represented as a string. + :ivar date_expires: The date and time in GMT when the Sync List expires and will be deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. If the Sync List does not expire, this value is `null`. The Sync List might not be deleted immediately after it expires. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar created_by: The identity of the Sync List's creator. If the Sync List is created from the client SDK, the value matches the Access Token's `identity` field. If the Sync List was created from the REST API, the value is `system`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.revision: Optional[str] = payload.get("revision") + self.date_expires: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expires") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[SyncListContext] = None + + @property + def _proxy(self) -> "SyncListContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SyncListContext for this SyncListInstance + """ + if self._context is None: + self._context = SyncListContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SyncListInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncListInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SyncListInstance": + """ + Fetch the SyncListInstance + + + :returns: The fetched SyncListInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SyncListInstance": + """ + Asynchronous coroutine to fetch the SyncListInstance + + + :returns: The fetched SyncListInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncListInstance": + """ + Update the SyncListInstance + + :param ttl: An alias for `collection_ttl`. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: The updated SyncListInstance + """ + return self._proxy.update( + ttl=ttl, + collection_ttl=collection_ttl, + ) + + async def update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncListInstance": + """ + Asynchronous coroutine to update the SyncListInstance + + :param ttl: An alias for `collection_ttl`. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: The updated SyncListInstance + """ + return await self._proxy.update_async( + ttl=ttl, + collection_ttl=collection_ttl, + ) + + @property + def sync_list_items(self) -> SyncListItemList: + """ + Access the sync_list_items + """ + return self._proxy.sync_list_items + + @property + def sync_list_permissions(self) -> SyncListPermissionList: + """ + Access the sync_list_permissions + """ + return self._proxy.sync_list_permissions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.SyncListInstance {}>".format(context) + + +class SyncListContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the SyncListContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync List resource to update. + :param sid: The SID of the Sync List resource to update. Can be the Sync List resource's `sid` or its `unique_name`. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Lists/{sid}".format(**self._solution) + + self._sync_list_items: Optional[SyncListItemList] = None + self._sync_list_permissions: Optional[SyncListPermissionList] = None + + def delete(self) -> bool: + """ + Deletes the SyncListInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncListInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncListInstance: + """ + Fetch the SyncListInstance + + + :returns: The fetched SyncListInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SyncListInstance: + """ + Asynchronous coroutine to fetch the SyncListInstance + + + :returns: The fetched SyncListInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListInstance: + """ + Update the SyncListInstance + + :param ttl: An alias for `collection_ttl`. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: The updated SyncListInstance + """ + + data = values.of( + { + "Ttl": ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListInstance: + """ + Asynchronous coroutine to update the SyncListInstance + + :param ttl: An alias for `collection_ttl`. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: The updated SyncListInstance + """ + + data = values.of( + { + "Ttl": ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def sync_list_items(self) -> SyncListItemList: + """ + Access the sync_list_items + """ + if self._sync_list_items is None: + self._sync_list_items = SyncListItemList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._sync_list_items + + @property + def sync_list_permissions(self) -> SyncListPermissionList: + """ + Access the sync_list_permissions + """ + if self._sync_list_permissions is None: + self._sync_list_permissions = SyncListPermissionList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._sync_list_permissions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.SyncListContext {}>".format(context) + + +class SyncListPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SyncListInstance: + """ + Build an instance of SyncListInstance + + :param payload: Payload response from the API + """ + return SyncListInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.SyncListPage>" + + +class SyncListList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the SyncListList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync List resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Lists".format(**self._solution) + + def create( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListInstance: + """ + Create the SyncListInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: Alias for collection_ttl. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: The created SyncListInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Ttl": ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListInstance: + """ + Asynchronously create the SyncListInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: Alias for collection_ttl. If both are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync List expires (time-to-live) and is deleted. + + :returns: The created SyncListInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Ttl": ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SyncListInstance]: + """ + Streams SyncListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SyncListInstance]: + """ + Asynchronously streams SyncListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncListInstance]: + """ + Lists SyncListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncListInstance]: + """ + Asynchronously lists SyncListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncListPage: + """ + Retrieve a single page of SyncListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncListInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncListPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncListPage: + """ + Asynchronously retrieve a single page of SyncListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncListInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncListPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SyncListPage: + """ + Retrieve a specific page of SyncListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncListInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SyncListPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SyncListPage: + """ + Asynchronously retrieve a specific page of SyncListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncListInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncListPage(self._version, response, self._solution) + + def get(self, sid: str) -> SyncListContext: + """ + Constructs a SyncListContext + + :param sid: The SID of the Sync List resource to update. Can be the Sync List resource's `sid` or its `unique_name`. + """ + return SyncListContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> SyncListContext: + """ + Constructs a SyncListContext + + :param sid: The SID of the Sync List resource to update. Can be the Sync List resource's `sid` or its `unique_name`. + """ + return SyncListContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.SyncListList>" diff --git a/twilio/rest/sync/v1/service/sync_list/sync_list_item.py b/twilio/rest/sync/v1/service/sync_list/sync_list_item.py new file mode 100644 index 0000000000..61783aa525 --- /dev/null +++ b/twilio/rest/sync/v1/service/sync_list/sync_list_item.py @@ -0,0 +1,835 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SyncListItemInstance(InstanceResource): + + class QueryFromBoundType(object): + INCLUSIVE = "inclusive" + EXCLUSIVE = "exclusive" + + class QueryResultOrder(object): + ASC = "asc" + DESC = "desc" + + """ + :ivar index: The automatically generated index of the List Item. The `index` values of the List Items in a Sync List can have gaps in their sequence. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the List Item resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar list_sid: The SID of the Sync List that contains the List Item. + :ivar url: The absolute URL of the List Item resource. + :ivar revision: The current revision of the item, represented as a string. + :ivar data: An arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :ivar date_expires: The date and time in GMT when the List Item expires and will be deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. If the List Item does not expire, this value is `null`. The List Item resource might not be deleted immediately after it expires. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar created_by: The identity of the List Item's creator. If the item is created from the client SDK, the value matches the Access Token's `identity` field. If the item was created from the REST API, the value is `system`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + list_sid: str, + index: Optional[int] = None, + ): + super().__init__(version) + + self.index: Optional[int] = deserialize.integer(payload.get("index")) + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.list_sid: Optional[str] = payload.get("list_sid") + self.url: Optional[str] = payload.get("url") + self.revision: Optional[str] = payload.get("revision") + self.data: Optional[Dict[str, object]] = payload.get("data") + self.date_expires: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expires") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + + self._solution = { + "service_sid": service_sid, + "list_sid": list_sid, + "index": index or self.index, + } + self._context: Optional[SyncListItemContext] = None + + @property + def _proxy(self) -> "SyncListItemContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SyncListItemContext for this SyncListItemInstance + """ + if self._context is None: + self._context = SyncListItemContext( + self._version, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + return self._context + + def delete(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Deletes the SyncListItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + if_match=if_match, + ) + + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Asynchronous coroutine that deletes the SyncListItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + if_match=if_match, + ) + + def fetch(self) -> "SyncListItemInstance": + """ + Fetch the SyncListItemInstance + + + :returns: The fetched SyncListItemInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SyncListItemInstance": + """ + Asynchronous coroutine to fetch the SyncListItemInstance + + + :returns: The fetched SyncListItemInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncListItemInstance": + """ + Update the SyncListItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. This parameter can only be used when the List Item's `data` or `ttl` is updated in the same request. + + :returns: The updated SyncListItemInstance + """ + return self._proxy.update( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncListItemInstance": + """ + Asynchronous coroutine to update the SyncListItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. This parameter can only be used when the List Item's `data` or `ttl` is updated in the same request. + + :returns: The updated SyncListItemInstance + """ + return await self._proxy.update_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.SyncListItemInstance {}>".format(context) + + +class SyncListItemContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, list_sid: str, index: int): + """ + Initialize the SyncListItemContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync List Item resource to update. + :param list_sid: The SID of the Sync List with the Sync List Item resource to update. Can be the Sync List resource's `sid` or its `unique_name`. + :param index: The index of the Sync List Item resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "list_sid": list_sid, + "index": index, + } + self._uri = "/Services/{service_sid}/Lists/{list_sid}/Items/{index}".format( + **self._solution + ) + + def delete(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Deletes the SyncListItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Asynchronous coroutine that deletes the SyncListItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncListItemInstance: + """ + Fetch the SyncListItemInstance + + + :returns: The fetched SyncListItemInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + + async def fetch_async(self) -> SyncListItemInstance: + """ + Asynchronous coroutine to fetch the SyncListItemInstance + + + :returns: The fetched SyncListItemInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListItemInstance: + """ + Update the SyncListItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. This parameter can only be used when the List Item's `data` or `ttl` is updated in the same request. + + :returns: The updated SyncListItemInstance + """ + + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListItemInstance: + """ + Asynchronous coroutine to update the SyncListItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. This parameter can only be used when the List Item's `data` or `ttl` is updated in the same request. + + :returns: The updated SyncListItemInstance + """ + + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.SyncListItemContext {}>".format(context) + + +class SyncListItemPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SyncListItemInstance: + """ + Build an instance of SyncListItemInstance + + :param payload: Payload response from the API + """ + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.SyncListItemPage>" + + +class SyncListItemList(ListResource): + + def __init__(self, version: Version, service_sid: str, list_sid: str): + """ + Initialize the SyncListItemList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the List Item resources to read. + :param list_sid: The SID of the Sync List with the List Items to read. Can be the Sync List resource's `sid` or its `unique_name`. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "list_sid": list_sid, + } + self._uri = "/Services/{service_sid}/Lists/{list_sid}/Items".format( + **self._solution + ) + + def create( + self, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListItemInstance: + """ + Create the SyncListItemInstance + + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. + + :returns: The created SyncListItemInstance + """ + + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + ) + + async def create_async( + self, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncListItemInstance: + """ + Asynchronously create the SyncListItemInstance + + :param data: A JSON string that represents an arbitrary, schema-less object that the List Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the List Item's parent Sync List expires (time-to-live) and is deleted. + + :returns: The created SyncListItemInstance + """ + + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + ) + + def stream( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SyncListItemInstance]: + """ + Streams SyncListItemInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "SyncListItemInstance.QueryResultOrder" order: How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. + :param str from_: The `index` of the first Sync List Item resource to read. See also `bounds`. + :param "SyncListItemInstance.QueryFromBoundType" bounds: Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SyncListItemInstance]: + """ + Asynchronously streams SyncListItemInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "SyncListItemInstance.QueryResultOrder" order: How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. + :param str from_: The `index` of the first Sync List Item resource to read. See also `bounds`. + :param "SyncListItemInstance.QueryFromBoundType" bounds: Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncListItemInstance]: + """ + Lists SyncListItemInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "SyncListItemInstance.QueryResultOrder" order: How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. + :param str from_: The `index` of the first Sync List Item resource to read. See also `bounds`. + :param "SyncListItemInstance.QueryFromBoundType" bounds: Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + order=order, + from_=from_, + bounds=bounds, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncListItemInstance]: + """ + Asynchronously lists SyncListItemInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "SyncListItemInstance.QueryResultOrder" order: How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. + :param str from_: The `index` of the first Sync List Item resource to read. See also `bounds`. + :param "SyncListItemInstance.QueryFromBoundType" bounds: Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + order=order, + from_=from_, + bounds=bounds, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncListItemPage: + """ + Retrieve a single page of SyncListItemInstance records from the API. + Request is executed immediately + + :param order: How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. + :param from_: The `index` of the first Sync List Item resource to read. See also `bounds`. + :param bounds: Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncListItemInstance + """ + data = values.of( + { + "Order": order, + "From": from_, + "Bounds": bounds, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncListItemPage(self._version, response, self._solution) + + async def page_async( + self, + order: Union["SyncListItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncListItemInstance.QueryFromBoundType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncListItemPage: + """ + Asynchronously retrieve a single page of SyncListItemInstance records from the API. + Request is executed immediately + + :param order: How to order the List Items returned by their `index` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. + :param from_: The `index` of the first Sync List Item resource to read. See also `bounds`. + :param bounds: Whether to include the List Item referenced by the `from` parameter. Can be: `inclusive` to include the List Item referenced by the `from` parameter or `exclusive` to start with the next List Item. The default value is `inclusive`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncListItemInstance + """ + data = values.of( + { + "Order": order, + "From": from_, + "Bounds": bounds, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncListItemPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SyncListItemPage: + """ + Retrieve a specific page of SyncListItemInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncListItemInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SyncListItemPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SyncListItemPage: + """ + Asynchronously retrieve a specific page of SyncListItemInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncListItemInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncListItemPage(self._version, response, self._solution) + + def get(self, index: int) -> SyncListItemContext: + """ + Constructs a SyncListItemContext + + :param index: The index of the Sync List Item resource to update. + """ + return SyncListItemContext( + self._version, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=index, + ) + + def __call__(self, index: int) -> SyncListItemContext: + """ + Constructs a SyncListItemContext + + :param index: The index of the Sync List Item resource to update. + """ + return SyncListItemContext( + self._version, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=index, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.SyncListItemList>" diff --git a/twilio/rest/sync/v1/service/sync_list/sync_list_permission.py b/twilio/rest/sync/v1/service/sync_list/sync_list_permission.py new file mode 100644 index 0000000000..f1eb853468 --- /dev/null +++ b/twilio/rest/sync/v1/service/sync_list/sync_list_permission.py @@ -0,0 +1,617 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SyncListPermissionInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Sync List Permission resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar list_sid: The SID of the Sync List to which the Permission applies. + :ivar identity: The application-defined string that uniquely identifies the resource's User within the Service to an FPA token. + :ivar read: Whether the identity can read the Sync List and its Items. + :ivar write: Whether the identity can create, update, and delete Items in the Sync List. + :ivar manage: Whether the identity can delete the Sync List. + :ivar url: The absolute URL of the Sync List Permission resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + list_sid: str, + identity: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.list_sid: Optional[str] = payload.get("list_sid") + self.identity: Optional[str] = payload.get("identity") + self.read: Optional[bool] = payload.get("read") + self.write: Optional[bool] = payload.get("write") + self.manage: Optional[bool] = payload.get("manage") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "list_sid": list_sid, + "identity": identity or self.identity, + } + self._context: Optional[SyncListPermissionContext] = None + + @property + def _proxy(self) -> "SyncListPermissionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SyncListPermissionContext for this SyncListPermissionInstance + """ + if self._context is None: + self._context = SyncListPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SyncListPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncListPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SyncListPermissionInstance": + """ + Fetch the SyncListPermissionInstance + + + :returns: The fetched SyncListPermissionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SyncListPermissionInstance": + """ + Asynchronous coroutine to fetch the SyncListPermissionInstance + + + :returns: The fetched SyncListPermissionInstance + """ + return await self._proxy.fetch_async() + + def update( + self, read: bool, write: bool, manage: bool + ) -> "SyncListPermissionInstance": + """ + Update the SyncListPermissionInstance + + :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. + :param manage: Whether the identity can delete the Sync List. Default value is `false`. + + :returns: The updated SyncListPermissionInstance + """ + return self._proxy.update( + read=read, + write=write, + manage=manage, + ) + + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> "SyncListPermissionInstance": + """ + Asynchronous coroutine to update the SyncListPermissionInstance + + :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. + :param manage: Whether the identity can delete the Sync List. Default value is `false`. + + :returns: The updated SyncListPermissionInstance + """ + return await self._proxy.update_async( + read=read, + write=write, + manage=manage, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.SyncListPermissionInstance {}>".format(context) + + +class SyncListPermissionContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, list_sid: str, identity: str + ): + """ + Initialize the SyncListPermissionContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync List Permission resource to update. + :param list_sid: The SID of the Sync List with the Sync List Permission resource to update. Can be the Sync List resource's `sid` or its `unique_name`. + :param identity: The application-defined string that uniquely identifies the User's Sync List Permission resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "list_sid": list_sid, + "identity": identity, + } + self._uri = ( + "/Services/{service_sid}/Lists/{list_sid}/Permissions/{identity}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the SyncListPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncListPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncListPermissionInstance: + """ + Fetch the SyncListPermissionInstance + + + :returns: The fetched SyncListPermissionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + + async def fetch_async(self) -> SyncListPermissionInstance: + """ + Asynchronous coroutine to fetch the SyncListPermissionInstance + + + :returns: The fetched SyncListPermissionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + + def update( + self, read: bool, write: bool, manage: bool + ) -> SyncListPermissionInstance: + """ + Update the SyncListPermissionInstance + + :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. + :param manage: Whether the identity can delete the Sync List. Default value is `false`. + + :returns: The updated SyncListPermissionInstance + """ + + data = values.of( + { + "Read": serialize.boolean_to_string(read), + "Write": serialize.boolean_to_string(write), + "Manage": serialize.boolean_to_string(manage), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> SyncListPermissionInstance: + """ + Asynchronous coroutine to update the SyncListPermissionInstance + + :param read: Whether the identity can read the Sync List and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync List. Default value is `false`. + :param manage: Whether the identity can delete the Sync List. Default value is `false`. + + :returns: The updated SyncListPermissionInstance + """ + + data = values.of( + { + "Read": serialize.boolean_to_string(read), + "Write": serialize.boolean_to_string(write), + "Manage": serialize.boolean_to_string(manage), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.SyncListPermissionContext {}>".format(context) + + +class SyncListPermissionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SyncListPermissionInstance: + """ + Build an instance of SyncListPermissionInstance + + :param payload: Payload response from the API + """ + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.SyncListPermissionPage>" + + +class SyncListPermissionList(ListResource): + + def __init__(self, version: Version, service_sid: str, list_sid: str): + """ + Initialize the SyncListPermissionList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync List Permission resources to read. + :param list_sid: The SID of the Sync List with the Sync List Permission resources to read. Can be the Sync List resource's `sid` or its `unique_name`. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "list_sid": list_sid, + } + self._uri = "/Services/{service_sid}/Lists/{list_sid}/Permissions".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SyncListPermissionInstance]: + """ + Streams SyncListPermissionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SyncListPermissionInstance]: + """ + Asynchronously streams SyncListPermissionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncListPermissionInstance]: + """ + Lists SyncListPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncListPermissionInstance]: + """ + Asynchronously lists SyncListPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncListPermissionPage: + """ + Retrieve a single page of SyncListPermissionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncListPermissionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncListPermissionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncListPermissionPage: + """ + Asynchronously retrieve a single page of SyncListPermissionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncListPermissionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncListPermissionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SyncListPermissionPage: + """ + Retrieve a specific page of SyncListPermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncListPermissionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SyncListPermissionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SyncListPermissionPage: + """ + Asynchronously retrieve a specific page of SyncListPermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncListPermissionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncListPermissionPage(self._version, response, self._solution) + + def get(self, identity: str) -> SyncListPermissionContext: + """ + Constructs a SyncListPermissionContext + + :param identity: The application-defined string that uniquely identifies the User's Sync List Permission resource to update. + """ + return SyncListPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=identity, + ) + + def __call__(self, identity: str) -> SyncListPermissionContext: + """ + Constructs a SyncListPermissionContext + + :param identity: The application-defined string that uniquely identifies the User's Sync List Permission resource to update. + """ + return SyncListPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=identity, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.SyncListPermissionList>" diff --git a/twilio/rest/sync/v1/service/sync_map/__init__.py b/twilio/rest/sync/v1/service/sync_map/__init__.py new file mode 100644 index 0000000000..c6bb1ce556 --- /dev/null +++ b/twilio/rest/sync/v1/service/sync_map/__init__.py @@ -0,0 +1,723 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.sync.v1.service.sync_map.sync_map_item import SyncMapItemList +from twilio.rest.sync.v1.service.sync_map.sync_map_permission import ( + SyncMapPermissionList, +) + + +class SyncMapInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Sync Map resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Sync Map resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar url: The absolute URL of the Sync Map resource. + :ivar links: The URLs of the Sync Map's nested resources. + :ivar revision: The current revision of the Sync Map, represented as a string. + :ivar date_expires: The date and time in GMT when the Sync Map expires and will be deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. If the Sync Map does not expire, this value is `null`. The Sync Map might not be deleted immediately after it expires. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar created_by: The identity of the Sync Map's creator. If the Sync Map is created from the client SDK, the value matches the Access Token's `identity` field. If the Sync Map was created from the REST API, the value is `system`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.revision: Optional[str] = payload.get("revision") + self.date_expires: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expires") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[SyncMapContext] = None + + @property + def _proxy(self) -> "SyncMapContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SyncMapContext for this SyncMapInstance + """ + if self._context is None: + self._context = SyncMapContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SyncMapInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncMapInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SyncMapInstance": + """ + Fetch the SyncMapInstance + + + :returns: The fetched SyncMapInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SyncMapInstance": + """ + Asynchronous coroutine to fetch the SyncMapInstance + + + :returns: The fetched SyncMapInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncMapInstance": + """ + Update the SyncMapInstance + + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: The updated SyncMapInstance + """ + return self._proxy.update( + ttl=ttl, + collection_ttl=collection_ttl, + ) + + async def update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncMapInstance": + """ + Asynchronous coroutine to update the SyncMapInstance + + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: The updated SyncMapInstance + """ + return await self._proxy.update_async( + ttl=ttl, + collection_ttl=collection_ttl, + ) + + @property + def sync_map_items(self) -> SyncMapItemList: + """ + Access the sync_map_items + """ + return self._proxy.sync_map_items + + @property + def sync_map_permissions(self) -> SyncMapPermissionList: + """ + Access the sync_map_permissions + """ + return self._proxy.sync_map_permissions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.SyncMapInstance {}>".format(context) + + +class SyncMapContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the SyncMapContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync Map resource to update. + :param sid: The SID of the Sync Map resource to update. Can be the Sync Map's `sid` or its `unique_name`. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Maps/{sid}".format(**self._solution) + + self._sync_map_items: Optional[SyncMapItemList] = None + self._sync_map_permissions: Optional[SyncMapPermissionList] = None + + def delete(self) -> bool: + """ + Deletes the SyncMapInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncMapInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncMapInstance: + """ + Fetch the SyncMapInstance + + + :returns: The fetched SyncMapInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SyncMapInstance: + """ + Asynchronous coroutine to fetch the SyncMapInstance + + + :returns: The fetched SyncMapInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapInstance: + """ + Update the SyncMapInstance + + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: The updated SyncMapInstance + """ + + data = values.of( + { + "Ttl": ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapInstance: + """ + Asynchronous coroutine to update the SyncMapInstance + + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: The updated SyncMapInstance + """ + + data = values.of( + { + "Ttl": ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def sync_map_items(self) -> SyncMapItemList: + """ + Access the sync_map_items + """ + if self._sync_map_items is None: + self._sync_map_items = SyncMapItemList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._sync_map_items + + @property + def sync_map_permissions(self) -> SyncMapPermissionList: + """ + Access the sync_map_permissions + """ + if self._sync_map_permissions is None: + self._sync_map_permissions = SyncMapPermissionList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._sync_map_permissions + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.SyncMapContext {}>".format(context) + + +class SyncMapPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SyncMapInstance: + """ + Build an instance of SyncMapInstance + + :param payload: Payload response from the API + """ + return SyncMapInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.SyncMapPage>" + + +class SyncMapList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the SyncMapList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync Map resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Maps".format(**self._solution) + + def create( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapInstance: + """ + Create the SyncMapInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: The created SyncMapInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Ttl": ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapInstance: + """ + Asynchronously create the SyncMapInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: An alias for `collection_ttl`. If both parameters are provided, this value is ignored. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Sync Map expires (time-to-live) and is deleted. + + :returns: The created SyncMapInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Ttl": ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SyncMapInstance]: + """ + Streams SyncMapInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SyncMapInstance]: + """ + Asynchronously streams SyncMapInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncMapInstance]: + """ + Lists SyncMapInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncMapInstance]: + """ + Asynchronously lists SyncMapInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncMapPage: + """ + Retrieve a single page of SyncMapInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncMapInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncMapPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncMapPage: + """ + Asynchronously retrieve a single page of SyncMapInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncMapInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncMapPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SyncMapPage: + """ + Retrieve a specific page of SyncMapInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncMapInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SyncMapPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SyncMapPage: + """ + Asynchronously retrieve a specific page of SyncMapInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncMapInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncMapPage(self._version, response, self._solution) + + def get(self, sid: str) -> SyncMapContext: + """ + Constructs a SyncMapContext + + :param sid: The SID of the Sync Map resource to update. Can be the Sync Map's `sid` or its `unique_name`. + """ + return SyncMapContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> SyncMapContext: + """ + Constructs a SyncMapContext + + :param sid: The SID of the Sync Map resource to update. Can be the Sync Map's `sid` or its `unique_name`. + """ + return SyncMapContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.SyncMapList>" diff --git a/twilio/rest/sync/v1/service/sync_map/sync_map_item.py b/twilio/rest/sync/v1/service/sync_map/sync_map_item.py new file mode 100644 index 0000000000..4939694026 --- /dev/null +++ b/twilio/rest/sync/v1/service/sync_map/sync_map_item.py @@ -0,0 +1,841 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SyncMapItemInstance(InstanceResource): + + class QueryFromBoundType(object): + INCLUSIVE = "inclusive" + EXCLUSIVE = "exclusive" + + class QueryResultOrder(object): + ASC = "asc" + DESC = "desc" + + """ + :ivar key: The unique, user-defined key for the Map Item. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Map Item resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar map_sid: The SID of the Sync Map that contains the Map Item. + :ivar url: The absolute URL of the Map Item resource. + :ivar revision: The current revision of the Map Item, represented as a string. + :ivar data: An arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :ivar date_expires: The date and time in GMT when the Map Item expires and will be deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. If the Map Item does not expire, this value is `null`. The Map Item might not be deleted immediately after it expires. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar created_by: The identity of the Map Item's creator. If the Map Item is created from the client SDK, the value matches the Access Token's `identity` field. If the Map Item was created from the REST API, the value is `system`. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + map_sid: str, + key: Optional[str] = None, + ): + super().__init__(version) + + self.key: Optional[str] = payload.get("key") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.map_sid: Optional[str] = payload.get("map_sid") + self.url: Optional[str] = payload.get("url") + self.revision: Optional[str] = payload.get("revision") + self.data: Optional[Dict[str, object]] = payload.get("data") + self.date_expires: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expires") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + + self._solution = { + "service_sid": service_sid, + "map_sid": map_sid, + "key": key or self.key, + } + self._context: Optional[SyncMapItemContext] = None + + @property + def _proxy(self) -> "SyncMapItemContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SyncMapItemContext for this SyncMapItemInstance + """ + if self._context is None: + self._context = SyncMapItemContext( + self._version, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + return self._context + + def delete(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Deletes the SyncMapItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + if_match=if_match, + ) + + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Asynchronous coroutine that deletes the SyncMapItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + if_match=if_match, + ) + + def fetch(self) -> "SyncMapItemInstance": + """ + Fetch the SyncMapItemInstance + + + :returns: The fetched SyncMapItemInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SyncMapItemInstance": + """ + Asynchronous coroutine to fetch the SyncMapItemInstance + + + :returns: The fetched SyncMapItemInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncMapItemInstance": + """ + Update the SyncMapItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. This parameter can only be used when the Map Item's `data` or `ttl` is updated in the same request. + + :returns: The updated SyncMapItemInstance + """ + return self._proxy.update( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> "SyncMapItemInstance": + """ + Asynchronous coroutine to update the SyncMapItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. This parameter can only be used when the Map Item's `data` or `ttl` is updated in the same request. + + :returns: The updated SyncMapItemInstance + """ + return await self._proxy.update_async( + if_match=if_match, + data=data, + ttl=ttl, + item_ttl=item_ttl, + collection_ttl=collection_ttl, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.SyncMapItemInstance {}>".format(context) + + +class SyncMapItemContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, map_sid: str, key: str): + """ + Initialize the SyncMapItemContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync Map Item resource to update. + :param map_sid: The SID of the Sync Map with the Sync Map Item resource to update. Can be the Sync Map resource's `sid` or its `unique_name`. + :param key: The `key` value of the Sync Map Item resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "map_sid": map_sid, + "key": key, + } + self._uri = "/Services/{service_sid}/Maps/{map_sid}/Items/{key}".format( + **self._solution + ) + + def delete(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Deletes the SyncMapItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Asynchronous coroutine that deletes the SyncMapItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncMapItemInstance: + """ + Fetch the SyncMapItemInstance + + + :returns: The fetched SyncMapItemInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + + async def fetch_async(self) -> SyncMapItemInstance: + """ + Asynchronous coroutine to fetch the SyncMapItemInstance + + + :returns: The fetched SyncMapItemInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapItemInstance: + """ + Update the SyncMapItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. This parameter can only be used when the Map Item's `data` or `ttl` is updated in the same request. + + :returns: The updated SyncMapItemInstance + """ + + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + data: Union[object, object] = values.unset, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapItemInstance: + """ + Asynchronous coroutine to update the SyncMapItemInstance + + :param if_match: If provided, applies this mutation if (and only if) the “revision” field of this [map item] matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. This parameter can only be used when the Map Item's `data` or `ttl` is updated in the same request. + + :returns: The updated SyncMapItemInstance + """ + + data = values.of( + { + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.SyncMapItemContext {}>".format(context) + + +class SyncMapItemPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SyncMapItemInstance: + """ + Build an instance of SyncMapItemInstance + + :param payload: Payload response from the API + """ + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.SyncMapItemPage>" + + +class SyncMapItemList(ListResource): + + def __init__(self, version: Version, service_sid: str, map_sid: str): + """ + Initialize the SyncMapItemList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Map Item resources to read. + :param map_sid: The SID of the Sync Map with the Sync Map Item resource to fetch. Can be the Sync Map resource's `sid` or its `unique_name`. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "map_sid": map_sid, + } + self._uri = "/Services/{service_sid}/Maps/{map_sid}/Items".format( + **self._solution + ) + + def create( + self, + key: str, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapItemInstance: + """ + Create the SyncMapItemInstance + + :param key: The unique, user-defined key for the Map Item. Can be up to 320 characters long. + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. + + :returns: The created SyncMapItemInstance + """ + + data = values.of( + { + "Key": key, + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + ) + + async def create_async( + self, + key: str, + data: object, + ttl: Union[int, object] = values.unset, + item_ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> SyncMapItemInstance: + """ + Asynchronously create the SyncMapItemInstance + + :param key: The unique, user-defined key for the Map Item. Can be up to 320 characters long. + :param data: A JSON string that represents an arbitrary, schema-less object that the Map Item stores. Can be up to 16 KiB in length. + :param ttl: An alias for `item_ttl`. If both parameters are provided, this value is ignored. + :param item_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item expires (time-to-live) and is deleted. + :param collection_ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Map Item's parent Sync Map expires (time-to-live) and is deleted. + + :returns: The created SyncMapItemInstance + """ + + data = values.of( + { + "Key": key, + "Data": serialize.object(data), + "Ttl": ttl, + "ItemTtl": item_ttl, + "CollectionTtl": collection_ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + ) + + def stream( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SyncMapItemInstance]: + """ + Streams SyncMapItemInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "SyncMapItemInstance.QueryResultOrder" order: How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. + :param str from_: The `key` of the first Sync Map Item resource to read. See also `bounds`. + :param "SyncMapItemInstance.QueryFromBoundType" bounds: Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SyncMapItemInstance]: + """ + Asynchronously streams SyncMapItemInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "SyncMapItemInstance.QueryResultOrder" order: How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. + :param str from_: The `key` of the first Sync Map Item resource to read. See also `bounds`. + :param "SyncMapItemInstance.QueryFromBoundType" bounds: Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + order=order, from_=from_, bounds=bounds, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncMapItemInstance]: + """ + Lists SyncMapItemInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "SyncMapItemInstance.QueryResultOrder" order: How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. + :param str from_: The `key` of the first Sync Map Item resource to read. See also `bounds`. + :param "SyncMapItemInstance.QueryFromBoundType" bounds: Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + order=order, + from_=from_, + bounds=bounds, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncMapItemInstance]: + """ + Asynchronously lists SyncMapItemInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "SyncMapItemInstance.QueryResultOrder" order: How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. + :param str from_: The `key` of the first Sync Map Item resource to read. See also `bounds`. + :param "SyncMapItemInstance.QueryFromBoundType" bounds: Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + order=order, + from_=from_, + bounds=bounds, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncMapItemPage: + """ + Retrieve a single page of SyncMapItemInstance records from the API. + Request is executed immediately + + :param order: How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. + :param from_: The `key` of the first Sync Map Item resource to read. See also `bounds`. + :param bounds: Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncMapItemInstance + """ + data = values.of( + { + "Order": order, + "From": from_, + "Bounds": bounds, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncMapItemPage(self._version, response, self._solution) + + async def page_async( + self, + order: Union["SyncMapItemInstance.QueryResultOrder", object] = values.unset, + from_: Union[str, object] = values.unset, + bounds: Union["SyncMapItemInstance.QueryFromBoundType", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncMapItemPage: + """ + Asynchronously retrieve a single page of SyncMapItemInstance records from the API. + Request is executed immediately + + :param order: How to order the Map Items returned by their `key` value. Can be: `asc` (ascending) or `desc` (descending) and the default is ascending. Map Items are [ordered lexicographically](https://en.wikipedia.org/wiki/Lexicographical_order) by Item key. + :param from_: The `key` of the first Sync Map Item resource to read. See also `bounds`. + :param bounds: Whether to include the Map Item referenced by the `from` parameter. Can be: `inclusive` to include the Map Item referenced by the `from` parameter or `exclusive` to start with the next Map Item. The default value is `inclusive`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncMapItemInstance + """ + data = values.of( + { + "Order": order, + "From": from_, + "Bounds": bounds, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncMapItemPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SyncMapItemPage: + """ + Retrieve a specific page of SyncMapItemInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncMapItemInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SyncMapItemPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SyncMapItemPage: + """ + Asynchronously retrieve a specific page of SyncMapItemInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncMapItemInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncMapItemPage(self._version, response, self._solution) + + def get(self, key: str) -> SyncMapItemContext: + """ + Constructs a SyncMapItemContext + + :param key: The `key` value of the Sync Map Item resource to update. + """ + return SyncMapItemContext( + self._version, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=key, + ) + + def __call__(self, key: str) -> SyncMapItemContext: + """ + Constructs a SyncMapItemContext + + :param key: The `key` value of the Sync Map Item resource to update. + """ + return SyncMapItemContext( + self._version, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=key, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.SyncMapItemList>" diff --git a/twilio/rest/sync/v1/service/sync_map/sync_map_permission.py b/twilio/rest/sync/v1/service/sync_map/sync_map_permission.py new file mode 100644 index 0000000000..910560add0 --- /dev/null +++ b/twilio/rest/sync/v1/service/sync_map/sync_map_permission.py @@ -0,0 +1,615 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SyncMapPermissionInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Sync Map Permission resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar map_sid: The SID of the Sync Map to which the Permission applies. + :ivar identity: The application-defined string that uniquely identifies the resource's User within the Service to an FPA token. + :ivar read: Whether the identity can read the Sync Map and its Items. + :ivar write: Whether the identity can create, update, and delete Items in the Sync Map. + :ivar manage: Whether the identity can delete the Sync Map. + :ivar url: The absolute URL of the Sync Map Permission resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + map_sid: str, + identity: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.map_sid: Optional[str] = payload.get("map_sid") + self.identity: Optional[str] = payload.get("identity") + self.read: Optional[bool] = payload.get("read") + self.write: Optional[bool] = payload.get("write") + self.manage: Optional[bool] = payload.get("manage") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "map_sid": map_sid, + "identity": identity or self.identity, + } + self._context: Optional[SyncMapPermissionContext] = None + + @property + def _proxy(self) -> "SyncMapPermissionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SyncMapPermissionContext for this SyncMapPermissionInstance + """ + if self._context is None: + self._context = SyncMapPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SyncMapPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncMapPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SyncMapPermissionInstance": + """ + Fetch the SyncMapPermissionInstance + + + :returns: The fetched SyncMapPermissionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SyncMapPermissionInstance": + """ + Asynchronous coroutine to fetch the SyncMapPermissionInstance + + + :returns: The fetched SyncMapPermissionInstance + """ + return await self._proxy.fetch_async() + + def update( + self, read: bool, write: bool, manage: bool + ) -> "SyncMapPermissionInstance": + """ + Update the SyncMapPermissionInstance + + :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. + :param manage: Whether the identity can delete the Sync Map. Default value is `false`. + + :returns: The updated SyncMapPermissionInstance + """ + return self._proxy.update( + read=read, + write=write, + manage=manage, + ) + + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> "SyncMapPermissionInstance": + """ + Asynchronous coroutine to update the SyncMapPermissionInstance + + :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. + :param manage: Whether the identity can delete the Sync Map. Default value is `false`. + + :returns: The updated SyncMapPermissionInstance + """ + return await self._proxy.update_async( + read=read, + write=write, + manage=manage, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.SyncMapPermissionInstance {}>".format(context) + + +class SyncMapPermissionContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, map_sid: str, identity: str): + """ + Initialize the SyncMapPermissionContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync Map Permission resource to update. Can be the Service's `sid` value or `default`. + :param map_sid: The SID of the Sync Map with the Sync Map Permission resource to update. Can be the Sync Map resource's `sid` or its `unique_name`. + :param identity: The application-defined string that uniquely identifies the User's Sync Map Permission resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "map_sid": map_sid, + "identity": identity, + } + self._uri = ( + "/Services/{service_sid}/Maps/{map_sid}/Permissions/{identity}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the SyncMapPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncMapPermissionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncMapPermissionInstance: + """ + Fetch the SyncMapPermissionInstance + + + :returns: The fetched SyncMapPermissionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + + async def fetch_async(self) -> SyncMapPermissionInstance: + """ + Asynchronous coroutine to fetch the SyncMapPermissionInstance + + + :returns: The fetched SyncMapPermissionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + + def update( + self, read: bool, write: bool, manage: bool + ) -> SyncMapPermissionInstance: + """ + Update the SyncMapPermissionInstance + + :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. + :param manage: Whether the identity can delete the Sync Map. Default value is `false`. + + :returns: The updated SyncMapPermissionInstance + """ + + data = values.of( + { + "Read": serialize.boolean_to_string(read), + "Write": serialize.boolean_to_string(write), + "Manage": serialize.boolean_to_string(manage), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + + async def update_async( + self, read: bool, write: bool, manage: bool + ) -> SyncMapPermissionInstance: + """ + Asynchronous coroutine to update the SyncMapPermissionInstance + + :param read: Whether the identity can read the Sync Map and its Items. Default value is `false`. + :param write: Whether the identity can create, update, and delete Items in the Sync Map. Default value is `false`. + :param manage: Whether the identity can delete the Sync Map. Default value is `false`. + + :returns: The updated SyncMapPermissionInstance + """ + + data = values.of( + { + "Read": serialize.boolean_to_string(read), + "Write": serialize.boolean_to_string(write), + "Manage": serialize.boolean_to_string(manage), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.SyncMapPermissionContext {}>".format(context) + + +class SyncMapPermissionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SyncMapPermissionInstance: + """ + Build an instance of SyncMapPermissionInstance + + :param payload: Payload response from the API + """ + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.SyncMapPermissionPage>" + + +class SyncMapPermissionList(ListResource): + + def __init__(self, version: Version, service_sid: str, map_sid: str): + """ + Initialize the SyncMapPermissionList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync Map Permission resources to read. Can be the Service's `sid` value or `default`. + :param map_sid: The SID of the Sync Map with the Permission resources to read. Can be the Sync Map resource's `sid` or its `unique_name`. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "map_sid": map_sid, + } + self._uri = "/Services/{service_sid}/Maps/{map_sid}/Permissions".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SyncMapPermissionInstance]: + """ + Streams SyncMapPermissionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SyncMapPermissionInstance]: + """ + Asynchronously streams SyncMapPermissionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncMapPermissionInstance]: + """ + Lists SyncMapPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncMapPermissionInstance]: + """ + Asynchronously lists SyncMapPermissionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncMapPermissionPage: + """ + Retrieve a single page of SyncMapPermissionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncMapPermissionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncMapPermissionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncMapPermissionPage: + """ + Asynchronously retrieve a single page of SyncMapPermissionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncMapPermissionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncMapPermissionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SyncMapPermissionPage: + """ + Retrieve a specific page of SyncMapPermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncMapPermissionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SyncMapPermissionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SyncMapPermissionPage: + """ + Asynchronously retrieve a specific page of SyncMapPermissionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncMapPermissionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncMapPermissionPage(self._version, response, self._solution) + + def get(self, identity: str) -> SyncMapPermissionContext: + """ + Constructs a SyncMapPermissionContext + + :param identity: The application-defined string that uniquely identifies the User's Sync Map Permission resource to update. + """ + return SyncMapPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=identity, + ) + + def __call__(self, identity: str) -> SyncMapPermissionContext: + """ + Constructs a SyncMapPermissionContext + + :param identity: The application-defined string that uniquely identifies the User's Sync Map Permission resource to update. + """ + return SyncMapPermissionContext( + self._version, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=identity, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.SyncMapPermissionList>" diff --git a/twilio/rest/sync/v1/service/sync_stream/__init__.py b/twilio/rest/sync/v1/service/sync_stream/__init__.py new file mode 100644 index 0000000000..a7f4128e05 --- /dev/null +++ b/twilio/rest/sync/v1/service/sync_stream/__init__.py @@ -0,0 +1,671 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.sync.v1.service.sync_stream.stream_message import StreamMessageList + + +class SyncStreamInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Sync Stream resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Sync Stream resource. + :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. + :ivar url: The absolute URL of the Message Stream resource. + :ivar links: The URLs of the Stream's nested resources. + :ivar date_expires: The date and time in GMT when the Message Stream expires and will be deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. If the Message Stream does not expire, this value is `null`. The Stream might not be deleted immediately after it expires. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar created_by: The identity of the Stream's creator. If the Stream is created from the client SDK, the value matches the Access Token's `identity` field. If the Stream was created from the REST API, the value is 'system'. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.date_expires: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expires") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.created_by: Optional[str] = payload.get("created_by") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[SyncStreamContext] = None + + @property + def _proxy(self) -> "SyncStreamContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SyncStreamContext for this SyncStreamInstance + """ + if self._context is None: + self._context = SyncStreamContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SyncStreamInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncStreamInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SyncStreamInstance": + """ + Fetch the SyncStreamInstance + + + :returns: The fetched SyncStreamInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SyncStreamInstance": + """ + Asynchronous coroutine to fetch the SyncStreamInstance + + + :returns: The fetched SyncStreamInstance + """ + return await self._proxy.fetch_async() + + def update(self, ttl: Union[int, object] = values.unset) -> "SyncStreamInstance": + """ + Update the SyncStreamInstance + + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: The updated SyncStreamInstance + """ + return self._proxy.update( + ttl=ttl, + ) + + async def update_async( + self, ttl: Union[int, object] = values.unset + ) -> "SyncStreamInstance": + """ + Asynchronous coroutine to update the SyncStreamInstance + + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: The updated SyncStreamInstance + """ + return await self._proxy.update_async( + ttl=ttl, + ) + + @property + def stream_messages(self) -> StreamMessageList: + """ + Access the stream_messages + """ + return self._proxy.stream_messages + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.SyncStreamInstance {}>".format(context) + + +class SyncStreamContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the SyncStreamContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Sync Stream resource to update. + :param sid: The SID of the Stream resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Streams/{sid}".format(**self._solution) + + self._stream_messages: Optional[StreamMessageList] = None + + def delete(self) -> bool: + """ + Deletes the SyncStreamInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SyncStreamInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SyncStreamInstance: + """ + Fetch the SyncStreamInstance + + + :returns: The fetched SyncStreamInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SyncStreamInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SyncStreamInstance: + """ + Asynchronous coroutine to fetch the SyncStreamInstance + + + :returns: The fetched SyncStreamInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SyncStreamInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update(self, ttl: Union[int, object] = values.unset) -> SyncStreamInstance: + """ + Update the SyncStreamInstance + + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: The updated SyncStreamInstance + """ + + data = values.of( + { + "Ttl": ttl, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncStreamInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, ttl: Union[int, object] = values.unset + ) -> SyncStreamInstance: + """ + Asynchronous coroutine to update the SyncStreamInstance + + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: The updated SyncStreamInstance + """ + + data = values.of( + { + "Ttl": ttl, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncStreamInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def stream_messages(self) -> StreamMessageList: + """ + Access the stream_messages + """ + if self._stream_messages is None: + self._stream_messages = StreamMessageList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._stream_messages + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.SyncStreamContext {}>".format(context) + + +class SyncStreamPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SyncStreamInstance: + """ + Build an instance of SyncStreamInstance + + :param payload: Payload response from the API + """ + return SyncStreamInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.SyncStreamPage>" + + +class SyncStreamList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the SyncStreamList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) with the Stream resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Streams".format(**self._solution) + + def create( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> SyncStreamInstance: + """ + Create the SyncStreamInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: The created SyncStreamInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncStreamInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> SyncStreamInstance: + """ + Asynchronously create the SyncStreamInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. This value must be unique within its Service and it can be up to 320 characters long. The `unique_name` value can be used as an alternative to the `sid` in the URL path to address the resource. + :param ttl: How long, [in seconds](https://www.twilio.com/docs/sync/limits#sync-payload-limits), before the Stream expires and is deleted (time-to-live). + + :returns: The created SyncStreamInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SyncStreamInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SyncStreamInstance]: + """ + Streams SyncStreamInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SyncStreamInstance]: + """ + Asynchronously streams SyncStreamInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncStreamInstance]: + """ + Lists SyncStreamInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SyncStreamInstance]: + """ + Asynchronously lists SyncStreamInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncStreamPage: + """ + Retrieve a single page of SyncStreamInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncStreamInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncStreamPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SyncStreamPage: + """ + Asynchronously retrieve a single page of SyncStreamInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SyncStreamInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SyncStreamPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SyncStreamPage: + """ + Retrieve a specific page of SyncStreamInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncStreamInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SyncStreamPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SyncStreamPage: + """ + Asynchronously retrieve a specific page of SyncStreamInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SyncStreamInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SyncStreamPage(self._version, response, self._solution) + + def get(self, sid: str) -> SyncStreamContext: + """ + Constructs a SyncStreamContext + + :param sid: The SID of the Stream resource to update. + """ + return SyncStreamContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> SyncStreamContext: + """ + Constructs a SyncStreamContext + + :param sid: The SID of the Stream resource to update. + """ + return SyncStreamContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.SyncStreamList>" diff --git a/twilio/rest/sync/v1/service/sync_stream/stream_message.py b/twilio/rest/sync/v1/service/sync_stream/stream_message.py new file mode 100644 index 0000000000..bcce239975 --- /dev/null +++ b/twilio/rest/sync/v1/service/sync_stream/stream_message.py @@ -0,0 +1,146 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Sync + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class StreamMessageInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Stream Message resource. + :ivar data: An arbitrary, schema-less object that contains the Stream Message body. Can be up to 4 KiB in length. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + stream_sid: str, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.data: Optional[Dict[str, object]] = payload.get("data") + + self._solution = { + "service_sid": service_sid, + "stream_sid": stream_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Sync.V1.StreamMessageInstance {}>".format(context) + + +class StreamMessageList(ListResource): + + def __init__(self, version: Version, service_sid: str, stream_sid: str): + """ + Initialize the StreamMessageList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) to create the new Stream Message in. + :param stream_sid: The SID of the Sync Stream to create the new Stream Message resource for. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "stream_sid": stream_sid, + } + self._uri = "/Services/{service_sid}/Streams/{stream_sid}/Messages".format( + **self._solution + ) + + def create(self, data: object) -> StreamMessageInstance: + """ + Create the StreamMessageInstance + + :param data: A JSON string that represents an arbitrary, schema-less object that makes up the Stream Message body. Can be up to 4 KiB in length. + + :returns: The created StreamMessageInstance + """ + + data = values.of( + { + "Data": serialize.object(data), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return StreamMessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + stream_sid=self._solution["stream_sid"], + ) + + async def create_async(self, data: object) -> StreamMessageInstance: + """ + Asynchronously create the StreamMessageInstance + + :param data: A JSON string that represents an arbitrary, schema-less object that makes up the Stream Message body. Can be up to 4 KiB in length. + + :returns: The created StreamMessageInstance + """ + + data = values.of( + { + "Data": serialize.object(data), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return StreamMessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + stream_sid=self._solution["stream_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Sync.V1.StreamMessageList>" diff --git a/twilio/rest/taskrouter/TaskrouterBase.py b/twilio/rest/taskrouter/TaskrouterBase.py new file mode 100644 index 0000000000..4bbbdb602e --- /dev/null +++ b/twilio/rest/taskrouter/TaskrouterBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.taskrouter.v1 import V1 + + +class TaskrouterBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Taskrouter Domain + + :returns: Domain for Taskrouter + """ + super().__init__(twilio, "https://taskrouter.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Taskrouter + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter>" diff --git a/twilio/rest/taskrouter/__init__.py b/twilio/rest/taskrouter/__init__.py new file mode 100644 index 0000000000..73d3ee8250 --- /dev/null +++ b/twilio/rest/taskrouter/__init__.py @@ -0,0 +1,15 @@ +from warnings import warn + +from twilio.rest.taskrouter.TaskrouterBase import TaskrouterBase +from twilio.rest.taskrouter.v1.workspace import WorkspaceList + + +class Taskrouter(TaskrouterBase): + @property + def workspaces(self) -> WorkspaceList: + warn( + "workspaces is deprecated. Use v1.workspaces instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.workspaces diff --git a/twilio/rest/taskrouter/v1/__init__.py b/twilio/rest/taskrouter/v1/__init__.py new file mode 100644 index 0000000000..a17eeccc2a --- /dev/null +++ b/twilio/rest/taskrouter/v1/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.taskrouter.v1.workspace import WorkspaceList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Taskrouter + + :param domain: The Twilio.taskrouter domain + """ + super().__init__(domain, "v1") + self._workspaces: Optional[WorkspaceList] = None + + @property + def workspaces(self) -> WorkspaceList: + if self._workspaces is None: + self._workspaces = WorkspaceList(self) + return self._workspaces + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1>" diff --git a/twilio/rest/taskrouter/v1/workspace/__init__.py b/twilio/rest/taskrouter/v1/workspace/__init__.py new file mode 100644 index 0000000000..086e3e1747 --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/__init__.py @@ -0,0 +1,979 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.taskrouter.v1.workspace.activity import ActivityList +from twilio.rest.taskrouter.v1.workspace.event import EventList +from twilio.rest.taskrouter.v1.workspace.task import TaskList +from twilio.rest.taskrouter.v1.workspace.task_channel import TaskChannelList +from twilio.rest.taskrouter.v1.workspace.task_queue import TaskQueueList +from twilio.rest.taskrouter.v1.workspace.worker import WorkerList +from twilio.rest.taskrouter.v1.workspace.workflow import WorkflowList +from twilio.rest.taskrouter.v1.workspace.workspace_cumulative_statistics import ( + WorkspaceCumulativeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.workspace_real_time_statistics import ( + WorkspaceRealTimeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.workspace_statistics import ( + WorkspaceStatisticsList, +) + + +class WorkspaceInstance(InstanceResource): + + class QueueOrder(object): + FIFO = "FIFO" + LIFO = "LIFO" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workspace resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar default_activity_name: The name of the default activity. + :ivar default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :ivar event_callback_url: The URL we call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :ivar events_filter: The list of Workspace events for which to call `event_callback_url`. For example, if `EventsFilter=task.created, task.canceled, worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :ivar friendly_name: The string that you assigned to describe the Workspace resource. For example `Customer Support` or `2014 Election Campaign`. + :ivar multi_task_enabled: Whether multi-tasking is enabled. The default is `true`, which enables multi-tasking. Multi-tasking allows Workers to handle multiple Tasks simultaneously. When enabled (`true`), each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking each Worker would only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :ivar sid: The unique string that we created to identify the Workspace resource. + :ivar timeout_activity_name: The name of the timeout activity. + :ivar timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :ivar prioritize_queue_order: + :ivar url: The absolute URL of the Workspace resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.default_activity_name: Optional[str] = payload.get("default_activity_name") + self.default_activity_sid: Optional[str] = payload.get("default_activity_sid") + self.event_callback_url: Optional[str] = payload.get("event_callback_url") + self.events_filter: Optional[str] = payload.get("events_filter") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.multi_task_enabled: Optional[bool] = payload.get("multi_task_enabled") + self.sid: Optional[str] = payload.get("sid") + self.timeout_activity_name: Optional[str] = payload.get("timeout_activity_name") + self.timeout_activity_sid: Optional[str] = payload.get("timeout_activity_sid") + self.prioritize_queue_order: Optional["WorkspaceInstance.QueueOrder"] = ( + payload.get("prioritize_queue_order") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[WorkspaceContext] = None + + @property + def _proxy(self) -> "WorkspaceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkspaceContext for this WorkspaceInstance + """ + if self._context is None: + self._context = WorkspaceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the WorkspaceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WorkspaceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "WorkspaceInstance": + """ + Fetch the WorkspaceInstance + + + :returns: The fetched WorkspaceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WorkspaceInstance": + """ + Asynchronous coroutine to fetch the WorkspaceInstance + + + :returns: The fetched WorkspaceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> "WorkspaceInstance": + """ + Update the WorkspaceInstance + + :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :param prioritize_queue_order: + + :returns: The updated WorkspaceInstance + """ + return self._proxy.update( + default_activity_sid=default_activity_sid, + event_callback_url=event_callback_url, + events_filter=events_filter, + friendly_name=friendly_name, + multi_task_enabled=multi_task_enabled, + timeout_activity_sid=timeout_activity_sid, + prioritize_queue_order=prioritize_queue_order, + ) + + async def update_async( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> "WorkspaceInstance": + """ + Asynchronous coroutine to update the WorkspaceInstance + + :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :param prioritize_queue_order: + + :returns: The updated WorkspaceInstance + """ + return await self._proxy.update_async( + default_activity_sid=default_activity_sid, + event_callback_url=event_callback_url, + events_filter=events_filter, + friendly_name=friendly_name, + multi_task_enabled=multi_task_enabled, + timeout_activity_sid=timeout_activity_sid, + prioritize_queue_order=prioritize_queue_order, + ) + + @property + def activities(self) -> ActivityList: + """ + Access the activities + """ + return self._proxy.activities + + @property + def events(self) -> EventList: + """ + Access the events + """ + return self._proxy.events + + @property + def tasks(self) -> TaskList: + """ + Access the tasks + """ + return self._proxy.tasks + + @property + def task_channels(self) -> TaskChannelList: + """ + Access the task_channels + """ + return self._proxy.task_channels + + @property + def task_queues(self) -> TaskQueueList: + """ + Access the task_queues + """ + return self._proxy.task_queues + + @property + def workers(self) -> WorkerList: + """ + Access the workers + """ + return self._proxy.workers + + @property + def workflows(self) -> WorkflowList: + """ + Access the workflows + """ + return self._proxy.workflows + + @property + def cumulative_statistics(self) -> WorkspaceCumulativeStatisticsList: + """ + Access the cumulative_statistics + """ + return self._proxy.cumulative_statistics + + @property + def real_time_statistics(self) -> WorkspaceRealTimeStatisticsList: + """ + Access the real_time_statistics + """ + return self._proxy.real_time_statistics + + @property + def statistics(self) -> WorkspaceStatisticsList: + """ + Access the statistics + """ + return self._proxy.statistics + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkspaceInstance {}>".format(context) + + +class WorkspaceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the WorkspaceContext + + :param version: Version that contains the resource + :param sid: The SID of the Workspace resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Workspaces/{sid}".format(**self._solution) + + self._activities: Optional[ActivityList] = None + self._events: Optional[EventList] = None + self._tasks: Optional[TaskList] = None + self._task_channels: Optional[TaskChannelList] = None + self._task_queues: Optional[TaskQueueList] = None + self._workers: Optional[WorkerList] = None + self._workflows: Optional[WorkflowList] = None + self._cumulative_statistics: Optional[WorkspaceCumulativeStatisticsList] = None + self._real_time_statistics: Optional[WorkspaceRealTimeStatisticsList] = None + self._statistics: Optional[WorkspaceStatisticsList] = None + + def delete(self) -> bool: + """ + Deletes the WorkspaceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WorkspaceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> WorkspaceInstance: + """ + Fetch the WorkspaceInstance + + + :returns: The fetched WorkspaceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WorkspaceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WorkspaceInstance: + """ + Asynchronous coroutine to fetch the WorkspaceInstance + + + :returns: The fetched WorkspaceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WorkspaceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> WorkspaceInstance: + """ + Update the WorkspaceInstance + + :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :param prioritize_queue_order: + + :returns: The updated WorkspaceInstance + """ + + data = values.of( + { + "DefaultActivitySid": default_activity_sid, + "EventCallbackUrl": event_callback_url, + "EventsFilter": events_filter, + "FriendlyName": friendly_name, + "MultiTaskEnabled": serialize.boolean_to_string(multi_task_enabled), + "TimeoutActivitySid": timeout_activity_sid, + "PrioritizeQueueOrder": prioritize_queue_order, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + default_activity_sid: Union[str, object] = values.unset, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + timeout_activity_sid: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> WorkspaceInstance: + """ + Asynchronous coroutine to update the WorkspaceInstance + + :param default_activity_sid: The SID of the Activity that will be used when new Workers are created in the Workspace. + :param event_callback_url: The URL we should call when an event occurs. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example if `EventsFilter=task.created,task.canceled,worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param friendly_name: A descriptive string that you create to describe the Workspace resource. For example: `Sales Call Center` or `Customer Support Team`. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be maintained as multi-tasking. There is no default when omitting this parameter. A multi-tasking Workspace can't be updated to single-tasking unless it is not a Flex Project and another (legacy) single-tasking Workspace exists. Multi-tasking allows Workers to handle multiple Tasks simultaneously. In multi-tasking mode, each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param timeout_activity_sid: The SID of the Activity that will be assigned to a Worker when a Task reservation times out without a response. + :param prioritize_queue_order: + + :returns: The updated WorkspaceInstance + """ + + data = values.of( + { + "DefaultActivitySid": default_activity_sid, + "EventCallbackUrl": event_callback_url, + "EventsFilter": events_filter, + "FriendlyName": friendly_name, + "MultiTaskEnabled": serialize.boolean_to_string(multi_task_enabled), + "TimeoutActivitySid": timeout_activity_sid, + "PrioritizeQueueOrder": prioritize_queue_order, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def activities(self) -> ActivityList: + """ + Access the activities + """ + if self._activities is None: + self._activities = ActivityList( + self._version, + self._solution["sid"], + ) + return self._activities + + @property + def events(self) -> EventList: + """ + Access the events + """ + if self._events is None: + self._events = EventList( + self._version, + self._solution["sid"], + ) + return self._events + + @property + def tasks(self) -> TaskList: + """ + Access the tasks + """ + if self._tasks is None: + self._tasks = TaskList( + self._version, + self._solution["sid"], + ) + return self._tasks + + @property + def task_channels(self) -> TaskChannelList: + """ + Access the task_channels + """ + if self._task_channels is None: + self._task_channels = TaskChannelList( + self._version, + self._solution["sid"], + ) + return self._task_channels + + @property + def task_queues(self) -> TaskQueueList: + """ + Access the task_queues + """ + if self._task_queues is None: + self._task_queues = TaskQueueList( + self._version, + self._solution["sid"], + ) + return self._task_queues + + @property + def workers(self) -> WorkerList: + """ + Access the workers + """ + if self._workers is None: + self._workers = WorkerList( + self._version, + self._solution["sid"], + ) + return self._workers + + @property + def workflows(self) -> WorkflowList: + """ + Access the workflows + """ + if self._workflows is None: + self._workflows = WorkflowList( + self._version, + self._solution["sid"], + ) + return self._workflows + + @property + def cumulative_statistics(self) -> WorkspaceCumulativeStatisticsList: + """ + Access the cumulative_statistics + """ + if self._cumulative_statistics is None: + self._cumulative_statistics = WorkspaceCumulativeStatisticsList( + self._version, + self._solution["sid"], + ) + return self._cumulative_statistics + + @property + def real_time_statistics(self) -> WorkspaceRealTimeStatisticsList: + """ + Access the real_time_statistics + """ + if self._real_time_statistics is None: + self._real_time_statistics = WorkspaceRealTimeStatisticsList( + self._version, + self._solution["sid"], + ) + return self._real_time_statistics + + @property + def statistics(self) -> WorkspaceStatisticsList: + """ + Access the statistics + """ + if self._statistics is None: + self._statistics = WorkspaceStatisticsList( + self._version, + self._solution["sid"], + ) + return self._statistics + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkspaceContext {}>".format(context) + + +class WorkspacePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WorkspaceInstance: + """ + Build an instance of WorkspaceInstance + + :param payload: Payload response from the API + """ + return WorkspaceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.WorkspacePage>" + + +class WorkspaceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the WorkspaceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Workspaces" + + def create( + self, + friendly_name: str, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + template: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> WorkspaceInstance: + """ + Create the WorkspaceInstance + + :param friendly_name: A descriptive string that you create to describe the Workspace resource. It can be up to 64 characters long. For example: `Customer Support` or `2014 Election Campaign`. + :param event_callback_url: The URL we should call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example, if `EventsFilter=task.created, task.canceled, worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be created as multi-tasking. The default is `true`. Multi-tasking allows Workers to handle multiple Tasks simultaneously. When enabled (`true`), each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param template: An available template name. Can be: `NONE` or `FIFO` and the default is `NONE`. Pre-configures the Workspace with the Workflow and Activities specified in the template. `NONE` will create a Workspace with only a set of default activities. `FIFO` will configure TaskRouter with a set of default activities and a single TaskQueue for first-in, first-out distribution, which can be useful when you are getting started with TaskRouter. + :param prioritize_queue_order: + + :returns: The created WorkspaceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "EventCallbackUrl": event_callback_url, + "EventsFilter": events_filter, + "MultiTaskEnabled": serialize.boolean_to_string(multi_task_enabled), + "Template": template, + "PrioritizeQueueOrder": prioritize_queue_order, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkspaceInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + event_callback_url: Union[str, object] = values.unset, + events_filter: Union[str, object] = values.unset, + multi_task_enabled: Union[bool, object] = values.unset, + template: Union[str, object] = values.unset, + prioritize_queue_order: Union[ + "WorkspaceInstance.QueueOrder", object + ] = values.unset, + ) -> WorkspaceInstance: + """ + Asynchronously create the WorkspaceInstance + + :param friendly_name: A descriptive string that you create to describe the Workspace resource. It can be up to 64 characters long. For example: `Customer Support` or `2014 Election Campaign`. + :param event_callback_url: The URL we should call when an event occurs. If provided, the Workspace will publish events to this URL, for example, to collect data for reporting. See [Workspace Events](https://www.twilio.com/docs/taskrouter/api/event) for more information. This parameter supports Twilio's [Webhooks (HTTP callbacks) Connection Overrides](https://www.twilio.com/docs/usage/webhooks/webhooks-connection-overrides). + :param events_filter: The list of Workspace events for which to call event_callback_url. For example, if `EventsFilter=task.created, task.canceled, worker.activity.update`, then TaskRouter will call event_callback_url only when a task is created, canceled, or a Worker activity is updated. + :param multi_task_enabled: Whether to enable multi-tasking. Can be: `true` to enable multi-tasking, or `false` to disable it. However, all workspaces should be created as multi-tasking. The default is `true`. Multi-tasking allows Workers to handle multiple Tasks simultaneously. When enabled (`true`), each Worker can receive parallel reservations up to the per-channel maximums defined in the Workers section. In single-tasking mode (legacy mode), each Worker will only receive a new reservation when the previous task is completed. Learn more at [Multitasking](https://www.twilio.com/docs/taskrouter/multitasking). + :param template: An available template name. Can be: `NONE` or `FIFO` and the default is `NONE`. Pre-configures the Workspace with the Workflow and Activities specified in the template. `NONE` will create a Workspace with only a set of default activities. `FIFO` will configure TaskRouter with a set of default activities and a single TaskQueue for first-in, first-out distribution, which can be useful when you are getting started with TaskRouter. + :param prioritize_queue_order: + + :returns: The created WorkspaceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "EventCallbackUrl": event_callback_url, + "EventsFilter": events_filter, + "MultiTaskEnabled": serialize.boolean_to_string(multi_task_enabled), + "Template": template, + "PrioritizeQueueOrder": prioritize_queue_order, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkspaceInstance(self._version, payload) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WorkspaceInstance]: + """ + Streams WorkspaceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WorkspaceInstance]: + """ + Asynchronously streams WorkspaceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkspaceInstance]: + """ + Lists WorkspaceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkspaceInstance]: + """ + Asynchronously lists WorkspaceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkspacePage: + """ + Retrieve a single page of WorkspaceInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkspaceInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkspacePage(self._version, response) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkspacePage: + """ + Asynchronously retrieve a single page of WorkspaceInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Workspace resources to read. For example `Customer Support` or `2014 Election Campaign`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkspaceInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkspacePage(self._version, response) + + def get_page(self, target_url: str) -> WorkspacePage: + """ + Retrieve a specific page of WorkspaceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkspaceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WorkspacePage(self._version, response) + + async def get_page_async(self, target_url: str) -> WorkspacePage: + """ + Asynchronously retrieve a specific page of WorkspaceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkspaceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WorkspacePage(self._version, response) + + def get(self, sid: str) -> WorkspaceContext: + """ + Constructs a WorkspaceContext + + :param sid: The SID of the Workspace resource to update. + """ + return WorkspaceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> WorkspaceContext: + """ + Constructs a WorkspaceContext + + :param sid: The SID of the Workspace resource to update. + """ + return WorkspaceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.WorkspaceList>" diff --git a/twilio/rest/taskrouter/v1/workspace/activity.py b/twilio/rest/taskrouter/v1/workspace/activity.py new file mode 100644 index 0000000000..4e3e416af7 --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/activity.py @@ -0,0 +1,686 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ActivityInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Activity resource. + :ivar available: Whether the Worker is eligible to receive a Task when it occupies the Activity. A value of `true`, `1`, or `yes` indicates the Activity is available. All other values indicate that it is not. The value cannot be changed after the Activity is created. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar friendly_name: The string that you assigned to describe the Activity resource. + :ivar sid: The unique string that we created to identify the Activity resource. + :ivar workspace_sid: The SID of the Workspace that contains the Activity. + :ivar url: The absolute URL of the Activity resource. + :ivar links: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.available: Optional[bool] = payload.get("available") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid or self.sid, + } + self._context: Optional[ActivityContext] = None + + @property + def _proxy(self) -> "ActivityContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ActivityContext for this ActivityInstance + """ + if self._context is None: + self._context = ActivityContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ActivityInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ActivityInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ActivityInstance": + """ + Fetch the ActivityInstance + + + :returns: The fetched ActivityInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ActivityInstance": + """ + Asynchronous coroutine to fetch the ActivityInstance + + + :returns: The fetched ActivityInstance + """ + return await self._proxy.fetch_async() + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "ActivityInstance": + """ + Update the ActivityInstance + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + + :returns: The updated ActivityInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "ActivityInstance": + """ + Asynchronous coroutine to update the ActivityInstance + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + + :returns: The updated ActivityInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.ActivityInstance {}>".format(context) + + +class ActivityContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, sid: str): + """ + Initialize the ActivityContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Activity resources to update. + :param sid: The SID of the Activity resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/Activities/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the ActivityInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ActivityInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ActivityInstance: + """ + Fetch the ActivityInstance + + + :returns: The fetched ActivityInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ActivityInstance: + """ + Asynchronous coroutine to fetch the ActivityInstance + + + :returns: The fetched ActivityInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> ActivityInstance: + """ + Update the ActivityInstance + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + + :returns: The updated ActivityInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ActivityInstance: + """ + Asynchronous coroutine to update the ActivityInstance + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + + :returns: The updated ActivityInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.ActivityContext {}>".format(context) + + +class ActivityPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ActivityInstance: + """ + Build an instance of ActivityInstance + + :param payload: Payload response from the API + """ + return ActivityInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.ActivityPage>" + + +class ActivityList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the ActivityList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Activity resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Activities".format(**self._solution) + + def create( + self, friendly_name: str, available: Union[bool, object] = values.unset + ) -> ActivityInstance: + """ + Create the ActivityInstance + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + :param available: Whether the Worker should be eligible to receive a Task when it occupies the Activity. A value of `true`, `1`, or `yes` specifies the Activity is available. All other values specify that it is not. The value cannot be changed after the Activity is created. + + :returns: The created ActivityInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Available": serialize.boolean_to_string(available), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ActivityInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_async( + self, friendly_name: str, available: Union[bool, object] = values.unset + ) -> ActivityInstance: + """ + Asynchronously create the ActivityInstance + + :param friendly_name: A descriptive string that you create to describe the Activity resource. It can be up to 64 characters long. These names are used to calculate and expose statistics about Workers, and provide visibility into the state of each Worker. Examples of friendly names include: `on-call`, `break`, and `email`. + :param available: Whether the Worker should be eligible to receive a Task when it occupies the Activity. A value of `true`, `1`, or `yes` specifies the Activity is available. All other values specify that it is not. The value cannot be changed after the Activity is created. + + :returns: The created ActivityInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Available": serialize.boolean_to_string(available), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ActivityInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ActivityInstance]: + """ + Streams ActivityInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the Activity resources to read. + :param str available: Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of '1' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + friendly_name=friendly_name, + available=available, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ActivityInstance]: + """ + Asynchronously streams ActivityInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the Activity resources to read. + :param str available: Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of '1' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, + available=available, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ActivityInstance]: + """ + Lists ActivityInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the Activity resources to read. + :param str available: Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of '1' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + available=available, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ActivityInstance]: + """ + Asynchronously lists ActivityInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the Activity resources to read. + :param str available: Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of '1' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + available=available, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ActivityPage: + """ + Retrieve a single page of ActivityInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Activity resources to read. + :param available: Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of '1' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ActivityInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "Available": available, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ActivityPage(self._version, response, self._solution) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ActivityPage: + """ + Asynchronously retrieve a single page of ActivityInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Activity resources to read. + :param available: Whether return only Activity resources that are available or unavailable. A value of `true` returns only available activities. Values of '1' or `yes` also indicate `true`. All other values represent `false` and return activities that are unavailable. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ActivityInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "Available": available, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ActivityPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ActivityPage: + """ + Retrieve a specific page of ActivityInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ActivityInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ActivityPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ActivityPage: + """ + Asynchronously retrieve a specific page of ActivityInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ActivityInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ActivityPage(self._version, response, self._solution) + + def get(self, sid: str) -> ActivityContext: + """ + Constructs a ActivityContext + + :param sid: The SID of the Activity resource to update. + """ + return ActivityContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ActivityContext: + """ + Constructs a ActivityContext + + :param sid: The SID of the Activity resource to update. + """ + return ActivityContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.ActivityList>" diff --git a/twilio/rest/taskrouter/v1/workspace/event.py b/twilio/rest/taskrouter/v1/workspace/event.py new file mode 100644 index 0000000000..1b7f289e5e --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/event.py @@ -0,0 +1,658 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EventInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Event resource. + :ivar actor_sid: The SID of the resource that triggered the event. + :ivar actor_type: The type of resource that triggered the event. + :ivar actor_url: The absolute URL of the resource that triggered the event. + :ivar description: A description of the event. + :ivar event_data: Data about the event. For more information, see [Event types](https://www.twilio.com/docs/taskrouter/api/event#event-types). + :ivar event_date: The time the event was sent, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar event_date_ms: The time the event was sent in milliseconds. + :ivar event_type: The identifier for the event. + :ivar resource_sid: The SID of the object the event is most relevant to, such as a TaskSid, ReservationSid, or a WorkerSid. + :ivar resource_type: The type of object the event is most relevant to, such as a Task, Reservation, or a Worker). + :ivar resource_url: The URL of the resource the event is most relevant to. + :ivar sid: The unique string that we created to identify the Event resource. + :ivar source: Where the Event originated. + :ivar source_ip_address: The IP from which the Event originated. + :ivar url: The absolute URL of the Event resource. + :ivar workspace_sid: The SID of the Workspace that contains the Event. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.actor_sid: Optional[str] = payload.get("actor_sid") + self.actor_type: Optional[str] = payload.get("actor_type") + self.actor_url: Optional[str] = payload.get("actor_url") + self.description: Optional[str] = payload.get("description") + self.event_data: Optional[Dict[str, object]] = payload.get("event_data") + self.event_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("event_date") + ) + self.event_date_ms: Optional[int] = payload.get("event_date_ms") + self.event_type: Optional[str] = payload.get("event_type") + self.resource_sid: Optional[str] = payload.get("resource_sid") + self.resource_type: Optional[str] = payload.get("resource_type") + self.resource_url: Optional[str] = payload.get("resource_url") + self.sid: Optional[str] = payload.get("sid") + self.source: Optional[str] = payload.get("source") + self.source_ip_address: Optional[str] = payload.get("source_ip_address") + self.url: Optional[str] = payload.get("url") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid or self.sid, + } + self._context: Optional[EventContext] = None + + @property + def _proxy(self) -> "EventContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EventContext for this EventInstance + """ + if self._context is None: + self._context = EventContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "EventInstance": + """ + Fetch the EventInstance + + + :returns: The fetched EventInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EventInstance": + """ + Asynchronous coroutine to fetch the EventInstance + + + :returns: The fetched EventInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.EventInstance {}>".format(context) + + +class EventContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, sid: str): + """ + Initialize the EventContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Event to fetch. + :param sid: The SID of the Event resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/Events/{sid}".format(**self._solution) + + def fetch(self) -> EventInstance: + """ + Fetch the EventInstance + + + :returns: The fetched EventInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EventInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EventInstance: + """ + Asynchronous coroutine to fetch the EventInstance + + + :returns: The fetched EventInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EventInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.EventContext {}>".format(context) + + +class EventPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EventInstance: + """ + Build an instance of EventInstance + + :param payload: Payload response from the API + """ + return EventInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.EventPage>" + + +class EventList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the EventList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Events to read. Returns only the Events that pertain to the specified Workspace. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Events".format(**self._solution) + + def stream( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EventInstance]: + """ + Streams EventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str event_type: The type of Events to read. Returns only Events of the type specified. + :param int minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param str reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param datetime start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param str task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param str task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param str worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param str workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param str task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param str sid: The SID of the Event resource to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + end_date=end_date, + event_type=event_type, + minutes=minutes, + reservation_sid=reservation_sid, + start_date=start_date, + task_queue_sid=task_queue_sid, + task_sid=task_sid, + worker_sid=worker_sid, + workflow_sid=workflow_sid, + task_channel=task_channel, + sid=sid, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EventInstance]: + """ + Asynchronously streams EventInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str event_type: The type of Events to read. Returns only Events of the type specified. + :param int minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param str reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param datetime start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param str task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param str task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param str worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param str workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param str task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param str sid: The SID of the Event resource to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + end_date=end_date, + event_type=event_type, + minutes=minutes, + reservation_sid=reservation_sid, + start_date=start_date, + task_queue_sid=task_queue_sid, + task_sid=task_sid, + worker_sid=worker_sid, + workflow_sid=workflow_sid, + task_channel=task_channel, + sid=sid, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: + """ + Lists EventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str event_type: The type of Events to read. Returns only Events of the type specified. + :param int minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param str reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param datetime start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param str task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param str task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param str worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param str workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param str task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param str sid: The SID of the Event resource to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + end_date=end_date, + event_type=event_type, + minutes=minutes, + reservation_sid=reservation_sid, + start_date=start_date, + task_queue_sid=task_queue_sid, + task_sid=task_sid, + worker_sid=worker_sid, + workflow_sid=workflow_sid, + task_channel=task_channel, + sid=sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EventInstance]: + """ + Asynchronously lists EventInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str event_type: The type of Events to read. Returns only Events of the type specified. + :param int minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param str reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param datetime start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param str task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param str task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param str worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param str workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param str task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param str sid: The SID of the Event resource to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + end_date=end_date, + event_type=event_type, + minutes=minutes, + reservation_sid=reservation_sid, + start_date=start_date, + task_queue_sid=task_queue_sid, + task_sid=task_sid, + worker_sid=worker_sid, + workflow_sid=workflow_sid, + task_channel=task_channel, + sid=sid, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventPage: + """ + Retrieve a single page of EventInstance records from the API. + Request is executed immediately + + :param end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param event_type: The type of Events to read. Returns only Events of the type specified. + :param minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param sid: The SID of the Event resource to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventInstance + """ + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "EventType": event_type, + "Minutes": minutes, + "ReservationSid": reservation_sid, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskQueueSid": task_queue_sid, + "TaskSid": task_sid, + "WorkerSid": worker_sid, + "WorkflowSid": workflow_sid, + "TaskChannel": task_channel, + "Sid": sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response, self._solution) + + async def page_async( + self, + end_date: Union[datetime, object] = values.unset, + event_type: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + reservation_sid: Union[str, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_sid: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EventPage: + """ + Asynchronously retrieve a single page of EventInstance records from the API. + Request is executed immediately + + :param end_date: Only include Events that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param event_type: The type of Events to read. Returns only Events of the type specified. + :param minutes: The period of events to read in minutes. Returns only Events that occurred since this many minutes in the past. The default is `15` minutes. Task Attributes for Events occuring more 43,200 minutes ago will be redacted. + :param reservation_sid: The SID of the Reservation with the Events to read. Returns only Events that pertain to the specified Reservation. + :param start_date: Only include Events from on or after this date and time, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Task Attributes for Events older than 30 days will be redacted. + :param task_queue_sid: The SID of the TaskQueue with the Events to read. Returns only the Events that pertain to the specified TaskQueue. + :param task_sid: The SID of the Task with the Events to read. Returns only the Events that pertain to the specified Task. + :param worker_sid: The SID of the Worker with the Events to read. Returns only the Events that pertain to the specified Worker. + :param workflow_sid: The SID of the Workflow with the Events to read. Returns only the Events that pertain to the specified Workflow. + :param task_channel: The TaskChannel with the Events to read. Returns only the Events that pertain to the specified TaskChannel. + :param sid: The SID of the Event resource to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EventInstance + """ + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "EventType": event_type, + "Minutes": minutes, + "ReservationSid": reservation_sid, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskQueueSid": task_queue_sid, + "TaskSid": task_sid, + "WorkerSid": worker_sid, + "WorkflowSid": workflow_sid, + "TaskChannel": task_channel, + "Sid": sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EventPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> EventPage: + """ + Retrieve a specific page of EventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EventPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> EventPage: + """ + Asynchronously retrieve a specific page of EventInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EventInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EventPage(self._version, response, self._solution) + + def get(self, sid: str) -> EventContext: + """ + Constructs a EventContext + + :param sid: The SID of the Event resource to fetch. + """ + return EventContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __call__(self, sid: str) -> EventContext: + """ + Constructs a EventContext + + :param sid: The SID of the Event resource to fetch. + """ + return EventContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.EventList>" diff --git a/twilio/rest/taskrouter/v1/workspace/task/__init__.py b/twilio/rest/taskrouter/v1/workspace/task/__init__.py new file mode 100644 index 0000000000..2c4516df77 --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/task/__init__.py @@ -0,0 +1,1050 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.taskrouter.v1.workspace.task.reservation import ReservationList + + +class TaskInstance(InstanceResource): + + class Status(object): + PENDING = "pending" + RESERVED = "reserved" + ASSIGNED = "assigned" + CANCELED = "canceled" + COMPLETED = "completed" + WRAPPING = "wrapping" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Task resource. + :ivar age: The number of seconds since the Task was created. + :ivar assignment_status: + :ivar attributes: The JSON string with custom attributes of the work. **Note** If this property has been assigned a value, it will only be displayed in FETCH action that returns a single resource. Otherwise, it will be null. + :ivar addons: An object that contains the [Add-on](https://www.twilio.com/docs/add-ons) data for all installed Add-ons. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar task_queue_entered_date: The date and time in GMT when the Task entered the TaskQueue, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar priority: The current priority score of the Task as assigned to a Worker by the workflow. Tasks with higher priority values will be assigned before Tasks with lower values. + :ivar reason: The reason the Task was canceled or completed, if applicable. + :ivar sid: The unique string that we created to identify the Task resource. + :ivar task_queue_sid: The SID of the TaskQueue. + :ivar task_queue_friendly_name: The friendly name of the TaskQueue. + :ivar task_channel_sid: The SID of the TaskChannel. + :ivar task_channel_unique_name: The unique name of the TaskChannel. + :ivar timeout: The amount of time in seconds that the Task can live before being assigned. + :ivar workflow_sid: The SID of the Workflow that is controlling the Task. + :ivar workflow_friendly_name: The friendly name of the Workflow that is controlling the Task. + :ivar workspace_sid: The SID of the Workspace that contains the Task. + :ivar url: The absolute URL of the Task resource. + :ivar links: The URLs of related resources. + :ivar virtual_start_time: The date and time in GMT indicating the ordering for routing of the Task specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar ignore_capacity: A boolean that indicates if the Task should respect a Worker's capacity and availability during assignment. This field can only be used when the `RoutingTarget` field is set to a Worker SID. By setting `IgnoreCapacity` to a value of `true`, `1`, or `yes`, the Task will be routed to the Worker without respecting their capacity and availability. Any other value will enforce the Worker's capacity and availability. The default value of `IgnoreCapacity` is `true` when the `RoutingTarget` is set to a Worker SID. + :ivar routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.age: Optional[int] = deserialize.integer(payload.get("age")) + self.assignment_status: Optional["TaskInstance.Status"] = payload.get( + "assignment_status" + ) + self.attributes: Optional[str] = payload.get("attributes") + self.addons: Optional[str] = payload.get("addons") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.task_queue_entered_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("task_queue_entered_date") + ) + self.priority: Optional[int] = deserialize.integer(payload.get("priority")) + self.reason: Optional[str] = payload.get("reason") + self.sid: Optional[str] = payload.get("sid") + self.task_queue_sid: Optional[str] = payload.get("task_queue_sid") + self.task_queue_friendly_name: Optional[str] = payload.get( + "task_queue_friendly_name" + ) + self.task_channel_sid: Optional[str] = payload.get("task_channel_sid") + self.task_channel_unique_name: Optional[str] = payload.get( + "task_channel_unique_name" + ) + self.timeout: Optional[int] = deserialize.integer(payload.get("timeout")) + self.workflow_sid: Optional[str] = payload.get("workflow_sid") + self.workflow_friendly_name: Optional[str] = payload.get( + "workflow_friendly_name" + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.virtual_start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("virtual_start_time") + ) + self.ignore_capacity: Optional[bool] = payload.get("ignore_capacity") + self.routing_target: Optional[str] = payload.get("routing_target") + + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid or self.sid, + } + self._context: Optional[TaskContext] = None + + @property + def _proxy(self) -> "TaskContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TaskContext for this TaskInstance + """ + if self._context is None: + self._context = TaskContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Deletes the TaskInstance + + :param if_match: If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + if_match=if_match, + ) + + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Asynchronous coroutine that deletes the TaskInstance + + :param if_match: If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + if_match=if_match, + ) + + def fetch(self) -> "TaskInstance": + """ + Fetch the TaskInstance + + + :returns: The fetched TaskInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TaskInstance": + """ + Asynchronous coroutine to fetch the TaskInstance + + + :returns: The fetched TaskInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + if_match: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + assignment_status: Union["TaskInstance.Status", object] = values.unset, + reason: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + ) -> "TaskInstance": + """ + Update the TaskInstance + + :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param attributes: The JSON string that describes the custom attributes of the task. + :param assignment_status: + :param reason: The reason that the Task was canceled or completed. This parameter is required only if the Task is canceled or completed. Setting this value queues the task for deletion and logs the reason. + :param priority: The Task's new priority value. When supplied, the Task takes on the specified priority unless it matches a Workflow Target with a Priority set. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param virtual_start_time: The task's new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can't be in the future or before the year of 1900. + + :returns: The updated TaskInstance + """ + return self._proxy.update( + if_match=if_match, + attributes=attributes, + assignment_status=assignment_status, + reason=reason, + priority=priority, + task_channel=task_channel, + virtual_start_time=virtual_start_time, + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + assignment_status: Union["TaskInstance.Status", object] = values.unset, + reason: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + ) -> "TaskInstance": + """ + Asynchronous coroutine to update the TaskInstance + + :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param attributes: The JSON string that describes the custom attributes of the task. + :param assignment_status: + :param reason: The reason that the Task was canceled or completed. This parameter is required only if the Task is canceled or completed. Setting this value queues the task for deletion and logs the reason. + :param priority: The Task's new priority value. When supplied, the Task takes on the specified priority unless it matches a Workflow Target with a Priority set. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param virtual_start_time: The task's new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can't be in the future or before the year of 1900. + + :returns: The updated TaskInstance + """ + return await self._proxy.update_async( + if_match=if_match, + attributes=attributes, + assignment_status=assignment_status, + reason=reason, + priority=priority, + task_channel=task_channel, + virtual_start_time=virtual_start_time, + ) + + @property + def reservations(self) -> ReservationList: + """ + Access the reservations + """ + return self._proxy.reservations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.TaskInstance {}>".format(context) + + +class TaskContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, sid: str): + """ + Initialize the TaskContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Task to update. + :param sid: The SID of the Task resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/Tasks/{sid}".format(**self._solution) + + self._reservations: Optional[ReservationList] = None + + def delete(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Deletes the TaskInstance + + :param if_match: If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Asynchronous coroutine that deletes the TaskInstance + + :param if_match: If provided, deletes this Task if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TaskInstance: + """ + Fetch the TaskInstance + + + :returns: The fetched TaskInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TaskInstance: + """ + Asynchronous coroutine to fetch the TaskInstance + + + :returns: The fetched TaskInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + assignment_status: Union["TaskInstance.Status", object] = values.unset, + reason: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + ) -> TaskInstance: + """ + Update the TaskInstance + + :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param attributes: The JSON string that describes the custom attributes of the task. + :param assignment_status: + :param reason: The reason that the Task was canceled or completed. This parameter is required only if the Task is canceled or completed. Setting this value queues the task for deletion and logs the reason. + :param priority: The Task's new priority value. When supplied, the Task takes on the specified priority unless it matches a Workflow Target with a Priority set. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param virtual_start_time: The task's new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can't be in the future or before the year of 1900. + + :returns: The updated TaskInstance + """ + + data = values.of( + { + "Attributes": attributes, + "AssignmentStatus": assignment_status, + "Reason": reason, + "Priority": priority, + "TaskChannel": task_channel, + "VirtualStartTime": serialize.iso8601_datetime(virtual_start_time), + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + assignment_status: Union["TaskInstance.Status", object] = values.unset, + reason: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + ) -> TaskInstance: + """ + Asynchronous coroutine to update the TaskInstance + + :param if_match: If provided, applies this mutation if (and only if) the [ETag](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag) header of the Task matches the provided value. This matches the semantics of (and is implemented with) the HTTP [If-Match header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Match). + :param attributes: The JSON string that describes the custom attributes of the task. + :param assignment_status: + :param reason: The reason that the Task was canceled or completed. This parameter is required only if the Task is canceled or completed. Setting this value queues the task for deletion and logs the reason. + :param priority: The Task's new priority value. When supplied, the Task takes on the specified priority unless it matches a Workflow Target with a Priority set. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel with the task to update. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param virtual_start_time: The task's new virtual start time value. When supplied, the Task takes on the specified virtual start time. Value can't be in the future or before the year of 1900. + + :returns: The updated TaskInstance + """ + + data = values.of( + { + "Attributes": attributes, + "AssignmentStatus": assignment_status, + "Reason": reason, + "Priority": priority, + "TaskChannel": task_channel, + "VirtualStartTime": serialize.iso8601_datetime(virtual_start_time), + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + @property + def reservations(self) -> ReservationList: + """ + Access the reservations + """ + if self._reservations is None: + self._reservations = ReservationList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._reservations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.TaskContext {}>".format(context) + + +class TaskPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TaskInstance: + """ + Build an instance of TaskInstance + + :param payload: Payload response from the API + """ + return TaskInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.TaskPage>" + + +class TaskList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the TaskList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Tasks to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Tasks".format(**self._solution) + + def create( + self, + timeout: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ignore_capacity: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ) -> TaskInstance: + """ + Create the TaskInstance + + :param timeout: The amount of time in seconds the new task can live before being assigned. Can be up to a maximum of 2 weeks (1,209,600 seconds). The default value is 24 hours (86,400 seconds). On timeout, the `task.canceled` event will fire with description `Task TTL Exceeded`. + :param priority: The priority to assign the new task and override the default. When supplied, the new Task will have this priority unless it matches a Workflow Target with a Priority set. When not supplied, the new Task will have the priority of the matching Workflow Target. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel by passing either its `unique_name` or `sid`. Default value is `default`. + :param workflow_sid: The SID of the Workflow that you would like to handle routing for the new Task. If there is only one Workflow defined for the Workspace that you are posting the new task to, this parameter is optional. + :param attributes: A URL-encoded JSON string with the attributes of the new task. This value is passed to the Workflow's `assignment_callback_url` when the Task is assigned to a Worker. For example: `{ \\\"task_type\\\": \\\"call\\\", \\\"twilio_call_sid\\\": \\\"CAxxx\\\", \\\"customer_ticket_number\\\": \\\"12345\\\" }`. + :param virtual_start_time: The virtual start time to assign the new task and override the default. When supplied, the new task will have this virtual start time. When not supplied, the new task will have the virtual start time equal to `date_created`. Value can't be in the future or before the year of 1900. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ignore_capacity: A boolean that indicates if the Task should respect a Worker's capacity and availability during assignment. This field can only be used when the `RoutingTarget` field is set to a Worker SID. By setting `IgnoreCapacity` to a value of `true`, `1`, or `yes`, the Task will be routed to the Worker without respecting their capacity and availability. Any other value will enforce the Worker's capacity and availability. The default value of `IgnoreCapacity` is `true` when the `RoutingTarget` is set to a Worker SID. + :param task_queue_sid: The SID of the TaskQueue in which the Task belongs + + :returns: The created TaskInstance + """ + + data = values.of( + { + "Timeout": timeout, + "Priority": priority, + "TaskChannel": task_channel, + "WorkflowSid": workflow_sid, + "Attributes": attributes, + "VirtualStartTime": serialize.iso8601_datetime(virtual_start_time), + "RoutingTarget": routing_target, + "IgnoreCapacity": ignore_capacity, + "TaskQueueSid": task_queue_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_async( + self, + timeout: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + task_channel: Union[str, object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + virtual_start_time: Union[datetime, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ignore_capacity: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ) -> TaskInstance: + """ + Asynchronously create the TaskInstance + + :param timeout: The amount of time in seconds the new task can live before being assigned. Can be up to a maximum of 2 weeks (1,209,600 seconds). The default value is 24 hours (86,400 seconds). On timeout, the `task.canceled` event will fire with description `Task TTL Exceeded`. + :param priority: The priority to assign the new task and override the default. When supplied, the new Task will have this priority unless it matches a Workflow Target with a Priority set. When not supplied, the new Task will have the priority of the matching Workflow Target. Value can be 0 to 2^31^ (2,147,483,647). + :param task_channel: When MultiTasking is enabled, specify the TaskChannel by passing either its `unique_name` or `sid`. Default value is `default`. + :param workflow_sid: The SID of the Workflow that you would like to handle routing for the new Task. If there is only one Workflow defined for the Workspace that you are posting the new task to, this parameter is optional. + :param attributes: A URL-encoded JSON string with the attributes of the new task. This value is passed to the Workflow's `assignment_callback_url` when the Task is assigned to a Worker. For example: `{ \\\"task_type\\\": \\\"call\\\", \\\"twilio_call_sid\\\": \\\"CAxxx\\\", \\\"customer_ticket_number\\\": \\\"12345\\\" }`. + :param virtual_start_time: The virtual start time to assign the new task and override the default. When supplied, the new task will have this virtual start time. When not supplied, the new task will have the virtual start time equal to `date_created`. Value can't be in the future or before the year of 1900. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ignore_capacity: A boolean that indicates if the Task should respect a Worker's capacity and availability during assignment. This field can only be used when the `RoutingTarget` field is set to a Worker SID. By setting `IgnoreCapacity` to a value of `true`, `1`, or `yes`, the Task will be routed to the Worker without respecting their capacity and availability. Any other value will enforce the Worker's capacity and availability. The default value of `IgnoreCapacity` is `true` when the `RoutingTarget` is set to a Worker SID. + :param task_queue_sid: The SID of the TaskQueue in which the Task belongs + + :returns: The created TaskInstance + """ + + data = values.of( + { + "Timeout": timeout, + "Priority": priority, + "TaskChannel": task_channel, + "WorkflowSid": workflow_sid, + "Attributes": attributes, + "VirtualStartTime": serialize.iso8601_datetime(virtual_start_time), + "RoutingTarget": routing_target, + "IgnoreCapacity": ignore_capacity, + "TaskQueueSid": task_queue_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def stream( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TaskInstance]: + """ + Streams TaskInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param str workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param str workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param str task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param str task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param str evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param str routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param str ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param bool has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + priority=priority, + assignment_status=assignment_status, + workflow_sid=workflow_sid, + workflow_name=workflow_name, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + evaluate_task_attributes=evaluate_task_attributes, + routing_target=routing_target, + ordering=ordering, + has_addons=has_addons, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TaskInstance]: + """ + Asynchronously streams TaskInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param str workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param str workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param str task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param str task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param str evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param str routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param str ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param bool has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + priority=priority, + assignment_status=assignment_status, + workflow_sid=workflow_sid, + workflow_name=workflow_name, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + evaluate_task_attributes=evaluate_task_attributes, + routing_target=routing_target, + ordering=ordering, + has_addons=has_addons, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskInstance]: + """ + Lists TaskInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param str workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param str workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param str task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param str task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param str evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param str routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param str ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param bool has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + priority=priority, + assignment_status=assignment_status, + workflow_sid=workflow_sid, + workflow_name=workflow_name, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + evaluate_task_attributes=evaluate_task_attributes, + routing_target=routing_target, + ordering=ordering, + has_addons=has_addons, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskInstance]: + """ + Asynchronously lists TaskInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param int priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param List[str] assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param str workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param str workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param str task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param str task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param str evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param str routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param str ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param bool has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + priority=priority, + assignment_status=assignment_status, + workflow_sid=workflow_sid, + workflow_name=workflow_name, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + evaluate_task_attributes=evaluate_task_attributes, + routing_target=routing_target, + ordering=ordering, + has_addons=has_addons, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskPage: + """ + Retrieve a single page of TaskInstance records from the API. + Request is executed immediately + + :param priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskInstance + """ + data = values.of( + { + "Priority": priority, + "AssignmentStatus": serialize.map(assignment_status, lambda e: e), + "WorkflowSid": workflow_sid, + "WorkflowName": workflow_name, + "TaskQueueSid": task_queue_sid, + "TaskQueueName": task_queue_name, + "EvaluateTaskAttributes": evaluate_task_attributes, + "RoutingTarget": routing_target, + "Ordering": ordering, + "HasAddons": serialize.boolean_to_string(has_addons), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskPage(self._version, response, self._solution) + + async def page_async( + self, + priority: Union[int, object] = values.unset, + assignment_status: Union[List[str], object] = values.unset, + workflow_sid: Union[str, object] = values.unset, + workflow_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + evaluate_task_attributes: Union[str, object] = values.unset, + routing_target: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + has_addons: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskPage: + """ + Asynchronously retrieve a single page of TaskInstance records from the API. + Request is executed immediately + + :param priority: The priority value of the Tasks to read. Returns the list of all Tasks in the Workspace with the specified priority. + :param assignment_status: The `assignment_status` of the Tasks you want to read. Can be: `pending`, `reserved`, `assigned`, `canceled`, `wrapping`, or `completed`. Returns all Tasks in the Workspace with the specified `assignment_status`. + :param workflow_sid: The SID of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this SID. + :param workflow_name: The friendly name of the Workflow with the Tasks to read. Returns the Tasks controlled by the Workflow identified by this friendly name. + :param task_queue_sid: The SID of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this SID. + :param task_queue_name: The `friendly_name` of the TaskQueue with the Tasks to read. Returns the Tasks waiting in the TaskQueue identified by this friendly name. + :param evaluate_task_attributes: The attributes of the Tasks to read. Returns the Tasks that match the attributes specified in this parameter. + :param routing_target: A SID of a Worker, Queue, or Workflow to route a Task to + :param ordering: How to order the returned Task resources. By default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `DateCreated`, `Priority`, or `VirtualStartTime` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Pairings of sort orders can be specified in a comma-separated list such as `Priority:desc,DateCreated:asc`, which returns the Tasks in descending Priority order and ascending DateCreated Order. The only ordering pairing not allowed is DateCreated and VirtualStartTime. + :param has_addons: Whether to read Tasks with Add-ons. If `true`, returns only Tasks with Add-ons. If `false`, returns only Tasks without Add-ons. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskInstance + """ + data = values.of( + { + "Priority": priority, + "AssignmentStatus": serialize.map(assignment_status, lambda e: e), + "WorkflowSid": workflow_sid, + "WorkflowName": workflow_name, + "TaskQueueSid": task_queue_sid, + "TaskQueueName": task_queue_name, + "EvaluateTaskAttributes": evaluate_task_attributes, + "RoutingTarget": routing_target, + "Ordering": ordering, + "HasAddons": serialize.boolean_to_string(has_addons), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TaskPage: + """ + Retrieve a specific page of TaskInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TaskPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TaskPage: + """ + Asynchronously retrieve a specific page of TaskInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TaskPage(self._version, response, self._solution) + + def get(self, sid: str) -> TaskContext: + """ + Constructs a TaskContext + + :param sid: The SID of the Task resource to update. + """ + return TaskContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __call__(self, sid: str) -> TaskContext: + """ + Constructs a TaskContext + + :param sid: The SID of the Task resource to update. + """ + return TaskContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.TaskList>" diff --git a/twilio/rest/taskrouter/v1/workspace/task/reservation.py b/twilio/rest/taskrouter/v1/workspace/task/reservation.py new file mode 100644 index 0000000000..28cb03339a --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/task/reservation.py @@ -0,0 +1,1351 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ReservationInstance(InstanceResource): + + class CallStatus(object): + INITIATED = "initiated" + RINGING = "ringing" + ANSWERED = "answered" + COMPLETED = "completed" + + class ConferenceEvent(object): + START = "start" + END = "end" + JOIN = "join" + LEAVE = "leave" + MUTE = "mute" + HOLD = "hold" + SPEAKER = "speaker" + + class Status(object): + PENDING = "pending" + ACCEPTED = "accepted" + REJECTED = "rejected" + TIMEOUT = "timeout" + CANCELED = "canceled" + RESCINDED = "rescinded" + WRAPPING = "wrapping" + COMPLETED = "completed" + + class SupervisorMode(object): + MONITOR = "monitor" + WHISPER = "whisper" + BARGE = "barge" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskReservation resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar reservation_status: + :ivar sid: The unique string that we created to identify the TaskReservation resource. + :ivar task_sid: The SID of the reserved Task resource. + :ivar worker_name: The `friendly_name` of the Worker that is reserved. + :ivar worker_sid: The SID of the reserved Worker resource. + :ivar workspace_sid: The SID of the Workspace that this task is contained within. + :ivar url: The absolute URL of the TaskReservation reservation. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + task_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.reservation_status: Optional["ReservationInstance.Status"] = payload.get( + "reservation_status" + ) + self.sid: Optional[str] = payload.get("sid") + self.task_sid: Optional[str] = payload.get("task_sid") + self.worker_name: Optional[str] = payload.get("worker_name") + self.worker_sid: Optional[str] = payload.get("worker_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "workspace_sid": workspace_sid, + "task_sid": task_sid, + "sid": sid or self.sid, + } + self._context: Optional[ReservationContext] = None + + @property + def _proxy(self) -> "ReservationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ReservationContext for this ReservationInstance + """ + if self._context is None: + self._context = ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ReservationInstance": + """ + Fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ReservationInstance": + """ + Asynchronous coroutine to fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> "ReservationInstance": + """ + Update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: Timeout for call when executing a Dequeue instruction. + :param dequeue_to: The Contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction or which leg to record. + :param call_timeout: Timeout for call when executing a Call instruction. + :param call_to: The Contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The Caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: Timeout for call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. The default is `false`. + :param muted: Whether the agent is muted in the conference. The default is `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. The default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: How to trim the leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param supervisor_mode: + :param supervisor: The Supervisor SID/URI when executing the Supervise instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + return self._proxy.update( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + supervisor_mode=supervisor_mode, + supervisor=supervisor, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> "ReservationInstance": + """ + Asynchronous coroutine to update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: Timeout for call when executing a Dequeue instruction. + :param dequeue_to: The Contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction or which leg to record. + :param call_timeout: Timeout for call when executing a Call instruction. + :param call_to: The Contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The Caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: Timeout for call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. The default is `false`. + :param muted: Whether the agent is muted in the conference. The default is `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. The default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: How to trim the leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param supervisor_mode: + :param supervisor: The Supervisor SID/URI when executing the Supervise instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + return await self._proxy.update_async( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + supervisor_mode=supervisor_mode, + supervisor=supervisor, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.ReservationInstance {}>".format(context) + + +class ReservationContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, task_sid: str, sid: str): + """ + Initialize the ReservationContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskReservation resources to update. + :param task_sid: The SID of the reserved Task resource with the TaskReservation resources to update. + :param sid: The SID of the TaskReservation resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_sid": task_sid, + "sid": sid, + } + self._uri = ( + "/Workspaces/{workspace_sid}/Tasks/{task_sid}/Reservations/{sid}".format( + **self._solution + ) + ) + + def fetch(self) -> ReservationInstance: + """ + Fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ReservationInstance: + """ + Asynchronous coroutine to fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ReservationInstance: + """ + Update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: Timeout for call when executing a Dequeue instruction. + :param dequeue_to: The Contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction or which leg to record. + :param call_timeout: Timeout for call when executing a Call instruction. + :param call_to: The Contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The Caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: Timeout for call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. The default is `false`. + :param muted: Whether the agent is muted in the conference. The default is `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. The default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: How to trim the leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param supervisor_mode: + :param supervisor: The Supervisor SID/URI when executing the Supervise instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerActivitySid": worker_activity_sid, + "Instruction": instruction, + "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, + "DequeueFrom": dequeue_from, + "DequeueRecord": dequeue_record, + "DequeueTimeout": dequeue_timeout, + "DequeueTo": dequeue_to, + "DequeueStatusCallbackUrl": dequeue_status_callback_url, + "CallFrom": call_from, + "CallRecord": call_record, + "CallTimeout": call_timeout, + "CallTo": call_to, + "CallUrl": call_url, + "CallStatusCallbackUrl": call_status_callback_url, + "CallAccept": serialize.boolean_to_string(call_accept), + "RedirectCallSid": redirect_call_sid, + "RedirectAccept": serialize.boolean_to_string(redirect_accept), + "RedirectUrl": redirect_url, + "To": to, + "From": from_, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), + "Beep": beep, + "StartConferenceOnEnter": serialize.boolean_to_string( + start_conference_on_enter + ), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "EarlyMedia": serialize.boolean_to_string(early_media), + "MaxParticipants": max_participants, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "Region": region, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "DequeueStatusCallbackEvent": serialize.map( + dequeue_status_callback_event, lambda e: e + ), + "PostWorkActivitySid": post_work_activity_sid, + "SupervisorMode": supervisor_mode, + "Supervisor": supervisor, + "EndConferenceOnCustomerExit": serialize.boolean_to_string( + end_conference_on_customer_exit + ), + "BeepOnCustomerEntrance": serialize.boolean_to_string( + beep_on_customer_entrance + ), + "JitterBufferSize": jitter_buffer_size, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + supervisor_mode: Union[ + "ReservationInstance.SupervisorMode", object + ] = values.unset, + supervisor: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ReservationInstance: + """ + Asynchronous coroutine to update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The Caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: Timeout for call when executing a Dequeue instruction. + :param dequeue_to: The Contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The Callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction or which leg to record. + :param call_timeout: Timeout for call when executing a Call instruction. + :param call_to: The Contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The Caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: Timeout for call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. The default is `false`. + :param muted: Whether the agent is muted in the conference. The default is `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. The default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: How to trim the leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The Call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param supervisor_mode: + :param supervisor: The Supervisor SID/URI when executing the Supervise instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerActivitySid": worker_activity_sid, + "Instruction": instruction, + "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, + "DequeueFrom": dequeue_from, + "DequeueRecord": dequeue_record, + "DequeueTimeout": dequeue_timeout, + "DequeueTo": dequeue_to, + "DequeueStatusCallbackUrl": dequeue_status_callback_url, + "CallFrom": call_from, + "CallRecord": call_record, + "CallTimeout": call_timeout, + "CallTo": call_to, + "CallUrl": call_url, + "CallStatusCallbackUrl": call_status_callback_url, + "CallAccept": serialize.boolean_to_string(call_accept), + "RedirectCallSid": redirect_call_sid, + "RedirectAccept": serialize.boolean_to_string(redirect_accept), + "RedirectUrl": redirect_url, + "To": to, + "From": from_, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), + "Beep": beep, + "StartConferenceOnEnter": serialize.boolean_to_string( + start_conference_on_enter + ), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "EarlyMedia": serialize.boolean_to_string(early_media), + "MaxParticipants": max_participants, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "Region": region, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "DequeueStatusCallbackEvent": serialize.map( + dequeue_status_callback_event, lambda e: e + ), + "PostWorkActivitySid": post_work_activity_sid, + "SupervisorMode": supervisor_mode, + "Supervisor": supervisor, + "EndConferenceOnCustomerExit": serialize.boolean_to_string( + end_conference_on_customer_exit + ), + "BeepOnCustomerEntrance": serialize.boolean_to_string( + beep_on_customer_entrance + ), + "JitterBufferSize": jitter_buffer_size, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.ReservationContext {}>".format(context) + + +class ReservationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ReservationInstance: + """ + Build an instance of ReservationInstance + + :param payload: Payload response from the API + """ + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.ReservationPage>" + + +class ReservationList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, task_sid: str): + """ + Initialize the ReservationList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskReservation resources to read. + :param task_sid: The SID of the reserved Task resource with the TaskReservation resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_sid": task_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Tasks/{task_sid}/Reservations".format( + **self._solution + ) + + def stream( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ReservationInstance]: + """ + Streams ReservationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param str worker_sid: The SID of the reserved Worker resource to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + reservation_status=reservation_status, + worker_sid=worker_sid, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ReservationInstance]: + """ + Asynchronously streams ReservationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param str worker_sid: The SID of the reserved Worker resource to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + reservation_status=reservation_status, + worker_sid=worker_sid, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ReservationInstance]: + """ + Lists ReservationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param str worker_sid: The SID of the reserved Worker resource to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + reservation_status=reservation_status, + worker_sid=worker_sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ReservationInstance]: + """ + Asynchronously lists ReservationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param str worker_sid: The SID of the reserved Worker resource to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + reservation_status=reservation_status, + worker_sid=worker_sid, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ReservationPage: + """ + Retrieve a single page of ReservationInstance records from the API. + Request is executed immediately + + :param reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param worker_sid: The SID of the reserved Worker resource to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ReservationInstance + """ + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerSid": worker_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ReservationPage(self._version, response, self._solution) + + async def page_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ReservationPage: + """ + Asynchronously retrieve a single page of ReservationInstance records from the API. + Request is executed immediately + + :param reservation_status: Returns the list of reservations for a task with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, or `timeout`. + :param worker_sid: The SID of the reserved Worker resource to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ReservationInstance + """ + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerSid": worker_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ReservationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ReservationPage: + """ + Retrieve a specific page of ReservationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ReservationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ReservationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ReservationPage: + """ + Asynchronously retrieve a specific page of ReservationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ReservationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ReservationPage(self._version, response, self._solution) + + def get(self, sid: str) -> ReservationContext: + """ + Constructs a ReservationContext + + :param sid: The SID of the TaskReservation resource to update. + """ + return ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ReservationContext: + """ + Constructs a ReservationContext + + :param sid: The SID of the TaskReservation resource to update. + """ + return ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_sid=self._solution["task_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.ReservationList>" diff --git a/twilio/rest/taskrouter/v1/workspace/task_channel.py b/twilio/rest/taskrouter/v1/workspace/task_channel.py new file mode 100644 index 0000000000..3a4b0a6b9e --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/task_channel.py @@ -0,0 +1,684 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TaskChannelInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Task Channel resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar sid: The unique string that we created to identify the Task Channel resource. + :ivar unique_name: An application-defined string that uniquely identifies the Task Channel, such as `voice` or `sms`. + :ivar workspace_sid: The SID of the Workspace that contains the Task Channel. + :ivar channel_optimized_routing: Whether the Task Channel will prioritize Workers that have been idle. When `true`, Workers that have been idle the longest are prioritized. + :ivar url: The absolute URL of the Task Channel resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.channel_optimized_routing: Optional[bool] = payload.get( + "channel_optimized_routing" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid or self.sid, + } + self._context: Optional[TaskChannelContext] = None + + @property + def _proxy(self) -> "TaskChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TaskChannelContext for this TaskChannelInstance + """ + if self._context is None: + self._context = TaskChannelContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TaskChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TaskChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TaskChannelInstance": + """ + Fetch the TaskChannelInstance + + + :returns: The fetched TaskChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TaskChannelInstance": + """ + Asynchronous coroutine to fetch the TaskChannelInstance + + + :returns: The fetched TaskChannelInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> "TaskChannelInstance": + """ + Update the TaskChannelInstance + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The updated TaskChannelInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> "TaskChannelInstance": + """ + Asynchronous coroutine to update the TaskChannelInstance + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The updated TaskChannelInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + channel_optimized_routing=channel_optimized_routing, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.TaskChannelInstance {}>".format(context) + + +class TaskChannelContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, sid: str): + """ + Initialize the TaskChannelContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Task Channel to update. + :param sid: The SID of the Task Channel resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskChannels/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the TaskChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TaskChannelInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TaskChannelInstance: + """ + Fetch the TaskChannelInstance + + + :returns: The fetched TaskChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TaskChannelInstance: + """ + Asynchronous coroutine to fetch the TaskChannelInstance + + + :returns: The fetched TaskChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: + """ + Update the TaskChannelInstance + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The updated TaskChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ChannelOptimizedRouting": serialize.boolean_to_string( + channel_optimized_routing + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: + """ + Asynchronous coroutine to update the TaskChannelInstance + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param channel_optimized_routing: Whether the TaskChannel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The updated TaskChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ChannelOptimizedRouting": serialize.boolean_to_string( + channel_optimized_routing + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.TaskChannelContext {}>".format(context) + + +class TaskChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TaskChannelInstance: + """ + Build an instance of TaskChannelInstance + + :param payload: Payload response from the API + """ + return TaskChannelInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.TaskChannelPage>" + + +class TaskChannelList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the TaskChannelList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Task Channel to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskChannels".format(**self._solution) + + def create( + self, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: + """ + Create the TaskChannelInstance + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the Task Channel, such as `voice` or `sms`. + :param channel_optimized_routing: Whether the Task Channel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The created TaskChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "ChannelOptimizedRouting": serialize.boolean_to_string( + channel_optimized_routing + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskChannelInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_async( + self, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> TaskChannelInstance: + """ + Asynchronously create the TaskChannelInstance + + :param friendly_name: A descriptive string that you create to describe the Task Channel. It can be up to 64 characters long. + :param unique_name: An application-defined string that uniquely identifies the Task Channel, such as `voice` or `sms`. + :param channel_optimized_routing: Whether the Task Channel should prioritize Workers that have been idle. If `true`, Workers that have been idle the longest are prioritized. + + :returns: The created TaskChannelInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "ChannelOptimizedRouting": serialize.boolean_to_string( + channel_optimized_routing + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskChannelInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TaskChannelInstance]: + """ + Streams TaskChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TaskChannelInstance]: + """ + Asynchronously streams TaskChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskChannelInstance]: + """ + Lists TaskChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskChannelInstance]: + """ + Asynchronously lists TaskChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskChannelPage: + """ + Retrieve a single page of TaskChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskChannelPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskChannelPage: + """ + Asynchronously retrieve a single page of TaskChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TaskChannelPage: + """ + Retrieve a specific page of TaskChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TaskChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TaskChannelPage: + """ + Asynchronously retrieve a specific page of TaskChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TaskChannelPage(self._version, response, self._solution) + + def get(self, sid: str) -> TaskChannelContext: + """ + Constructs a TaskChannelContext + + :param sid: The SID of the Task Channel resource to update. + """ + return TaskChannelContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __call__(self, sid: str) -> TaskChannelContext: + """ + Constructs a TaskChannelContext + + :param sid: The SID of the Task Channel resource to update. + """ + return TaskChannelContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.TaskChannelList>" diff --git a/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py b/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py new file mode 100644 index 0000000000..4511a55310 --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py @@ -0,0 +1,949 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_bulk_real_time_statistics import ( + TaskQueueBulkRealTimeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics import ( + TaskQueueCumulativeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_real_time_statistics import ( + TaskQueueRealTimeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_statistics import ( + TaskQueueStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.task_queue.task_queues_statistics import ( + TaskQueuesStatisticsList, +) + + +class TaskQueueInstance(InstanceResource): + + class TaskOrder(object): + FIFO = "FIFO" + LIFO = "LIFO" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + :ivar assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :ivar assignment_activity_name: The name of the Activity to assign Workers when a task is assigned for them. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar max_reserved_workers: The maximum number of Workers to reserve for the assignment of a task in the queue. Can be an integer between 1 and 50, inclusive and defaults to 1. + :ivar reservation_activity_sid: The SID of the Activity to assign Workers once a task is reserved for them. + :ivar reservation_activity_name: The name of the Activity to assign Workers once a task is reserved for them. + :ivar sid: The unique string that we created to identify the TaskQueue resource. + :ivar target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example `'\"language\" == \"spanish\"'` If no TargetWorkers parameter is provided, Tasks will wait in the TaskQueue until they are either deleted or moved to another TaskQueue. Additional examples on how to describing Worker selection criteria below. Defaults to 1==1. + :ivar task_order: + :ivar url: The absolute URL of the TaskQueue resource. + :ivar workspace_sid: The SID of the Workspace that contains the TaskQueue. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.assignment_activity_sid: Optional[str] = payload.get( + "assignment_activity_sid" + ) + self.assignment_activity_name: Optional[str] = payload.get( + "assignment_activity_name" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.max_reserved_workers: Optional[int] = deserialize.integer( + payload.get("max_reserved_workers") + ) + self.reservation_activity_sid: Optional[str] = payload.get( + "reservation_activity_sid" + ) + self.reservation_activity_name: Optional[str] = payload.get( + "reservation_activity_name" + ) + self.sid: Optional[str] = payload.get("sid") + self.target_workers: Optional[str] = payload.get("target_workers") + self.task_order: Optional["TaskQueueInstance.TaskOrder"] = payload.get( + "task_order" + ) + self.url: Optional[str] = payload.get("url") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid or self.sid, + } + self._context: Optional[TaskQueueContext] = None + + @property + def _proxy(self) -> "TaskQueueContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TaskQueueContext for this TaskQueueInstance + """ + if self._context is None: + self._context = TaskQueueContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TaskQueueInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TaskQueueInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TaskQueueInstance": + """ + Fetch the TaskQueueInstance + + + :returns: The fetched TaskQueueInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TaskQueueInstance": + """ + Asynchronous coroutine to fetch the TaskQueueInstance + + + :returns: The fetched TaskQueueInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + target_workers: Union[str, object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + ) -> "TaskQueueInstance": + """ + Update the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. + :param task_order: + + :returns: The updated TaskQueueInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + target_workers=target_workers, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + target_workers: Union[str, object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + ) -> "TaskQueueInstance": + """ + Asynchronous coroutine to update the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. + :param task_order: + + :returns: The updated TaskQueueInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + target_workers=target_workers, + reservation_activity_sid=reservation_activity_sid, + assignment_activity_sid=assignment_activity_sid, + max_reserved_workers=max_reserved_workers, + task_order=task_order, + ) + + @property + def cumulative_statistics(self) -> TaskQueueCumulativeStatisticsList: + """ + Access the cumulative_statistics + """ + return self._proxy.cumulative_statistics + + @property + def real_time_statistics(self) -> TaskQueueRealTimeStatisticsList: + """ + Access the real_time_statistics + """ + return self._proxy.real_time_statistics + + @property + def statistics(self) -> TaskQueueStatisticsList: + """ + Access the statistics + """ + return self._proxy.statistics + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.TaskQueueInstance {}>".format(context) + + +class TaskQueueContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, sid: str): + """ + Initialize the TaskQueueContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueue to update. + :param sid: The SID of the TaskQueue resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskQueues/{sid}".format( + **self._solution + ) + + self._cumulative_statistics: Optional[TaskQueueCumulativeStatisticsList] = None + self._real_time_statistics: Optional[TaskQueueRealTimeStatisticsList] = None + self._statistics: Optional[TaskQueueStatisticsList] = None + + def delete(self) -> bool: + """ + Deletes the TaskQueueInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TaskQueueInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TaskQueueInstance: + """ + Fetch the TaskQueueInstance + + + :returns: The fetched TaskQueueInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TaskQueueInstance: + """ + Asynchronous coroutine to fetch the TaskQueueInstance + + + :returns: The fetched TaskQueueInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + target_workers: Union[str, object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + ) -> TaskQueueInstance: + """ + Update the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. + :param task_order: + + :returns: The updated TaskQueueInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "TargetWorkers": target_workers, + "ReservationActivitySid": reservation_activity_sid, + "AssignmentActivitySid": assignment_activity_sid, + "MaxReservedWorkers": max_reserved_workers, + "TaskOrder": task_order, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + target_workers: Union[str, object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + ) -> TaskQueueInstance: + """ + Asynchronous coroutine to update the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string describing the Worker selection criteria for any Tasks that enter the TaskQueue. For example '\\\"language\\\" == \\\"spanish\\\"' If no TargetWorkers parameter is provided, Tasks will wait in the queue until they are either deleted or moved to another queue. Additional examples on how to describing Worker selection criteria below. + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned for them. + :param max_reserved_workers: The maximum number of Workers to create reservations for the assignment of a task while in the queue. Maximum of 50. + :param task_order: + + :returns: The updated TaskQueueInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "TargetWorkers": target_workers, + "ReservationActivitySid": reservation_activity_sid, + "AssignmentActivitySid": assignment_activity_sid, + "MaxReservedWorkers": max_reserved_workers, + "TaskOrder": task_order, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + @property + def cumulative_statistics(self) -> TaskQueueCumulativeStatisticsList: + """ + Access the cumulative_statistics + """ + if self._cumulative_statistics is None: + self._cumulative_statistics = TaskQueueCumulativeStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._cumulative_statistics + + @property + def real_time_statistics(self) -> TaskQueueRealTimeStatisticsList: + """ + Access the real_time_statistics + """ + if self._real_time_statistics is None: + self._real_time_statistics = TaskQueueRealTimeStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._real_time_statistics + + @property + def statistics(self) -> TaskQueueStatisticsList: + """ + Access the statistics + """ + if self._statistics is None: + self._statistics = TaskQueueStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._statistics + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.TaskQueueContext {}>".format(context) + + +class TaskQueuePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TaskQueueInstance: + """ + Build an instance of TaskQueueInstance + + :param payload: Payload response from the API + """ + return TaskQueueInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.TaskQueuePage>" + + +class TaskQueueList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the TaskQueueList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueue to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskQueues".format(**self._solution) + + self._bulk_real_time_statistics: Optional[ + TaskQueueBulkRealTimeStatisticsList + ] = None + self._statistics: Optional[TaskQueuesStatisticsList] = None + + def create( + self, + friendly_name: str, + target_workers: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + ) -> TaskQueueInstance: + """ + Create the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string that describes the Worker selection criteria for any Tasks that enter the TaskQueue. For example, `'\\\"language\\\" == \\\"spanish\\\"'`. The default value is `1==1`. If this value is empty, Tasks will wait in the TaskQueue until they are deleted or moved to another TaskQueue. For more information about Worker selection, see [Describing Worker selection criteria](https://www.twilio.com/docs/taskrouter/api/taskqueues#target-workers). + :param max_reserved_workers: The maximum number of Workers to reserve for the assignment of a Task in the queue. Can be an integer between 1 and 50, inclusive and defaults to 1. + :param task_order: + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned to them. + + :returns: The created TaskQueueInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "TargetWorkers": target_workers, + "MaxReservedWorkers": max_reserved_workers, + "TaskOrder": task_order, + "ReservationActivitySid": reservation_activity_sid, + "AssignmentActivitySid": assignment_activity_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskQueueInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_async( + self, + friendly_name: str, + target_workers: Union[str, object] = values.unset, + max_reserved_workers: Union[int, object] = values.unset, + task_order: Union["TaskQueueInstance.TaskOrder", object] = values.unset, + reservation_activity_sid: Union[str, object] = values.unset, + assignment_activity_sid: Union[str, object] = values.unset, + ) -> TaskQueueInstance: + """ + Asynchronously create the TaskQueueInstance + + :param friendly_name: A descriptive string that you create to describe the TaskQueue. For example `Support-Tier 1`, `Sales`, or `Escalation`. + :param target_workers: A string that describes the Worker selection criteria for any Tasks that enter the TaskQueue. For example, `'\\\"language\\\" == \\\"spanish\\\"'`. The default value is `1==1`. If this value is empty, Tasks will wait in the TaskQueue until they are deleted or moved to another TaskQueue. For more information about Worker selection, see [Describing Worker selection criteria](https://www.twilio.com/docs/taskrouter/api/taskqueues#target-workers). + :param max_reserved_workers: The maximum number of Workers to reserve for the assignment of a Task in the queue. Can be an integer between 1 and 50, inclusive and defaults to 1. + :param task_order: + :param reservation_activity_sid: The SID of the Activity to assign Workers when a task is reserved for them. + :param assignment_activity_sid: The SID of the Activity to assign Workers when a task is assigned to them. + + :returns: The created TaskQueueInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "TargetWorkers": target_workers, + "MaxReservedWorkers": max_reserved_workers, + "TaskOrder": task_order, + "ReservationActivitySid": reservation_activity_sid, + "AssignmentActivitySid": assignment_activity_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskQueueInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TaskQueueInstance]: + """ + Streams TaskQueueInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param str evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param str worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param str ordering: Sorting parameter for TaskQueues + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + friendly_name=friendly_name, + evaluate_worker_attributes=evaluate_worker_attributes, + worker_sid=worker_sid, + ordering=ordering, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TaskQueueInstance]: + """ + Asynchronously streams TaskQueueInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param str evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param str worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param str ordering: Sorting parameter for TaskQueues + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, + evaluate_worker_attributes=evaluate_worker_attributes, + worker_sid=worker_sid, + ordering=ordering, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskQueueInstance]: + """ + Lists TaskQueueInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param str evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param str worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param str ordering: Sorting parameter for TaskQueues + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + evaluate_worker_attributes=evaluate_worker_attributes, + worker_sid=worker_sid, + ordering=ordering, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskQueueInstance]: + """ + Asynchronously lists TaskQueueInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param str evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param str worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param str ordering: Sorting parameter for TaskQueues + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + evaluate_worker_attributes=evaluate_worker_attributes, + worker_sid=worker_sid, + ordering=ordering, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskQueuePage: + """ + Retrieve a single page of TaskQueueInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param ordering: Sorting parameter for TaskQueues + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskQueueInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "EvaluateWorkerAttributes": evaluate_worker_attributes, + "WorkerSid": worker_sid, + "Ordering": ordering, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskQueuePage(self._version, response, self._solution) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + evaluate_worker_attributes: Union[str, object] = values.unset, + worker_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskQueuePage: + """ + Asynchronously retrieve a single page of TaskQueueInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the TaskQueue resources to read. + :param evaluate_worker_attributes: The attributes of the Workers to read. Returns the TaskQueues with Workers that match the attributes specified in this parameter. + :param worker_sid: The SID of the Worker with the TaskQueue resources to read. + :param ordering: Sorting parameter for TaskQueues + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskQueueInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "EvaluateWorkerAttributes": evaluate_worker_attributes, + "WorkerSid": worker_sid, + "Ordering": ordering, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskQueuePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TaskQueuePage: + """ + Retrieve a specific page of TaskQueueInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskQueueInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TaskQueuePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TaskQueuePage: + """ + Asynchronously retrieve a specific page of TaskQueueInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskQueueInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TaskQueuePage(self._version, response, self._solution) + + @property + def bulk_real_time_statistics(self) -> TaskQueueBulkRealTimeStatisticsList: + """ + Access the bulk_real_time_statistics + """ + if self._bulk_real_time_statistics is None: + self._bulk_real_time_statistics = TaskQueueBulkRealTimeStatisticsList( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + return self._bulk_real_time_statistics + + @property + def statistics(self) -> TaskQueuesStatisticsList: + """ + Access the statistics + """ + if self._statistics is None: + self._statistics = TaskQueuesStatisticsList( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + return self._statistics + + def get(self, sid: str) -> TaskQueueContext: + """ + Constructs a TaskQueueContext + + :param sid: The SID of the TaskQueue resource to update. + """ + return TaskQueueContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __call__(self, sid: str) -> TaskQueueContext: + """ + Constructs a TaskQueueContext + + :param sid: The SID of the TaskQueue resource to update. + """ + return TaskQueueContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.TaskQueueList>" diff --git a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_bulk_real_time_statistics.py b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_bulk_real_time_statistics.py new file mode 100644 index 0000000000..90400c7930 --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_bulk_real_time_statistics.py @@ -0,0 +1,141 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TaskQueueBulkRealTimeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + :ivar workspace_sid: The SID of the Workspace that contains the TaskQueue. + :ivar task_queue_data: The real-time statistics for each requested TaskQueue SID. `task_queue_data` returns the following attributes: `task_queue_sid`: The SID of the TaskQueue from which these statistics were calculated. `total_available_workers`: The total number of Workers available for Tasks in the TaskQueue. `total_eligible_workers`: The total number of Workers eligible for Tasks in the TaskQueue, regardless of their Activity state. `total_tasks`: The total number of Tasks. `longest_task_waiting_age`: The age of the longest waiting Task. `longest_task_waiting_sid`: The SID of the longest waiting Task. `tasks_by_status`: The number of Tasks grouped by their current status. `tasks_by_priority`: The number of Tasks grouped by priority. `activity_statistics`: The number of current Workers grouped by Activity. + :ivar task_queue_response_count: The number of TaskQueue statistics received in task_queue_data. + :ivar url: The absolute URL of the TaskQueue statistics resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.task_queue_data: Optional[List[Dict[str, object]]] = payload.get( + "task_queue_data" + ) + self.task_queue_response_count: Optional[int] = deserialize.integer( + payload.get("task_queue_response_count") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return ( + "<Twilio.Taskrouter.V1.TaskQueueBulkRealTimeStatisticsInstance {}>".format( + context + ) + ) + + +class TaskQueueBulkRealTimeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the TaskQueueBulkRealTimeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The unique SID identifier of the Workspace. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskQueues/RealTimeStatistics".format( + **self._solution + ) + + def create( + self, body: Union[object, object] = values.unset + ) -> TaskQueueBulkRealTimeStatisticsInstance: + """ + Create the TaskQueueBulkRealTimeStatisticsInstance + + :param body: + + :returns: The created TaskQueueBulkRealTimeStatisticsInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskQueueBulkRealTimeStatisticsInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_async( + self, body: Union[object, object] = values.unset + ) -> TaskQueueBulkRealTimeStatisticsInstance: + """ + Asynchronously create the TaskQueueBulkRealTimeStatisticsInstance + + :param body: + + :returns: The created TaskQueueBulkRealTimeStatisticsInstance + """ + data = body.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TaskQueueBulkRealTimeStatisticsInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.TaskQueueBulkRealTimeStatisticsList>" diff --git a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_cumulative_statistics.py b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_cumulative_statistics.py new file mode 100644 index 0000000000..ef851c755a --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_cumulative_statistics.py @@ -0,0 +1,376 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TaskQueueCumulativeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + :ivar avg_task_acceptance_time: The average time in seconds between Task creation and acceptance. + :ivar start_time: The beginning of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar end_time: The end of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar reservations_created: The total number of Reservations created for Tasks in the TaskQueue. + :ivar reservations_accepted: The total number of Reservations accepted for Tasks in the TaskQueue. + :ivar reservations_rejected: The total number of Reservations rejected for Tasks in the TaskQueue. + :ivar reservations_timed_out: The total number of Reservations that timed out for Tasks in the TaskQueue. + :ivar reservations_canceled: The total number of Reservations canceled for Tasks in the TaskQueue. + :ivar reservations_rescinded: The total number of Reservations rescinded. + :ivar split_by_wait_time: A list of objects that describe the number of Tasks canceled and reservations accepted above and below the thresholds specified in seconds. + :ivar task_queue_sid: The SID of the TaskQueue from which these statistics were calculated. + :ivar wait_duration_until_accepted: The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks accepted while in the TaskQueue. Calculation is based on the time when the Tasks were created. For transfers, the wait duration is counted from the moment ***the Task was created***, and not from when the transfer was initiated. + :ivar wait_duration_until_canceled: The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks canceled while in the TaskQueue. + :ivar wait_duration_in_queue_until_accepted: The relative wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks accepted while in the TaskQueue. Calculation is based on the time when the Tasks entered the TaskQueue. + :ivar tasks_canceled: The total number of Tasks canceled in the TaskQueue. + :ivar tasks_completed: The total number of Tasks completed in the TaskQueue. + :ivar tasks_deleted: The total number of Tasks deleted in the TaskQueue. + :ivar tasks_entered: The total number of Tasks entered into the TaskQueue. + :ivar tasks_moved: The total number of Tasks that were moved from one queue to another. + :ivar workspace_sid: The SID of the Workspace that contains the TaskQueue. + :ivar url: The absolute URL of the TaskQueue statistics resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + task_queue_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.avg_task_acceptance_time: Optional[int] = deserialize.integer( + payload.get("avg_task_acceptance_time") + ) + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.reservations_created: Optional[int] = deserialize.integer( + payload.get("reservations_created") + ) + self.reservations_accepted: Optional[int] = deserialize.integer( + payload.get("reservations_accepted") + ) + self.reservations_rejected: Optional[int] = deserialize.integer( + payload.get("reservations_rejected") + ) + self.reservations_timed_out: Optional[int] = deserialize.integer( + payload.get("reservations_timed_out") + ) + self.reservations_canceled: Optional[int] = deserialize.integer( + payload.get("reservations_canceled") + ) + self.reservations_rescinded: Optional[int] = deserialize.integer( + payload.get("reservations_rescinded") + ) + self.split_by_wait_time: Optional[Dict[str, object]] = payload.get( + "split_by_wait_time" + ) + self.task_queue_sid: Optional[str] = payload.get("task_queue_sid") + self.wait_duration_until_accepted: Optional[Dict[str, object]] = payload.get( + "wait_duration_until_accepted" + ) + self.wait_duration_until_canceled: Optional[Dict[str, object]] = payload.get( + "wait_duration_until_canceled" + ) + self.wait_duration_in_queue_until_accepted: Optional[Dict[str, object]] = ( + payload.get("wait_duration_in_queue_until_accepted") + ) + self.tasks_canceled: Optional[int] = deserialize.integer( + payload.get("tasks_canceled") + ) + self.tasks_completed: Optional[int] = deserialize.integer( + payload.get("tasks_completed") + ) + self.tasks_deleted: Optional[int] = deserialize.integer( + payload.get("tasks_deleted") + ) + self.tasks_entered: Optional[int] = deserialize.integer( + payload.get("tasks_entered") + ) + self.tasks_moved: Optional[int] = deserialize.integer( + payload.get("tasks_moved") + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + self._context: Optional[TaskQueueCumulativeStatisticsContext] = None + + @property + def _proxy(self) -> "TaskQueueCumulativeStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TaskQueueCumulativeStatisticsContext for this TaskQueueCumulativeStatisticsInstance + """ + if self._context is None: + self._context = TaskQueueCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return self._context + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "TaskQueueCumulativeStatisticsInstance": + """ + Fetch the TaskQueueCumulativeStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. + + :returns: The fetched TaskQueueCumulativeStatisticsInstance + """ + return self._proxy.fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "TaskQueueCumulativeStatisticsInstance": + """ + Asynchronous coroutine to fetch the TaskQueueCumulativeStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. + + :returns: The fetched TaskQueueCumulativeStatisticsInstance + """ + return await self._proxy.fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.TaskQueueCumulativeStatisticsInstance {}>".format( + context + ) + + +class TaskQueueCumulativeStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): + """ + Initialize the TaskQueueCumulativeStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueue to fetch. + :param task_queue_sid: The SID of the TaskQueue for which to fetch statistics. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskQueues/{task_queue_sid}/CumulativeStatistics".format( + **self._solution + ) + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> TaskQueueCumulativeStatisticsInstance: + """ + Fetch the TaskQueueCumulativeStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. + + :returns: The fetched TaskQueueCumulativeStatisticsInstance + """ + + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return TaskQueueCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> TaskQueueCumulativeStatisticsInstance: + """ + Asynchronous coroutine to fetch the TaskQueueCumulativeStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. TaskRouter will calculate statistics on up to 10,000 Tasks/Reservations for any given threshold. + + :returns: The fetched TaskQueueCumulativeStatisticsInstance + """ + + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return TaskQueueCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.TaskQueueCumulativeStatisticsContext {}>".format( + context + ) + + +class TaskQueueCumulativeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): + """ + Initialize the TaskQueueCumulativeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueue to fetch. + :param task_queue_sid: The SID of the TaskQueue for which to fetch statistics. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + + def get(self) -> TaskQueueCumulativeStatisticsContext: + """ + Constructs a TaskQueueCumulativeStatisticsContext + + """ + return TaskQueueCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + def __call__(self) -> TaskQueueCumulativeStatisticsContext: + """ + Constructs a TaskQueueCumulativeStatisticsContext + + """ + return TaskQueueCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.TaskQueueCumulativeStatisticsList>" diff --git a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_real_time_statistics.py b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_real_time_statistics.py new file mode 100644 index 0000000000..c4eb30ddc0 --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_real_time_statistics.py @@ -0,0 +1,291 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TaskQueueRealTimeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + :ivar activity_statistics: The number of current Workers by Activity. + :ivar longest_task_waiting_age: The age of the longest waiting Task. + :ivar longest_task_waiting_sid: The SID of the longest waiting Task. + :ivar longest_relative_task_age_in_queue: The relative age in the TaskQueue for the longest waiting Task. Calculation is based on the time when the Task entered the TaskQueue. + :ivar longest_relative_task_sid_in_queue: The Task SID of the Task waiting in the TaskQueue the longest. Calculation is based on the time when the Task entered the TaskQueue. + :ivar task_queue_sid: The SID of the TaskQueue from which these statistics were calculated. + :ivar tasks_by_priority: The number of Tasks by priority. For example: `{\"0\": \"10\", \"99\": \"5\"}` shows 10 Tasks at priority 0 and 5 at priority 99. + :ivar tasks_by_status: The number of Tasks by their current status. For example: `{\"pending\": \"1\", \"reserved\": \"3\", \"assigned\": \"2\", \"completed\": \"5\"}`. + :ivar total_available_workers: The total number of Workers in the TaskQueue with an `available` status. Workers with an `available` status may already have active interactions or may have none. + :ivar total_eligible_workers: The total number of Workers eligible for Tasks in the TaskQueue, independent of their Activity state. + :ivar total_tasks: The total number of Tasks. + :ivar workspace_sid: The SID of the Workspace that contains the TaskQueue. + :ivar url: The absolute URL of the TaskQueue statistics resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + task_queue_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.activity_statistics: Optional[List[Dict[str, object]]] = payload.get( + "activity_statistics" + ) + self.longest_task_waiting_age: Optional[int] = deserialize.integer( + payload.get("longest_task_waiting_age") + ) + self.longest_task_waiting_sid: Optional[str] = payload.get( + "longest_task_waiting_sid" + ) + self.longest_relative_task_age_in_queue: Optional[int] = deserialize.integer( + payload.get("longest_relative_task_age_in_queue") + ) + self.longest_relative_task_sid_in_queue: Optional[str] = payload.get( + "longest_relative_task_sid_in_queue" + ) + self.task_queue_sid: Optional[str] = payload.get("task_queue_sid") + self.tasks_by_priority: Optional[Dict[str, object]] = payload.get( + "tasks_by_priority" + ) + self.tasks_by_status: Optional[Dict[str, object]] = payload.get( + "tasks_by_status" + ) + self.total_available_workers: Optional[int] = deserialize.integer( + payload.get("total_available_workers") + ) + self.total_eligible_workers: Optional[int] = deserialize.integer( + payload.get("total_eligible_workers") + ) + self.total_tasks: Optional[int] = deserialize.integer( + payload.get("total_tasks") + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + self._context: Optional[TaskQueueRealTimeStatisticsContext] = None + + @property + def _proxy(self) -> "TaskQueueRealTimeStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TaskQueueRealTimeStatisticsContext for this TaskQueueRealTimeStatisticsInstance + """ + if self._context is None: + self._context = TaskQueueRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return self._context + + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> "TaskQueueRealTimeStatisticsInstance": + """ + Fetch the TaskQueueRealTimeStatisticsInstance + + :param task_channel: The TaskChannel for which to fetch statistics. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched TaskQueueRealTimeStatisticsInstance + """ + return self._proxy.fetch( + task_channel=task_channel, + ) + + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> "TaskQueueRealTimeStatisticsInstance": + """ + Asynchronous coroutine to fetch the TaskQueueRealTimeStatisticsInstance + + :param task_channel: The TaskChannel for which to fetch statistics. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched TaskQueueRealTimeStatisticsInstance + """ + return await self._proxy.fetch_async( + task_channel=task_channel, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.TaskQueueRealTimeStatisticsInstance {}>".format( + context + ) + + +class TaskQueueRealTimeStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): + """ + Initialize the TaskQueueRealTimeStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueue to fetch. + :param task_queue_sid: The SID of the TaskQueue for which to fetch statistics. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskQueues/{task_queue_sid}/RealTimeStatistics".format( + **self._solution + ) + + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> TaskQueueRealTimeStatisticsInstance: + """ + Fetch the TaskQueueRealTimeStatisticsInstance + + :param task_channel: The TaskChannel for which to fetch statistics. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched TaskQueueRealTimeStatisticsInstance + """ + + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return TaskQueueRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> TaskQueueRealTimeStatisticsInstance: + """ + Asynchronous coroutine to fetch the TaskQueueRealTimeStatisticsInstance + + :param task_channel: The TaskChannel for which to fetch statistics. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched TaskQueueRealTimeStatisticsInstance + """ + + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return TaskQueueRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.TaskQueueRealTimeStatisticsContext {}>".format( + context + ) + + +class TaskQueueRealTimeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): + """ + Initialize the TaskQueueRealTimeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueue to fetch. + :param task_queue_sid: The SID of the TaskQueue for which to fetch statistics. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + + def get(self) -> TaskQueueRealTimeStatisticsContext: + """ + Constructs a TaskQueueRealTimeStatisticsContext + + """ + return TaskQueueRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + def __call__(self) -> TaskQueueRealTimeStatisticsContext: + """ + Constructs a TaskQueueRealTimeStatisticsContext + + """ + return TaskQueueRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.TaskQueueRealTimeStatisticsList>" diff --git a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_statistics.py b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_statistics.py new file mode 100644 index 0000000000..2d5d631069 --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_statistics.py @@ -0,0 +1,306 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class TaskQueueStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + :ivar cumulative: An object that contains the cumulative statistics for the TaskQueue. + :ivar realtime: An object that contains the real-time statistics for the TaskQueue. + :ivar task_queue_sid: The SID of the TaskQueue from which these statistics were calculated. + :ivar workspace_sid: The SID of the Workspace that contains the TaskQueue. + :ivar url: The absolute URL of the TaskQueue statistics resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + task_queue_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.cumulative: Optional[Dict[str, object]] = payload.get("cumulative") + self.realtime: Optional[Dict[str, object]] = payload.get("realtime") + self.task_queue_sid: Optional[str] = payload.get("task_queue_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + self._context: Optional[TaskQueueStatisticsContext] = None + + @property + def _proxy(self) -> "TaskQueueStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TaskQueueStatisticsContext for this TaskQueueStatisticsInstance + """ + if self._context is None: + self._context = TaskQueueStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + return self._context + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "TaskQueueStatisticsInstance": + """ + Fetch the TaskQueueStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + + :returns: The fetched TaskQueueStatisticsInstance + """ + return self._proxy.fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "TaskQueueStatisticsInstance": + """ + Asynchronous coroutine to fetch the TaskQueueStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + + :returns: The fetched TaskQueueStatisticsInstance + """ + return await self._proxy.fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.TaskQueueStatisticsInstance {}>".format(context) + + +class TaskQueueStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): + """ + Initialize the TaskQueueStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueue to fetch. + :param task_queue_sid: The SID of the TaskQueue for which to fetch statistics. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + self._uri = ( + "/Workspaces/{workspace_sid}/TaskQueues/{task_queue_sid}/Statistics".format( + **self._solution + ) + ) + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> TaskQueueStatisticsInstance: + """ + Fetch the TaskQueueStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + + :returns: The fetched TaskQueueStatisticsInstance + """ + + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return TaskQueueStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> TaskQueueStatisticsInstance: + """ + Asynchronous coroutine to fetch the TaskQueueStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate real-time and cumulative statistics for the specified TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + + :returns: The fetched TaskQueueStatisticsInstance + """ + + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return TaskQueueStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.TaskQueueStatisticsContext {}>".format(context) + + +class TaskQueueStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): + """ + Initialize the TaskQueueStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueue to fetch. + :param task_queue_sid: The SID of the TaskQueue for which to fetch statistics. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "task_queue_sid": task_queue_sid, + } + + def get(self) -> TaskQueueStatisticsContext: + """ + Constructs a TaskQueueStatisticsContext + + """ + return TaskQueueStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + def __call__(self) -> TaskQueueStatisticsContext: + """ + Constructs a TaskQueueStatisticsContext + + """ + return TaskQueueStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + task_queue_sid=self._solution["task_queue_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.TaskQueueStatisticsList>" diff --git a/twilio/rest/taskrouter/v1/workspace/task_queue/task_queues_statistics.py b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queues_statistics.py new file mode 100644 index 0000000000..036f6ad92b --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queues_statistics.py @@ -0,0 +1,409 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TaskQueuesStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + :ivar cumulative: An object that contains the cumulative statistics for the TaskQueues. + :ivar realtime: An object that contains the real-time statistics for the TaskQueues. + :ivar task_queue_sid: The SID of the TaskQueue from which these statistics were calculated. + :ivar workspace_sid: The SID of the Workspace that contains the TaskQueues. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.cumulative: Optional[Dict[str, object]] = payload.get("cumulative") + self.realtime: Optional[Dict[str, object]] = payload.get("realtime") + self.task_queue_sid: Optional[str] = payload.get("task_queue_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + + self._solution = { + "workspace_sid": workspace_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.TaskQueuesStatisticsInstance {}>".format(context) + + +class TaskQueuesStatisticsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TaskQueuesStatisticsInstance: + """ + Build an instance of TaskQueuesStatisticsInstance + + :param payload: Payload response from the API + """ + return TaskQueuesStatisticsInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.TaskQueuesStatisticsPage>" + + +class TaskQueuesStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the TaskQueuesStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the TaskQueues to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskQueues/Statistics".format( + **self._solution + ) + + def stream( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TaskQueuesStatisticsInstance]: + """ + Streams TaskQueuesStatisticsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param int minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param datetime start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param str task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param str split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TaskQueuesStatisticsInstance]: + """ + Asynchronously streams TaskQueuesStatisticsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param int minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param datetime start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param str task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param str split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskQueuesStatisticsInstance]: + """ + Lists TaskQueuesStatisticsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param int minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param datetime start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param str task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param str split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TaskQueuesStatisticsInstance]: + """ + Asynchronously lists TaskQueuesStatisticsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param str friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param int minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param datetime start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param str task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param str split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + end_date=end_date, + friendly_name=friendly_name, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskQueuesStatisticsPage: + """ + Retrieve a single page of TaskQueuesStatisticsInstance records from the API. + Request is executed immediately + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskQueuesStatisticsInstance + """ + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "FriendlyName": friendly_name, + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskQueuesStatisticsPage(self._version, response, self._solution) + + async def page_async( + self, + end_date: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TaskQueuesStatisticsPage: + """ + Asynchronously retrieve a single page of TaskQueuesStatisticsInstance records from the API. + Request is executed immediately + + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param friendly_name: The `friendly_name` of the TaskQueue statistics to read. + :param minutes: Only calculate statistics since this many minutes in the past. The default is 15 minutes. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TaskQueuesStatisticsInstance + """ + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "FriendlyName": friendly_name, + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TaskQueuesStatisticsPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TaskQueuesStatisticsPage: + """ + Retrieve a specific page of TaskQueuesStatisticsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskQueuesStatisticsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TaskQueuesStatisticsPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TaskQueuesStatisticsPage: + """ + Asynchronously retrieve a specific page of TaskQueuesStatisticsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TaskQueuesStatisticsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TaskQueuesStatisticsPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.TaskQueuesStatisticsList>" diff --git a/twilio/rest/taskrouter/v1/workspace/worker/__init__.py b/twilio/rest/taskrouter/v1/workspace/worker/__init__.py new file mode 100644 index 0000000000..38aede84bb --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/worker/__init__.py @@ -0,0 +1,1009 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.taskrouter.v1.workspace.worker.reservation import ReservationList +from twilio.rest.taskrouter.v1.workspace.worker.worker_channel import WorkerChannelList +from twilio.rest.taskrouter.v1.workspace.worker.worker_statistics import ( + WorkerStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics import ( + WorkersCumulativeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics import ( + WorkersRealTimeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.worker.workers_statistics import ( + WorkersStatisticsList, +) + + +class WorkerInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. + :ivar activity_name: The `friendly_name` of the Worker's current Activity. + :ivar activity_sid: The SID of the Worker's current Activity. + :ivar attributes: The JSON string that describes the Worker. For example: `{ \"email\": \"Bob@example.com\", \"phone\": \"+5095551234\" }`. **Note** If this property has been assigned a value, it will only be displayed in FETCH actions that return a single resource. Otherwise, this property will be null, even if it has a value. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. + :ivar available: Whether the Worker is available to perform tasks. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_status_changed: The date and time in GMT of the last change to the Worker's activity specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. Used to calculate Workflow statistics. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar friendly_name: The string that you assigned to describe the resource. Friendly names are case insensitive, and unique within the TaskRouter Workspace. + :ivar sid: The unique string that we created to identify the Worker resource. + :ivar workspace_sid: The SID of the Workspace that contains the Worker. + :ivar url: The absolute URL of the Worker resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.activity_name: Optional[str] = payload.get("activity_name") + self.activity_sid: Optional[str] = payload.get("activity_sid") + self.attributes: Optional[str] = payload.get("attributes") + self.available: Optional[bool] = payload.get("available") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_status_changed: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_status_changed") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid or self.sid, + } + self._context: Optional[WorkerContext] = None + + @property + def _proxy(self) -> "WorkerContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkerContext for this WorkerInstance + """ + if self._context is None: + self._context = WorkerContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Deletes the WorkerInstance + + :param if_match: The If-Match HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete( + if_match=if_match, + ) + + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Asynchronous coroutine that deletes the WorkerInstance + + :param if_match: The If-Match HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async( + if_match=if_match, + ) + + def fetch(self) -> "WorkerInstance": + """ + Fetch the WorkerInstance + + + :returns: The fetched WorkerInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WorkerInstance": + """ + Asynchronous coroutine to fetch the WorkerInstance + + + :returns: The fetched WorkerInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + if_match: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reject_pending_reservations: Union[bool, object] = values.unset, + ) -> "WorkerInstance": + """ + Update the WorkerInstance + + :param if_match: The If-Match HTTP request header + :param activity_sid: The SID of a valid Activity that will describe the Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. + :param attributes: The JSON string that describes the Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + :param friendly_name: A descriptive string that you create to describe the Worker. It can be up to 64 characters long. + :param reject_pending_reservations: Whether to reject the Worker's pending reservations. This option is only valid if the Worker's new [Activity](https://www.twilio.com/docs/taskrouter/api/activity) resource has its `availability` property set to `False`. + + :returns: The updated WorkerInstance + """ + return self._proxy.update( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reject_pending_reservations: Union[bool, object] = values.unset, + ) -> "WorkerInstance": + """ + Asynchronous coroutine to update the WorkerInstance + + :param if_match: The If-Match HTTP request header + :param activity_sid: The SID of a valid Activity that will describe the Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. + :param attributes: The JSON string that describes the Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + :param friendly_name: A descriptive string that you create to describe the Worker. It can be up to 64 characters long. + :param reject_pending_reservations: Whether to reject the Worker's pending reservations. This option is only valid if the Worker's new [Activity](https://www.twilio.com/docs/taskrouter/api/activity) resource has its `availability` property set to `False`. + + :returns: The updated WorkerInstance + """ + return await self._proxy.update_async( + if_match=if_match, + activity_sid=activity_sid, + attributes=attributes, + friendly_name=friendly_name, + reject_pending_reservations=reject_pending_reservations, + ) + + @property + def reservations(self) -> ReservationList: + """ + Access the reservations + """ + return self._proxy.reservations + + @property + def worker_channels(self) -> WorkerChannelList: + """ + Access the worker_channels + """ + return self._proxy.worker_channels + + @property + def statistics(self) -> WorkerStatisticsList: + """ + Access the statistics + """ + return self._proxy.statistics + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkerInstance {}>".format(context) + + +class WorkerContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, sid: str): + """ + Initialize the WorkerContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Worker to update. + :param sid: The SID of the Worker resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers/{sid}".format(**self._solution) + + self._reservations: Optional[ReservationList] = None + self._worker_channels: Optional[WorkerChannelList] = None + self._statistics: Optional[WorkerStatisticsList] = None + + def delete(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Deletes the WorkerInstance + + :param if_match: The If-Match HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self, if_match: Union[str, object] = values.unset) -> bool: + """ + Asynchronous coroutine that deletes the WorkerInstance + + :param if_match: The If-Match HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> WorkerInstance: + """ + Fetch the WorkerInstance + + + :returns: The fetched WorkerInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WorkerInstance: + """ + Asynchronous coroutine to fetch the WorkerInstance + + + :returns: The fetched WorkerInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reject_pending_reservations: Union[bool, object] = values.unset, + ) -> WorkerInstance: + """ + Update the WorkerInstance + + :param if_match: The If-Match HTTP request header + :param activity_sid: The SID of a valid Activity that will describe the Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. + :param attributes: The JSON string that describes the Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + :param friendly_name: A descriptive string that you create to describe the Worker. It can be up to 64 characters long. + :param reject_pending_reservations: Whether to reject the Worker's pending reservations. This option is only valid if the Worker's new [Activity](https://www.twilio.com/docs/taskrouter/api/activity) resource has its `availability` property set to `False`. + + :returns: The updated WorkerInstance + """ + + data = values.of( + { + "ActivitySid": activity_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + "RejectPendingReservations": serialize.boolean_to_string( + reject_pending_reservations + ), + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + reject_pending_reservations: Union[bool, object] = values.unset, + ) -> WorkerInstance: + """ + Asynchronous coroutine to update the WorkerInstance + + :param if_match: The If-Match HTTP request header + :param activity_sid: The SID of a valid Activity that will describe the Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. + :param attributes: The JSON string that describes the Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + :param friendly_name: A descriptive string that you create to describe the Worker. It can be up to 64 characters long. + :param reject_pending_reservations: Whether to reject the Worker's pending reservations. This option is only valid if the Worker's new [Activity](https://www.twilio.com/docs/taskrouter/api/activity) resource has its `availability` property set to `False`. + + :returns: The updated WorkerInstance + """ + + data = values.of( + { + "ActivitySid": activity_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + "RejectPendingReservations": serialize.boolean_to_string( + reject_pending_reservations + ), + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + @property + def reservations(self) -> ReservationList: + """ + Access the reservations + """ + if self._reservations is None: + self._reservations = ReservationList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._reservations + + @property + def worker_channels(self) -> WorkerChannelList: + """ + Access the worker_channels + """ + if self._worker_channels is None: + self._worker_channels = WorkerChannelList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._worker_channels + + @property + def statistics(self) -> WorkerStatisticsList: + """ + Access the statistics + """ + if self._statistics is None: + self._statistics = WorkerStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._statistics + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkerContext {}>".format(context) + + +class WorkerPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WorkerInstance: + """ + Build an instance of WorkerInstance + + :param payload: Payload response from the API + """ + return WorkerInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.WorkerPage>" + + +class WorkerList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkerList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workers to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers".format(**self._solution) + + self._cumulative_statistics: Optional[WorkersCumulativeStatisticsList] = None + self._real_time_statistics: Optional[WorkersRealTimeStatisticsList] = None + self._statistics: Optional[WorkersStatisticsList] = None + + def create( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> WorkerInstance: + """ + Create the WorkerInstance + + :param friendly_name: A descriptive string that you create to describe the new Worker. It can be up to 64 characters long. + :param activity_sid: The SID of a valid Activity that will describe the new Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. If not provided, the new Worker's initial state is the `default_activity_sid` configured on the Workspace. + :param attributes: A valid JSON string that describes the new Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + + :returns: The created WorkerInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ActivitySid": activity_sid, + "Attributes": attributes, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkerInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_async( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> WorkerInstance: + """ + Asynchronously create the WorkerInstance + + :param friendly_name: A descriptive string that you create to describe the new Worker. It can be up to 64 characters long. + :param activity_sid: The SID of a valid Activity that will describe the new Worker's initial state. See [Activities](https://www.twilio.com/docs/taskrouter/api/activity) for more information. If not provided, the new Worker's initial state is the `default_activity_sid` configured on the Workspace. + :param attributes: A valid JSON string that describes the new Worker. For example: `{ \\\"email\\\": \\\"Bob@example.com\\\", \\\"phone\\\": \\\"+5095551234\\\" }`. This data is passed to the `assignment_callback_url` when TaskRouter assigns a Task to the Worker. Defaults to {}. + + :returns: The created WorkerInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ActivitySid": activity_sid, + "Attributes": attributes, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkerInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def stream( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WorkerInstance]: + """ + Streams WorkerInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str activity_name: The `activity_name` of the Worker resources to read. + :param str activity_sid: The `activity_sid` of the Worker resources to read. + :param str available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param str friendly_name: The `friendly_name` of the Worker resources to read. + :param str target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param str task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param str task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param str ordering: Sorting parameter for Workers + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + activity_name=activity_name, + activity_sid=activity_sid, + available=available, + friendly_name=friendly_name, + target_workers_expression=target_workers_expression, + task_queue_name=task_queue_name, + task_queue_sid=task_queue_sid, + ordering=ordering, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WorkerInstance]: + """ + Asynchronously streams WorkerInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str activity_name: The `activity_name` of the Worker resources to read. + :param str activity_sid: The `activity_sid` of the Worker resources to read. + :param str available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param str friendly_name: The `friendly_name` of the Worker resources to read. + :param str target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param str task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param str task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param str ordering: Sorting parameter for Workers + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + activity_name=activity_name, + activity_sid=activity_sid, + available=available, + friendly_name=friendly_name, + target_workers_expression=target_workers_expression, + task_queue_name=task_queue_name, + task_queue_sid=task_queue_sid, + ordering=ordering, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkerInstance]: + """ + Lists WorkerInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str activity_name: The `activity_name` of the Worker resources to read. + :param str activity_sid: The `activity_sid` of the Worker resources to read. + :param str available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param str friendly_name: The `friendly_name` of the Worker resources to read. + :param str target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param str task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param str task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param str ordering: Sorting parameter for Workers + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + activity_name=activity_name, + activity_sid=activity_sid, + available=available, + friendly_name=friendly_name, + target_workers_expression=target_workers_expression, + task_queue_name=task_queue_name, + task_queue_sid=task_queue_sid, + ordering=ordering, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkerInstance]: + """ + Asynchronously lists WorkerInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str activity_name: The `activity_name` of the Worker resources to read. + :param str activity_sid: The `activity_sid` of the Worker resources to read. + :param str available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param str friendly_name: The `friendly_name` of the Worker resources to read. + :param str target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param str task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param str task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param str ordering: Sorting parameter for Workers + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + activity_name=activity_name, + activity_sid=activity_sid, + available=available, + friendly_name=friendly_name, + target_workers_expression=target_workers_expression, + task_queue_name=task_queue_name, + task_queue_sid=task_queue_sid, + ordering=ordering, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkerPage: + """ + Retrieve a single page of WorkerInstance records from the API. + Request is executed immediately + + :param activity_name: The `activity_name` of the Worker resources to read. + :param activity_sid: The `activity_sid` of the Worker resources to read. + :param available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param friendly_name: The `friendly_name` of the Worker resources to read. + :param target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param ordering: Sorting parameter for Workers + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkerInstance + """ + data = values.of( + { + "ActivityName": activity_name, + "ActivitySid": activity_sid, + "Available": available, + "FriendlyName": friendly_name, + "TargetWorkersExpression": target_workers_expression, + "TaskQueueName": task_queue_name, + "TaskQueueSid": task_queue_sid, + "Ordering": ordering, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkerPage(self._version, response, self._solution) + + async def page_async( + self, + activity_name: Union[str, object] = values.unset, + activity_sid: Union[str, object] = values.unset, + available: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + target_workers_expression: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + ordering: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkerPage: + """ + Asynchronously retrieve a single page of WorkerInstance records from the API. + Request is executed immediately + + :param activity_name: The `activity_name` of the Worker resources to read. + :param activity_sid: The `activity_sid` of the Worker resources to read. + :param available: Whether to return only Worker resources that are available or unavailable. Can be `true`, `1`, or `yes` to return Worker resources that are available, and `false`, or any value returns the Worker resources that are not available. + :param friendly_name: The `friendly_name` of the Worker resources to read. + :param target_workers_expression: Filter by Workers that would match an expression. In addition to fields in the workers' attributes, the expression can include the following worker fields: `sid`, `friendly_name`, `activity_sid`, or `activity_name` + :param task_queue_name: The `friendly_name` of the TaskQueue that the Workers to read are eligible for. + :param task_queue_sid: The SID of the TaskQueue that the Workers to read are eligible for. + :param ordering: Sorting parameter for Workers + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkerInstance + """ + data = values.of( + { + "ActivityName": activity_name, + "ActivitySid": activity_sid, + "Available": available, + "FriendlyName": friendly_name, + "TargetWorkersExpression": target_workers_expression, + "TaskQueueName": task_queue_name, + "TaskQueueSid": task_queue_sid, + "Ordering": ordering, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkerPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> WorkerPage: + """ + Retrieve a specific page of WorkerInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkerInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WorkerPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> WorkerPage: + """ + Asynchronously retrieve a specific page of WorkerInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkerInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WorkerPage(self._version, response, self._solution) + + @property + def cumulative_statistics(self) -> WorkersCumulativeStatisticsList: + """ + Access the cumulative_statistics + """ + if self._cumulative_statistics is None: + self._cumulative_statistics = WorkersCumulativeStatisticsList( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + return self._cumulative_statistics + + @property + def real_time_statistics(self) -> WorkersRealTimeStatisticsList: + """ + Access the real_time_statistics + """ + if self._real_time_statistics is None: + self._real_time_statistics = WorkersRealTimeStatisticsList( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + return self._real_time_statistics + + @property + def statistics(self) -> WorkersStatisticsList: + """ + Access the statistics + """ + if self._statistics is None: + self._statistics = WorkersStatisticsList( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + return self._statistics + + def get(self, sid: str) -> WorkerContext: + """ + Constructs a WorkerContext + + :param sid: The SID of the Worker resource to update. + """ + return WorkerContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __call__(self, sid: str) -> WorkerContext: + """ + Constructs a WorkerContext + + :param sid: The SID of the Worker resource to update. + """ + return WorkerContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.WorkerList>" diff --git a/twilio/rest/taskrouter/v1/workspace/worker/reservation.py b/twilio/rest/taskrouter/v1/workspace/worker/reservation.py new file mode 100644 index 0000000000..7f24057806 --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/worker/reservation.py @@ -0,0 +1,1294 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ReservationInstance(InstanceResource): + + class CallStatus(object): + INITIATED = "initiated" + RINGING = "ringing" + ANSWERED = "answered" + COMPLETED = "completed" + + class ConferenceEvent(object): + START = "start" + END = "end" + JOIN = "join" + LEAVE = "leave" + MUTE = "mute" + HOLD = "hold" + SPEAKER = "speaker" + + class Status(object): + PENDING = "pending" + ACCEPTED = "accepted" + REJECTED = "rejected" + TIMEOUT = "timeout" + CANCELED = "canceled" + RESCINDED = "rescinded" + WRAPPING = "wrapping" + COMPLETED = "completed" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the WorkerReservation resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar reservation_status: + :ivar sid: The unique string that we created to identify the WorkerReservation resource. + :ivar task_sid: The SID of the reserved Task resource. + :ivar worker_name: The `friendly_name` of the Worker that is reserved. + :ivar worker_sid: The SID of the reserved Worker resource. + :ivar workspace_sid: The SID of the Workspace that this worker is contained within. + :ivar url: The absolute URL of the WorkerReservation resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + worker_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.reservation_status: Optional["ReservationInstance.Status"] = payload.get( + "reservation_status" + ) + self.sid: Optional[str] = payload.get("sid") + self.task_sid: Optional[str] = payload.get("task_sid") + self.worker_name: Optional[str] = payload.get("worker_name") + self.worker_sid: Optional[str] = payload.get("worker_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + "sid": sid or self.sid, + } + self._context: Optional[ReservationContext] = None + + @property + def _proxy(self) -> "ReservationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ReservationContext for this ReservationInstance + """ + if self._context is None: + self._context = ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ReservationInstance": + """ + Fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ReservationInstance": + """ + Asynchronous coroutine to fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> "ReservationInstance": + """ + Update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for the reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: The timeout for call when executing a Dequeue instruction. + :param dequeue_to: The contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction. + :param call_timeout: The timeout for a call when executing a Call instruction. + :param call_to: The contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: The timeout for a call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Defaults to `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants allowed in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + return self._proxy.update( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> "ReservationInstance": + """ + Asynchronous coroutine to update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for the reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: The timeout for call when executing a Dequeue instruction. + :param dequeue_to: The contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction. + :param call_timeout: The timeout for a call when executing a Call instruction. + :param call_to: The contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: The timeout for a call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Defaults to `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants allowed in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + return await self._proxy.update_async( + if_match=if_match, + reservation_status=reservation_status, + worker_activity_sid=worker_activity_sid, + instruction=instruction, + dequeue_post_work_activity_sid=dequeue_post_work_activity_sid, + dequeue_from=dequeue_from, + dequeue_record=dequeue_record, + dequeue_timeout=dequeue_timeout, + dequeue_to=dequeue_to, + dequeue_status_callback_url=dequeue_status_callback_url, + call_from=call_from, + call_record=call_record, + call_timeout=call_timeout, + call_to=call_to, + call_url=call_url, + call_status_callback_url=call_status_callback_url, + call_accept=call_accept, + redirect_call_sid=redirect_call_sid, + redirect_accept=redirect_accept, + redirect_url=redirect_url, + to=to, + from_=from_, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + timeout=timeout, + record=record, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + early_media=early_media, + max_participants=max_participants, + conference_status_callback=conference_status_callback, + conference_status_callback_method=conference_status_callback_method, + conference_status_callback_event=conference_status_callback_event, + conference_record=conference_record, + conference_trim=conference_trim, + recording_channels=recording_channels, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + conference_recording_status_callback=conference_recording_status_callback, + conference_recording_status_callback_method=conference_recording_status_callback_method, + region=region, + sip_auth_username=sip_auth_username, + sip_auth_password=sip_auth_password, + dequeue_status_callback_event=dequeue_status_callback_event, + post_work_activity_sid=post_work_activity_sid, + end_conference_on_customer_exit=end_conference_on_customer_exit, + beep_on_customer_entrance=beep_on_customer_entrance, + jitter_buffer_size=jitter_buffer_size, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.ReservationInstance {}>".format(context) + + +class ReservationContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, worker_sid: str, sid: str): + """ + Initialize the ReservationContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the WorkerReservation resources to update. + :param worker_sid: The SID of the reserved Worker resource with the WorkerReservation resources to update. + :param sid: The SID of the WorkerReservation resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers/{worker_sid}/Reservations/{sid}".format( + **self._solution + ) + + def fetch(self) -> ReservationInstance: + """ + Fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ReservationInstance: + """ + Asynchronous coroutine to fetch the ReservationInstance + + + :returns: The fetched ReservationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ReservationInstance: + """ + Update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for the reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: The timeout for call when executing a Dequeue instruction. + :param dequeue_to: The contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction. + :param call_timeout: The timeout for a call when executing a Call instruction. + :param call_to: The contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: The timeout for a call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Defaults to `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants allowed in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerActivitySid": worker_activity_sid, + "Instruction": instruction, + "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, + "DequeueFrom": dequeue_from, + "DequeueRecord": dequeue_record, + "DequeueTimeout": dequeue_timeout, + "DequeueTo": dequeue_to, + "DequeueStatusCallbackUrl": dequeue_status_callback_url, + "CallFrom": call_from, + "CallRecord": call_record, + "CallTimeout": call_timeout, + "CallTo": call_to, + "CallUrl": call_url, + "CallStatusCallbackUrl": call_status_callback_url, + "CallAccept": serialize.boolean_to_string(call_accept), + "RedirectCallSid": redirect_call_sid, + "RedirectAccept": serialize.boolean_to_string(redirect_accept), + "RedirectUrl": redirect_url, + "To": to, + "From": from_, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), + "Beep": beep, + "StartConferenceOnEnter": serialize.boolean_to_string( + start_conference_on_enter + ), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "EarlyMedia": serialize.boolean_to_string(early_media), + "MaxParticipants": max_participants, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "Region": region, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "DequeueStatusCallbackEvent": serialize.map( + dequeue_status_callback_event, lambda e: e + ), + "PostWorkActivitySid": post_work_activity_sid, + "EndConferenceOnCustomerExit": serialize.boolean_to_string( + end_conference_on_customer_exit + ), + "BeepOnCustomerEntrance": serialize.boolean_to_string( + beep_on_customer_entrance + ), + "JitterBufferSize": jitter_buffer_size, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + if_match: Union[str, object] = values.unset, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + worker_activity_sid: Union[str, object] = values.unset, + instruction: Union[str, object] = values.unset, + dequeue_post_work_activity_sid: Union[str, object] = values.unset, + dequeue_from: Union[str, object] = values.unset, + dequeue_record: Union[str, object] = values.unset, + dequeue_timeout: Union[int, object] = values.unset, + dequeue_to: Union[str, object] = values.unset, + dequeue_status_callback_url: Union[str, object] = values.unset, + call_from: Union[str, object] = values.unset, + call_record: Union[str, object] = values.unset, + call_timeout: Union[int, object] = values.unset, + call_to: Union[str, object] = values.unset, + call_url: Union[str, object] = values.unset, + call_status_callback_url: Union[str, object] = values.unset, + call_accept: Union[bool, object] = values.unset, + redirect_call_sid: Union[str, object] = values.unset, + redirect_accept: Union[bool, object] = values.unset, + redirect_url: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + from_: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + status_callback_event: Union[ + List["ReservationInstance.CallStatus"], object + ] = values.unset, + timeout: Union[int, object] = values.unset, + record: Union[bool, object] = values.unset, + muted: Union[bool, object] = values.unset, + beep: Union[str, object] = values.unset, + start_conference_on_enter: Union[bool, object] = values.unset, + end_conference_on_exit: Union[bool, object] = values.unset, + wait_url: Union[str, object] = values.unset, + wait_method: Union[str, object] = values.unset, + early_media: Union[bool, object] = values.unset, + max_participants: Union[int, object] = values.unset, + conference_status_callback: Union[str, object] = values.unset, + conference_status_callback_method: Union[str, object] = values.unset, + conference_status_callback_event: Union[ + List["ReservationInstance.ConferenceEvent"], object + ] = values.unset, + conference_record: Union[str, object] = values.unset, + conference_trim: Union[str, object] = values.unset, + recording_channels: Union[str, object] = values.unset, + recording_status_callback: Union[str, object] = values.unset, + recording_status_callback_method: Union[str, object] = values.unset, + conference_recording_status_callback: Union[str, object] = values.unset, + conference_recording_status_callback_method: Union[str, object] = values.unset, + region: Union[str, object] = values.unset, + sip_auth_username: Union[str, object] = values.unset, + sip_auth_password: Union[str, object] = values.unset, + dequeue_status_callback_event: Union[List[str], object] = values.unset, + post_work_activity_sid: Union[str, object] = values.unset, + end_conference_on_customer_exit: Union[bool, object] = values.unset, + beep_on_customer_entrance: Union[bool, object] = values.unset, + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ReservationInstance: + """ + Asynchronous coroutine to update the ReservationInstance + + :param if_match: The If-Match HTTP request header + :param reservation_status: + :param worker_activity_sid: The new worker activity SID if rejecting a reservation. + :param instruction: The assignment instruction for the reservation. + :param dequeue_post_work_activity_sid: The SID of the Activity resource to start after executing a Dequeue instruction. + :param dequeue_from: The caller ID of the call to the worker when executing a Dequeue instruction. + :param dequeue_record: Whether to record both legs of a call when executing a Dequeue instruction or which leg to record. + :param dequeue_timeout: The timeout for call when executing a Dequeue instruction. + :param dequeue_to: The contact URI of the worker when executing a Dequeue instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param dequeue_status_callback_url: The callback URL for completed call event when executing a Dequeue instruction. + :param call_from: The Caller ID of the outbound call when executing a Call instruction. + :param call_record: Whether to record both legs of a call when executing a Call instruction. + :param call_timeout: The timeout for a call when executing a Call instruction. + :param call_to: The contact URI of the worker when executing a Call instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param call_url: TwiML URI executed on answering the worker's leg as a result of the Call instruction. + :param call_status_callback_url: The URL to call for the completed call event when executing a Call instruction. + :param call_accept: Whether to accept a reservation when executing a Call instruction. + :param redirect_call_sid: The Call SID of the call parked in the queue when executing a Redirect instruction. + :param redirect_accept: Whether the reservation should be accepted when executing a Redirect instruction. + :param redirect_url: TwiML URI to redirect the call to when executing the Redirect instruction. + :param to: The Contact URI of the worker when executing a Conference instruction. Can be the URI of the Twilio Client, the SIP URI for Programmable SIP, or the [E.164](https://www.twilio.com/docs/glossary/what-e164) formatted phone number, depending on the destination. + :param from_: The caller ID of the call to the worker when executing a Conference instruction. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param status_callback_event: The call progress events that we will send to `status_callback`. Can be: `initiated`, `ringing`, `answered`, or `completed`. + :param timeout: The timeout for a call when executing a Conference instruction. + :param record: Whether to record the participant and their conferences, including the time between conferences. Can be `true` or `false` and the default is `false`. + :param muted: Whether the agent is muted in the conference. Defaults to `false`. + :param beep: Whether to play a notification beep when the participant joins or when to play a beep. Can be: `true`, `false`, `onEnter`, or `onExit`. The default value is `true`. + :param start_conference_on_enter: Whether to start the conference when the participant joins, if it has not already started. Can be: `true` or `false` and the default is `true`. If `false` and the conference has not started, the participant is muted and hears background music until another participant starts the conference. + :param end_conference_on_exit: Whether to end the conference when the agent leaves. + :param wait_url: The URL we should call using the `wait_method` for the music to play while participants are waiting for the conference to start. The default value is the URL of our standard hold music. [Learn more about hold music](https://www.twilio.com/labs/twimlets/holdmusic). + :param wait_method: The HTTP method we should use to call `wait_url`. Can be `GET` or `POST` and the default is `POST`. When using a static audio file, this should be `GET` so that we can cache the file. + :param early_media: Whether to allow an agent to hear the state of the outbound call, including ringing or disconnect messages. The default is `true`. + :param max_participants: The maximum number of participants allowed in the conference. Can be a positive integer from `2` to `250`. The default value is `250`. + :param conference_status_callback: The URL we should call using the `conference_status_callback_method` when the conference events in `conference_status_callback_event` occur. Only the value set by the first participant to join the conference is used. Subsequent `conference_status_callback` values are ignored. + :param conference_status_callback_method: The HTTP method we should use to call `conference_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_status_callback_event: The conference status events that we will send to `conference_status_callback`. Can be: `start`, `end`, `join`, `leave`, `mute`, `hold`, `speaker`. + :param conference_record: Whether to record the conference the participant is joining or when to record the conference. Can be: `true`, `false`, `record-from-start`, and `do-not-record`. The default value is `false`. + :param conference_trim: Whether to trim leading and trailing silence from your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :param recording_channels: The recording channels for the final recording. Can be: `mono` or `dual` and the default is `mono`. + :param recording_status_callback: The URL that we should call using the `recording_status_callback_method` when the recording status changes. + :param recording_status_callback_method: The HTTP method we should use when we call `recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param conference_recording_status_callback: The URL we should call using the `conference_recording_status_callback_method` when the conference recording is available. + :param conference_recording_status_callback_method: The HTTP method we should use to call `conference_recording_status_callback`. Can be: `GET` or `POST` and defaults to `POST`. + :param region: The [region](https://support.twilio.com/hc/en-us/articles/223132167-How-global-low-latency-routing-and-region-selection-work-for-conferences-and-Client-calls) where we should mix the recorded audio. Can be:`us1`, `us2`, `ie1`, `de1`, `sg1`, `br1`, `au1`, or `jp1`. + :param sip_auth_username: The SIP username used for authentication. + :param sip_auth_password: The SIP password for authentication. + :param dequeue_status_callback_event: The call progress events sent via webhooks as a result of a Dequeue instruction. + :param post_work_activity_sid: The new worker activity SID after executing a Conference instruction. + :param end_conference_on_customer_exit: Whether to end the conference when the customer leaves. + :param beep_on_customer_entrance: Whether to play a notification beep when the customer joins. + :param jitter_buffer_size: The jitter buffer size for conference. Can be: `small`, `medium`, `large`, `off`. + + :returns: The updated ReservationInstance + """ + + data = values.of( + { + "ReservationStatus": reservation_status, + "WorkerActivitySid": worker_activity_sid, + "Instruction": instruction, + "DequeuePostWorkActivitySid": dequeue_post_work_activity_sid, + "DequeueFrom": dequeue_from, + "DequeueRecord": dequeue_record, + "DequeueTimeout": dequeue_timeout, + "DequeueTo": dequeue_to, + "DequeueStatusCallbackUrl": dequeue_status_callback_url, + "CallFrom": call_from, + "CallRecord": call_record, + "CallTimeout": call_timeout, + "CallTo": call_to, + "CallUrl": call_url, + "CallStatusCallbackUrl": call_status_callback_url, + "CallAccept": serialize.boolean_to_string(call_accept), + "RedirectCallSid": redirect_call_sid, + "RedirectAccept": serialize.boolean_to_string(redirect_accept), + "RedirectUrl": redirect_url, + "To": to, + "From": from_, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "StatusCallbackEvent": serialize.map( + status_callback_event, lambda e: e + ), + "Timeout": timeout, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), + "Beep": beep, + "StartConferenceOnEnter": serialize.boolean_to_string( + start_conference_on_enter + ), + "EndConferenceOnExit": serialize.boolean_to_string( + end_conference_on_exit + ), + "WaitUrl": wait_url, + "WaitMethod": wait_method, + "EarlyMedia": serialize.boolean_to_string(early_media), + "MaxParticipants": max_participants, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "Region": region, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "DequeueStatusCallbackEvent": serialize.map( + dequeue_status_callback_event, lambda e: e + ), + "PostWorkActivitySid": post_work_activity_sid, + "EndConferenceOnCustomerExit": serialize.boolean_to_string( + end_conference_on_customer_exit + ), + "BeepOnCustomerEntrance": serialize.boolean_to_string( + beep_on_customer_entrance + ), + "JitterBufferSize": jitter_buffer_size, + } + ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.ReservationContext {}>".format(context) + + +class ReservationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ReservationInstance: + """ + Build an instance of ReservationInstance + + :param payload: Payload response from the API + """ + return ReservationInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.ReservationPage>" + + +class ReservationList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): + """ + Initialize the ReservationList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the WorkerReservation resources to read. + :param worker_sid: The SID of the reserved Worker resource with the WorkerReservation resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + } + self._uri = ( + "/Workspaces/{workspace_sid}/Workers/{worker_sid}/Reservations".format( + **self._solution + ) + ) + + def stream( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ReservationInstance]: + """ + Streams ReservationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + reservation_status=reservation_status, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ReservationInstance]: + """ + Asynchronously streams ReservationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + reservation_status=reservation_status, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ReservationInstance]: + """ + Lists ReservationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + reservation_status=reservation_status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ReservationInstance]: + """ + Asynchronously lists ReservationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "ReservationInstance.Status" reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + reservation_status=reservation_status, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ReservationPage: + """ + Retrieve a single page of ReservationInstance records from the API. + Request is executed immediately + + :param reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ReservationInstance + """ + data = values.of( + { + "ReservationStatus": reservation_status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ReservationPage(self._version, response, self._solution) + + async def page_async( + self, + reservation_status: Union["ReservationInstance.Status", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ReservationPage: + """ + Asynchronously retrieve a single page of ReservationInstance records from the API. + Request is executed immediately + + :param reservation_status: Returns the list of reservations for a worker with a specified ReservationStatus. Can be: `pending`, `accepted`, `rejected`, `timeout`, `canceled`, or `rescinded`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ReservationInstance + """ + data = values.of( + { + "ReservationStatus": reservation_status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ReservationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ReservationPage: + """ + Retrieve a specific page of ReservationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ReservationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ReservationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ReservationPage: + """ + Asynchronously retrieve a specific page of ReservationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ReservationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ReservationPage(self._version, response, self._solution) + + def get(self, sid: str) -> ReservationContext: + """ + Constructs a ReservationContext + + :param sid: The SID of the WorkerReservation resource to update. + """ + return ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ReservationContext: + """ + Constructs a ReservationContext + + :param sid: The SID of the WorkerReservation resource to update. + """ + return ReservationContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.ReservationList>" diff --git a/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py b/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py new file mode 100644 index 0000000000..6e3cc9c1dd --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py @@ -0,0 +1,594 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class WorkerChannelInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. + :ivar assigned_tasks: The total number of Tasks assigned to Worker for the TaskChannel type. + :ivar available: Whether the Worker should receive Tasks of the TaskChannel type. + :ivar available_capacity_percentage: The current percentage of capacity the TaskChannel has available. Can be a number between `0` and `100`. A value of `0` indicates that TaskChannel has no capacity available and a value of `100` means the Worker is available to receive any Tasks of this TaskChannel type. + :ivar configured_capacity: The current configured capacity for the WorkerChannel. TaskRouter will not create any reservations after the assigned Tasks for the Worker reaches the value. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar sid: The unique string that we created to identify the WorkerChannel resource. + :ivar task_channel_sid: The SID of the TaskChannel. + :ivar task_channel_unique_name: The unique name of the TaskChannel, such as `voice` or `sms`. + :ivar worker_sid: The SID of the Worker that contains the WorkerChannel. + :ivar workspace_sid: The SID of the Workspace that contains the WorkerChannel. + :ivar url: The absolute URL of the WorkerChannel resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + worker_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.assigned_tasks: Optional[int] = deserialize.integer( + payload.get("assigned_tasks") + ) + self.available: Optional[bool] = payload.get("available") + self.available_capacity_percentage: Optional[int] = deserialize.integer( + payload.get("available_capacity_percentage") + ) + self.configured_capacity: Optional[int] = deserialize.integer( + payload.get("configured_capacity") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sid: Optional[str] = payload.get("sid") + self.task_channel_sid: Optional[str] = payload.get("task_channel_sid") + self.task_channel_unique_name: Optional[str] = payload.get( + "task_channel_unique_name" + ) + self.worker_sid: Optional[str] = payload.get("worker_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + "sid": sid or self.sid, + } + self._context: Optional[WorkerChannelContext] = None + + @property + def _proxy(self) -> "WorkerChannelContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkerChannelContext for this WorkerChannelInstance + """ + if self._context is None: + self._context = WorkerChannelContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "WorkerChannelInstance": + """ + Fetch the WorkerChannelInstance + + + :returns: The fetched WorkerChannelInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WorkerChannelInstance": + """ + Asynchronous coroutine to fetch the WorkerChannelInstance + + + :returns: The fetched WorkerChannelInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> "WorkerChannelInstance": + """ + Update the WorkerChannelInstance + + :param capacity: The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. + :param available: Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. + + :returns: The updated WorkerChannelInstance + """ + return self._proxy.update( + capacity=capacity, + available=available, + ) + + async def update_async( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> "WorkerChannelInstance": + """ + Asynchronous coroutine to update the WorkerChannelInstance + + :param capacity: The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. + :param available: Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. + + :returns: The updated WorkerChannelInstance + """ + return await self._proxy.update_async( + capacity=capacity, + available=available, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkerChannelInstance {}>".format(context) + + +class WorkerChannelContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, worker_sid: str, sid: str): + """ + Initialize the WorkerChannelContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the WorkerChannel to update. + :param worker_sid: The SID of the Worker with the WorkerChannel to update. + :param sid: The SID of the WorkerChannel to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + "sid": sid, + } + self._uri = ( + "/Workspaces/{workspace_sid}/Workers/{worker_sid}/Channels/{sid}".format( + **self._solution + ) + ) + + def fetch(self) -> WorkerChannelInstance: + """ + Fetch the WorkerChannelInstance + + + :returns: The fetched WorkerChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WorkerChannelInstance: + """ + Asynchronous coroutine to fetch the WorkerChannelInstance + + + :returns: The fetched WorkerChannelInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> WorkerChannelInstance: + """ + Update the WorkerChannelInstance + + :param capacity: The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. + :param available: Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. + + :returns: The updated WorkerChannelInstance + """ + + data = values.of( + { + "Capacity": capacity, + "Available": serialize.boolean_to_string(available), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + capacity: Union[int, object] = values.unset, + available: Union[bool, object] = values.unset, + ) -> WorkerChannelInstance: + """ + Asynchronous coroutine to update the WorkerChannelInstance + + :param capacity: The total number of Tasks that the Worker should handle for the TaskChannel type. TaskRouter creates reservations for Tasks of this TaskChannel type up to the specified capacity. If the capacity is 0, no new reservations will be created. + :param available: Whether the WorkerChannel is available. Set to `false` to prevent the Worker from receiving any new Tasks of this TaskChannel type. + + :returns: The updated WorkerChannelInstance + """ + + data = values.of( + { + "Capacity": capacity, + "Available": serialize.boolean_to_string(available), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkerChannelContext {}>".format(context) + + +class WorkerChannelPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WorkerChannelInstance: + """ + Build an instance of WorkerChannelInstance + + :param payload: Payload response from the API + """ + return WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.WorkerChannelPage>" + + +class WorkerChannelList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): + """ + Initialize the WorkerChannelList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the WorkerChannels to read. + :param worker_sid: The SID of the Worker with the WorkerChannels to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers/{worker_sid}/Channels".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WorkerChannelInstance]: + """ + Streams WorkerChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WorkerChannelInstance]: + """ + Asynchronously streams WorkerChannelInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkerChannelInstance]: + """ + Lists WorkerChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkerChannelInstance]: + """ + Asynchronously lists WorkerChannelInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkerChannelPage: + """ + Retrieve a single page of WorkerChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkerChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkerChannelPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkerChannelPage: + """ + Asynchronously retrieve a single page of WorkerChannelInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkerChannelInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkerChannelPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> WorkerChannelPage: + """ + Retrieve a specific page of WorkerChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkerChannelInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WorkerChannelPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> WorkerChannelPage: + """ + Asynchronously retrieve a specific page of WorkerChannelInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkerChannelInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WorkerChannelPage(self._version, response, self._solution) + + def get(self, sid: str) -> WorkerChannelContext: + """ + Constructs a WorkerChannelContext + + :param sid: The SID of the WorkerChannel to update. + """ + return WorkerChannelContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> WorkerChannelContext: + """ + Constructs a WorkerChannelContext + + :param sid: The SID of the WorkerChannel to update. + """ + return WorkerChannelContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.WorkerChannelList>" diff --git a/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py b/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py new file mode 100644 index 0000000000..eea670aa7d --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py @@ -0,0 +1,292 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WorkerStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. + :ivar cumulative: An object that contains the cumulative statistics for the Worker. + :ivar worker_sid: The SID of the Worker that contains the WorkerChannel. + :ivar workspace_sid: The SID of the Workspace that contains the WorkerChannel. + :ivar url: The absolute URL of the WorkerChannel statistics resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + worker_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.cumulative: Optional[Dict[str, object]] = payload.get("cumulative") + self.worker_sid: Optional[str] = payload.get("worker_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + } + self._context: Optional[WorkerStatisticsContext] = None + + @property + def _proxy(self) -> "WorkerStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkerStatisticsContext for this WorkerStatisticsInstance + """ + if self._context is None: + self._context = WorkerStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + return self._context + + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> "WorkerStatisticsInstance": + """ + Fetch the WorkerStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkerStatisticsInstance + """ + return self._proxy.fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + ) + + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> "WorkerStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkerStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkerStatisticsInstance + """ + return await self._proxy.fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkerStatisticsInstance {}>".format(context) + + +class WorkerStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): + """ + Initialize the WorkerStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the WorkerChannel to fetch. + :param worker_sid: The SID of the Worker with the WorkerChannel to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + } + self._uri = ( + "/Workspaces/{workspace_sid}/Workers/{worker_sid}/Statistics".format( + **self._solution + ) + ) + + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> WorkerStatisticsInstance: + """ + Fetch the WorkerStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkerStatisticsInstance + """ + + data = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkerStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> WorkerStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkerStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkerStatisticsInstance + """ + + data = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkerStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkerStatisticsContext {}>".format(context) + + +class WorkerStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): + """ + Initialize the WorkerStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the WorkerChannel to fetch. + :param worker_sid: The SID of the Worker with the WorkerChannel to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "worker_sid": worker_sid, + } + + def get(self) -> WorkerStatisticsContext: + """ + Constructs a WorkerStatisticsContext + + """ + return WorkerStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + + def __call__(self) -> WorkerStatisticsContext: + """ + Constructs a WorkerStatisticsContext + + """ + return WorkerStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.WorkerStatisticsList>" diff --git a/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py b/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py new file mode 100644 index 0000000000..48a78710e2 --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py @@ -0,0 +1,308 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WorkersCumulativeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. + :ivar start_time: The beginning of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar end_time: The end of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar activity_durations: The minimum, average, maximum, and total time (in seconds) that Workers spent in each Activity. + :ivar reservations_created: The total number of Reservations that were created. + :ivar reservations_accepted: The total number of Reservations that were accepted. + :ivar reservations_rejected: The total number of Reservations that were rejected. + :ivar reservations_timed_out: The total number of Reservations that were timed out. + :ivar reservations_canceled: The total number of Reservations that were canceled. + :ivar reservations_rescinded: The total number of Reservations that were rescinded. + :ivar workspace_sid: The SID of the Workspace that contains the Workers. + :ivar url: The absolute URL of the Workers statistics resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.activity_durations: Optional[List[Dict[str, object]]] = payload.get( + "activity_durations" + ) + self.reservations_created: Optional[int] = deserialize.integer( + payload.get("reservations_created") + ) + self.reservations_accepted: Optional[int] = deserialize.integer( + payload.get("reservations_accepted") + ) + self.reservations_rejected: Optional[int] = deserialize.integer( + payload.get("reservations_rejected") + ) + self.reservations_timed_out: Optional[int] = deserialize.integer( + payload.get("reservations_timed_out") + ) + self.reservations_canceled: Optional[int] = deserialize.integer( + payload.get("reservations_canceled") + ) + self.reservations_rescinded: Optional[int] = deserialize.integer( + payload.get("reservations_rescinded") + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + } + self._context: Optional[WorkersCumulativeStatisticsContext] = None + + @property + def _proxy(self) -> "WorkersCumulativeStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkersCumulativeStatisticsContext for this WorkersCumulativeStatisticsInstance + """ + if self._context is None: + self._context = WorkersCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + ) + return self._context + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> "WorkersCumulativeStatisticsInstance": + """ + Fetch the WorkersCumulativeStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersCumulativeStatisticsInstance + """ + return self._proxy.fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + ) + + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> "WorkersCumulativeStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkersCumulativeStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersCumulativeStatisticsInstance + """ + return await self._proxy.fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkersCumulativeStatisticsInstance {}>".format( + context + ) + + +class WorkersCumulativeStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkersCumulativeStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers/CumulativeStatistics".format( + **self._solution + ) + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> WorkersCumulativeStatisticsInstance: + """ + Fetch the WorkersCumulativeStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersCumulativeStatisticsInstance + """ + + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkersCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> WorkersCumulativeStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkersCumulativeStatisticsInstance + + :param end_date: Only calculate statistics from this date and time and earlier, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersCumulativeStatisticsInstance + """ + + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkersCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkersCumulativeStatisticsContext {}>".format( + context + ) + + +class WorkersCumulativeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkersCumulativeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the resource to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + + def get(self) -> WorkersCumulativeStatisticsContext: + """ + Constructs a WorkersCumulativeStatisticsContext + + """ + return WorkersCumulativeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __call__(self) -> WorkersCumulativeStatisticsContext: + """ + Constructs a WorkersCumulativeStatisticsContext + + """ + return WorkersCumulativeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.WorkersCumulativeStatisticsList>" diff --git a/twilio/rest/taskrouter/v1/workspace/worker/workers_real_time_statistics.py b/twilio/rest/taskrouter/v1/workspace/worker/workers_real_time_statistics.py new file mode 100644 index 0000000000..2e9970478e --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/worker/workers_real_time_statistics.py @@ -0,0 +1,239 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WorkersRealTimeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. + :ivar activity_statistics: The number of current Workers by Activity. + :ivar total_workers: The total number of Workers. + :ivar workspace_sid: The SID of the Workspace that contains the Workers. + :ivar url: The absolute URL of the Workers statistics resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.activity_statistics: Optional[List[Dict[str, object]]] = payload.get( + "activity_statistics" + ) + self.total_workers: Optional[int] = deserialize.integer( + payload.get("total_workers") + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + } + self._context: Optional[WorkersRealTimeStatisticsContext] = None + + @property + def _proxy(self) -> "WorkersRealTimeStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkersRealTimeStatisticsContext for this WorkersRealTimeStatisticsInstance + """ + if self._context is None: + self._context = WorkersRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + ) + return self._context + + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkersRealTimeStatisticsInstance": + """ + Fetch the WorkersRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersRealTimeStatisticsInstance + """ + return self._proxy.fetch( + task_channel=task_channel, + ) + + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkersRealTimeStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkersRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersRealTimeStatisticsInstance + """ + return await self._proxy.fetch_async( + task_channel=task_channel, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkersRealTimeStatisticsInstance {}>".format( + context + ) + + +class WorkersRealTimeStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkersRealTimeStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers/RealTimeStatistics".format( + **self._solution + ) + + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> WorkersRealTimeStatisticsInstance: + """ + Fetch the WorkersRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersRealTimeStatisticsInstance + """ + + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkersRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> WorkersRealTimeStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkersRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersRealTimeStatisticsInstance + """ + + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkersRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkersRealTimeStatisticsContext {}>".format( + context + ) + + +class WorkersRealTimeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkersRealTimeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the resource to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + + def get(self) -> WorkersRealTimeStatisticsContext: + """ + Constructs a WorkersRealTimeStatisticsContext + + """ + return WorkersRealTimeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __call__(self) -> WorkersRealTimeStatisticsContext: + """ + Constructs a WorkersRealTimeStatisticsContext + + """ + return WorkersRealTimeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.WorkersRealTimeStatisticsList>" diff --git a/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py b/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py new file mode 100644 index 0000000000..31c79ee6ba --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py @@ -0,0 +1,308 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WorkersStatisticsInstance(InstanceResource): + """ + :ivar realtime: An object that contains the real-time statistics for the Worker. + :ivar cumulative: An object that contains the cumulative statistics for the Worker. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. + :ivar workspace_sid: The SID of the Workspace that contains the Worker. + :ivar url: The absolute URL of the Worker statistics resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.realtime: Optional[Dict[str, object]] = payload.get("realtime") + self.cumulative: Optional[Dict[str, object]] = payload.get("cumulative") + self.account_sid: Optional[str] = payload.get("account_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + } + self._context: Optional[WorkersStatisticsContext] = None + + @property + def _proxy(self) -> "WorkersStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkersStatisticsContext for this WorkersStatisticsInstance + """ + if self._context is None: + self._context = WorkersStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + ) + return self._context + + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> "WorkersStatisticsInstance": + """ + Fetch the WorkersStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics. + :param task_queue_name: The `friendly_name` of the TaskQueue for which to fetch Worker statistics. + :param friendly_name: Only include Workers with `friendly_name` values that match this parameter. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersStatisticsInstance + """ + return self._proxy.fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + friendly_name=friendly_name, + task_channel=task_channel, + ) + + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> "WorkersStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkersStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics. + :param task_queue_name: The `friendly_name` of the TaskQueue for which to fetch Worker statistics. + :param friendly_name: Only include Workers with `friendly_name` values that match this parameter. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersStatisticsInstance + """ + return await self._proxy.fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_queue_sid=task_queue_sid, + task_queue_name=task_queue_name, + friendly_name=friendly_name, + task_channel=task_channel, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkersStatisticsInstance {}>".format(context) + + +class WorkersStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkersStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Worker to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workers/Statistics".format( + **self._solution + ) + + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> WorkersStatisticsInstance: + """ + Fetch the WorkersStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics. + :param task_queue_name: The `friendly_name` of the TaskQueue for which to fetch Worker statistics. + :param friendly_name: Only include Workers with `friendly_name` values that match this parameter. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersStatisticsInstance + """ + + data = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskQueueSid": task_queue_sid, + "TaskQueueName": task_queue_name, + "FriendlyName": friendly_name, + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkersStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_queue_sid: Union[str, object] = values.unset, + task_queue_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + task_channel: Union[str, object] = values.unset, + ) -> WorkersStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkersStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_queue_sid: The SID of the TaskQueue for which to fetch Worker statistics. + :param task_queue_name: The `friendly_name` of the TaskQueue for which to fetch Worker statistics. + :param friendly_name: Only include Workers with `friendly_name` values that match this parameter. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkersStatisticsInstance + """ + + data = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskQueueSid": task_queue_sid, + "TaskQueueName": task_queue_name, + "FriendlyName": friendly_name, + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkersStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkersStatisticsContext {}>".format(context) + + +class WorkersStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkersStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Worker to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + + def get(self) -> WorkersStatisticsContext: + """ + Constructs a WorkersStatisticsContext + + """ + return WorkersStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __call__(self) -> WorkersStatisticsContext: + """ + Constructs a WorkersStatisticsContext + + """ + return WorkersStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.WorkersStatisticsList>" diff --git a/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py b/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py new file mode 100644 index 0000000000..619ae1bce9 --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py @@ -0,0 +1,837 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.taskrouter.v1.workspace.workflow.workflow_cumulative_statistics import ( + WorkflowCumulativeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.workflow.workflow_real_time_statistics import ( + WorkflowRealTimeStatisticsList, +) +from twilio.rest.taskrouter.v1.workspace.workflow.workflow_statistics import ( + WorkflowStatisticsList, +) + + +class WorkflowInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workflow resource. + :ivar assignment_callback_url: The URL that we call when a task managed by the Workflow is assigned to a Worker. See Assignment Callback URL for more information. + :ivar configuration: A JSON string that contains the Workflow's configuration. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar document_content_type: The MIME type of the document. + :ivar fallback_assignment_callback_url: The URL that we call when a call to the `assignment_callback_url` fails. + :ivar friendly_name: The string that you assigned to describe the Workflow resource. For example, `Customer Support` or `2014 Election Campaign`. + :ivar sid: The unique string that we created to identify the Workflow resource. + :ivar task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + :ivar workspace_sid: The SID of the Workspace that contains the Workflow. + :ivar url: The absolute URL of the Workflow resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.assignment_callback_url: Optional[str] = payload.get( + "assignment_callback_url" + ) + self.configuration: Optional[str] = payload.get("configuration") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.document_content_type: Optional[str] = payload.get("document_content_type") + self.fallback_assignment_callback_url: Optional[str] = payload.get( + "fallback_assignment_callback_url" + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.sid: Optional[str] = payload.get("sid") + self.task_reservation_timeout: Optional[int] = deserialize.integer( + payload.get("task_reservation_timeout") + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid or self.sid, + } + self._context: Optional[WorkflowContext] = None + + @property + def _proxy(self) -> "WorkflowContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkflowContext for this WorkflowInstance + """ + if self._context is None: + self._context = WorkflowContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the WorkflowInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WorkflowInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "WorkflowInstance": + """ + Fetch the WorkflowInstance + + + :returns: The fetched WorkflowInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WorkflowInstance": + """ + Asynchronous coroutine to fetch the WorkflowInstance + + + :returns: The fetched WorkflowInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + re_evaluate_tasks: Union[str, object] = values.unset, + ) -> "WorkflowInstance": + """ + Update the WorkflowInstance + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + :param re_evaluate_tasks: Whether or not to re-evaluate Tasks. The default is `false`, which means Tasks in the Workflow will not be processed through the assignment loop again. + + :returns: The updated WorkflowInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + configuration=configuration, + task_reservation_timeout=task_reservation_timeout, + re_evaluate_tasks=re_evaluate_tasks, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + re_evaluate_tasks: Union[str, object] = values.unset, + ) -> "WorkflowInstance": + """ + Asynchronous coroutine to update the WorkflowInstance + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + :param re_evaluate_tasks: Whether or not to re-evaluate Tasks. The default is `false`, which means Tasks in the Workflow will not be processed through the assignment loop again. + + :returns: The updated WorkflowInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + assignment_callback_url=assignment_callback_url, + fallback_assignment_callback_url=fallback_assignment_callback_url, + configuration=configuration, + task_reservation_timeout=task_reservation_timeout, + re_evaluate_tasks=re_evaluate_tasks, + ) + + @property + def cumulative_statistics(self) -> WorkflowCumulativeStatisticsList: + """ + Access the cumulative_statistics + """ + return self._proxy.cumulative_statistics + + @property + def real_time_statistics(self) -> WorkflowRealTimeStatisticsList: + """ + Access the real_time_statistics + """ + return self._proxy.real_time_statistics + + @property + def statistics(self) -> WorkflowStatisticsList: + """ + Access the statistics + """ + return self._proxy.statistics + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkflowInstance {}>".format(context) + + +class WorkflowContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, sid: str): + """ + Initialize the WorkflowContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workflow to update. + :param sid: The SID of the Workflow resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "sid": sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workflows/{sid}".format( + **self._solution + ) + + self._cumulative_statistics: Optional[WorkflowCumulativeStatisticsList] = None + self._real_time_statistics: Optional[WorkflowRealTimeStatisticsList] = None + self._statistics: Optional[WorkflowStatisticsList] = None + + def delete(self) -> bool: + """ + Deletes the WorkflowInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WorkflowInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> WorkflowInstance: + """ + Fetch the WorkflowInstance + + + :returns: The fetched WorkflowInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WorkflowInstance: + """ + Asynchronous coroutine to fetch the WorkflowInstance + + + :returns: The fetched WorkflowInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + re_evaluate_tasks: Union[str, object] = values.unset, + ) -> WorkflowInstance: + """ + Update the WorkflowInstance + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + :param re_evaluate_tasks: Whether or not to re-evaluate Tasks. The default is `false`, which means Tasks in the Workflow will not be processed through the assignment loop again. + + :returns: The updated WorkflowInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "AssignmentCallbackUrl": assignment_callback_url, + "FallbackAssignmentCallbackUrl": fallback_assignment_callback_url, + "Configuration": configuration, + "TaskReservationTimeout": task_reservation_timeout, + "ReEvaluateTasks": re_evaluate_tasks, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + re_evaluate_tasks: Union[str, object] = values.unset, + ) -> WorkflowInstance: + """ + Asynchronous coroutine to update the WorkflowInstance + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + :param re_evaluate_tasks: Whether or not to re-evaluate Tasks. The default is `false`, which means Tasks in the Workflow will not be processed through the assignment loop again. + + :returns: The updated WorkflowInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "AssignmentCallbackUrl": assignment_callback_url, + "FallbackAssignmentCallbackUrl": fallback_assignment_callback_url, + "Configuration": configuration, + "TaskReservationTimeout": task_reservation_timeout, + "ReEvaluateTasks": re_evaluate_tasks, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], + ) + + @property + def cumulative_statistics(self) -> WorkflowCumulativeStatisticsList: + """ + Access the cumulative_statistics + """ + if self._cumulative_statistics is None: + self._cumulative_statistics = WorkflowCumulativeStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._cumulative_statistics + + @property + def real_time_statistics(self) -> WorkflowRealTimeStatisticsList: + """ + Access the real_time_statistics + """ + if self._real_time_statistics is None: + self._real_time_statistics = WorkflowRealTimeStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._real_time_statistics + + @property + def statistics(self) -> WorkflowStatisticsList: + """ + Access the statistics + """ + if self._statistics is None: + self._statistics = WorkflowStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._statistics + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkflowContext {}>".format(context) + + +class WorkflowPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WorkflowInstance: + """ + Build an instance of WorkflowInstance + + :param payload: Payload response from the API + """ + return WorkflowInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.WorkflowPage>" + + +class WorkflowList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkflowList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workflow to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workflows".format(**self._solution) + + def create( + self, + friendly_name: str, + configuration: str, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + ) -> WorkflowInstance: + """ + Create the WorkflowInstance + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + + :returns: The created WorkflowInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Configuration": configuration, + "AssignmentCallbackUrl": assignment_callback_url, + "FallbackAssignmentCallbackUrl": fallback_assignment_callback_url, + "TaskReservationTimeout": task_reservation_timeout, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkflowInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + async def create_async( + self, + friendly_name: str, + configuration: str, + assignment_callback_url: Union[str, object] = values.unset, + fallback_assignment_callback_url: Union[str, object] = values.unset, + task_reservation_timeout: Union[int, object] = values.unset, + ) -> WorkflowInstance: + """ + Asynchronously create the WorkflowInstance + + :param friendly_name: A descriptive string that you create to describe the Workflow resource. For example, `Inbound Call Workflow` or `2014 Outbound Campaign`. + :param configuration: A JSON string that contains the rules to apply to the Workflow. See [Configuring Workflows](https://www.twilio.com/docs/taskrouter/workflow-configuration) for more information. + :param assignment_callback_url: The URL from your application that will process task assignment events. See [Handling Task Assignment Callback](https://www.twilio.com/docs/taskrouter/handle-assignment-callbacks) for more details. + :param fallback_assignment_callback_url: The URL that we should call when a call to the `assignment_callback_url` fails. + :param task_reservation_timeout: How long TaskRouter will wait for a confirmation response from your application after it assigns a Task to a Worker. Can be up to `86,400` (24 hours) and the default is `120`. + + :returns: The created WorkflowInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Configuration": configuration, + "AssignmentCallbackUrl": assignment_callback_url, + "FallbackAssignmentCallbackUrl": fallback_assignment_callback_url, + "TaskReservationTimeout": task_reservation_timeout, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WorkflowInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WorkflowInstance]: + """ + Streams WorkflowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the Workflow resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WorkflowInstance]: + """ + Asynchronously streams WorkflowInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: The `friendly_name` of the Workflow resources to read. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkflowInstance]: + """ + Lists WorkflowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the Workflow resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WorkflowInstance]: + """ + Asynchronously lists WorkflowInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: The `friendly_name` of the Workflow resources to read. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkflowPage: + """ + Retrieve a single page of WorkflowInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Workflow resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkflowInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkflowPage(self._version, response, self._solution) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WorkflowPage: + """ + Asynchronously retrieve a single page of WorkflowInstance records from the API. + Request is executed immediately + + :param friendly_name: The `friendly_name` of the Workflow resources to read. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WorkflowInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WorkflowPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> WorkflowPage: + """ + Retrieve a specific page of WorkflowInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkflowInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WorkflowPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> WorkflowPage: + """ + Asynchronously retrieve a specific page of WorkflowInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WorkflowInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WorkflowPage(self._version, response, self._solution) + + def get(self, sid: str) -> WorkflowContext: + """ + Constructs a WorkflowContext + + :param sid: The SID of the Workflow resource to update. + """ + return WorkflowContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __call__(self, sid: str) -> WorkflowContext: + """ + Constructs a WorkflowContext + + :param sid: The SID of the Workflow resource to update. + """ + return WorkflowContext( + self._version, workspace_sid=self._solution["workspace_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.WorkflowList>" diff --git a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py new file mode 100644 index 0000000000..d6d7c094cc --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py @@ -0,0 +1,376 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WorkflowCumulativeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workflow resource. + :ivar avg_task_acceptance_time: The average time in seconds between Task creation and acceptance. + :ivar start_time: The beginning of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar end_time: The end of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar reservations_created: The total number of Reservations that were created for Workers. + :ivar reservations_accepted: The total number of Reservations accepted by Workers. + :ivar reservations_rejected: The total number of Reservations that were rejected. + :ivar reservations_timed_out: The total number of Reservations that were timed out. + :ivar reservations_canceled: The total number of Reservations that were canceled. + :ivar reservations_rescinded: The total number of Reservations that were rescinded. + :ivar split_by_wait_time: A list of objects that describe the number of Tasks canceled and reservations accepted above and below the thresholds specified in seconds. + :ivar wait_duration_until_accepted: The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks that were accepted. + :ivar wait_duration_until_canceled: The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks that were canceled. + :ivar tasks_canceled: The total number of Tasks that were canceled. + :ivar tasks_completed: The total number of Tasks that were completed. + :ivar tasks_entered: The total number of Tasks that entered the Workflow. + :ivar tasks_deleted: The total number of Tasks that were deleted. + :ivar tasks_moved: The total number of Tasks that were moved from one queue to another. + :ivar tasks_timed_out_in_workflow: The total number of Tasks that were timed out of their Workflows (and deleted). + :ivar workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified Sid value. + :ivar workspace_sid: The SID of the Workspace that contains the Workflow. + :ivar url: The absolute URL of the Workflow statistics resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + workflow_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.avg_task_acceptance_time: Optional[int] = deserialize.integer( + payload.get("avg_task_acceptance_time") + ) + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.reservations_created: Optional[int] = deserialize.integer( + payload.get("reservations_created") + ) + self.reservations_accepted: Optional[int] = deserialize.integer( + payload.get("reservations_accepted") + ) + self.reservations_rejected: Optional[int] = deserialize.integer( + payload.get("reservations_rejected") + ) + self.reservations_timed_out: Optional[int] = deserialize.integer( + payload.get("reservations_timed_out") + ) + self.reservations_canceled: Optional[int] = deserialize.integer( + payload.get("reservations_canceled") + ) + self.reservations_rescinded: Optional[int] = deserialize.integer( + payload.get("reservations_rescinded") + ) + self.split_by_wait_time: Optional[Dict[str, object]] = payload.get( + "split_by_wait_time" + ) + self.wait_duration_until_accepted: Optional[Dict[str, object]] = payload.get( + "wait_duration_until_accepted" + ) + self.wait_duration_until_canceled: Optional[Dict[str, object]] = payload.get( + "wait_duration_until_canceled" + ) + self.tasks_canceled: Optional[int] = deserialize.integer( + payload.get("tasks_canceled") + ) + self.tasks_completed: Optional[int] = deserialize.integer( + payload.get("tasks_completed") + ) + self.tasks_entered: Optional[int] = deserialize.integer( + payload.get("tasks_entered") + ) + self.tasks_deleted: Optional[int] = deserialize.integer( + payload.get("tasks_deleted") + ) + self.tasks_moved: Optional[int] = deserialize.integer( + payload.get("tasks_moved") + ) + self.tasks_timed_out_in_workflow: Optional[int] = deserialize.integer( + payload.get("tasks_timed_out_in_workflow") + ) + self.workflow_sid: Optional[str] = payload.get("workflow_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + self._context: Optional[WorkflowCumulativeStatisticsContext] = None + + @property + def _proxy(self) -> "WorkflowCumulativeStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkflowCumulativeStatisticsContext for this WorkflowCumulativeStatisticsInstance + """ + if self._context is None: + self._context = WorkflowCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return self._context + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "WorkflowCumulativeStatisticsInstance": + """ + Fetch the WorkflowCumulativeStatisticsInstance + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: The fetched WorkflowCumulativeStatisticsInstance + """ + return self._proxy.fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "WorkflowCumulativeStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkflowCumulativeStatisticsInstance + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: The fetched WorkflowCumulativeStatisticsInstance + """ + return await self._proxy.fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkflowCumulativeStatisticsInstance {}>".format( + context + ) + + +class WorkflowCumulativeStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): + """ + Initialize the WorkflowCumulativeStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the resource to fetch. + :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified Sid value. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workflows/{workflow_sid}/CumulativeStatistics".format( + **self._solution + ) + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkflowCumulativeStatisticsInstance: + """ + Fetch the WorkflowCumulativeStatisticsInstance + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: The fetched WorkflowCumulativeStatisticsInstance + """ + + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkflowCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkflowCumulativeStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkflowCumulativeStatisticsInstance + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: The fetched WorkflowCumulativeStatisticsInstance + """ + + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkflowCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkflowCumulativeStatisticsContext {}>".format( + context + ) + + +class WorkflowCumulativeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): + """ + Initialize the WorkflowCumulativeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the resource to fetch. + :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified Sid value. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + + def get(self) -> WorkflowCumulativeStatisticsContext: + """ + Constructs a WorkflowCumulativeStatisticsContext + + """ + return WorkflowCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + def __call__(self) -> WorkflowCumulativeStatisticsContext: + """ + Constructs a WorkflowCumulativeStatisticsContext + + """ + return WorkflowCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.WorkflowCumulativeStatisticsList>" diff --git a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_real_time_statistics.py b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_real_time_statistics.py new file mode 100644 index 0000000000..9387622518 --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_real_time_statistics.py @@ -0,0 +1,271 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WorkflowRealTimeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workflow resource. + :ivar longest_task_waiting_age: The age of the longest waiting Task. + :ivar longest_task_waiting_sid: The SID of the longest waiting Task. + :ivar tasks_by_priority: The number of Tasks by priority. For example: `{\"0\": \"10\", \"99\": \"5\"}` shows 10 Tasks at priority 0 and 5 at priority 99. + :ivar tasks_by_status: The number of Tasks by their current status. For example: `{\"pending\": \"1\", \"reserved\": \"3\", \"assigned\": \"2\", \"completed\": \"5\"}`. + :ivar total_tasks: The total number of Tasks. + :ivar workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value. + :ivar workspace_sid: The SID of the Workspace that contains the Workflow. + :ivar url: The absolute URL of the Workflow statistics resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + workflow_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.longest_task_waiting_age: Optional[int] = deserialize.integer( + payload.get("longest_task_waiting_age") + ) + self.longest_task_waiting_sid: Optional[str] = payload.get( + "longest_task_waiting_sid" + ) + self.tasks_by_priority: Optional[Dict[str, object]] = payload.get( + "tasks_by_priority" + ) + self.tasks_by_status: Optional[Dict[str, object]] = payload.get( + "tasks_by_status" + ) + self.total_tasks: Optional[int] = deserialize.integer( + payload.get("total_tasks") + ) + self.workflow_sid: Optional[str] = payload.get("workflow_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + self._context: Optional[WorkflowRealTimeStatisticsContext] = None + + @property + def _proxy(self) -> "WorkflowRealTimeStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkflowRealTimeStatisticsContext for this WorkflowRealTimeStatisticsInstance + """ + if self._context is None: + self._context = WorkflowRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return self._context + + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkflowRealTimeStatisticsInstance": + """ + Fetch the WorkflowRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkflowRealTimeStatisticsInstance + """ + return self._proxy.fetch( + task_channel=task_channel, + ) + + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkflowRealTimeStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkflowRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkflowRealTimeStatisticsInstance + """ + return await self._proxy.fetch_async( + task_channel=task_channel, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkflowRealTimeStatisticsInstance {}>".format( + context + ) + + +class WorkflowRealTimeStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): + """ + Initialize the WorkflowRealTimeStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workflow to fetch. + :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Workflows/{workflow_sid}/RealTimeStatistics".format( + **self._solution + ) + + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> WorkflowRealTimeStatisticsInstance: + """ + Fetch the WorkflowRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkflowRealTimeStatisticsInstance + """ + + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkflowRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> WorkflowRealTimeStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkflowRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkflowRealTimeStatisticsInstance + """ + + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkflowRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkflowRealTimeStatisticsContext {}>".format( + context + ) + + +class WorkflowRealTimeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): + """ + Initialize the WorkflowRealTimeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workflow to fetch. + :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + + def get(self) -> WorkflowRealTimeStatisticsContext: + """ + Constructs a WorkflowRealTimeStatisticsContext + + """ + return WorkflowRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + def __call__(self) -> WorkflowRealTimeStatisticsContext: + """ + Constructs a WorkflowRealTimeStatisticsContext + + """ + return WorkflowRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.WorkflowRealTimeStatisticsList>" diff --git a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py new file mode 100644 index 0000000000..e49bd32d6e --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py @@ -0,0 +1,306 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WorkflowStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workflow resource. + :ivar cumulative: An object that contains the cumulative statistics for the Workflow. + :ivar realtime: An object that contains the real-time statistics for the Workflow. + :ivar workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value. + :ivar workspace_sid: The SID of the Workspace that contains the Workflow. + :ivar url: The absolute URL of the Workflow statistics resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + workspace_sid: str, + workflow_sid: str, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.cumulative: Optional[Dict[str, object]] = payload.get("cumulative") + self.realtime: Optional[Dict[str, object]] = payload.get("realtime") + self.workflow_sid: Optional[str] = payload.get("workflow_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + self._context: Optional[WorkflowStatisticsContext] = None + + @property + def _proxy(self) -> "WorkflowStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkflowStatisticsContext for this WorkflowStatisticsInstance + """ + if self._context is None: + self._context = WorkflowStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + return self._context + + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "WorkflowStatisticsInstance": + """ + Fetch the WorkflowStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: The fetched WorkflowStatisticsInstance + """ + return self._proxy.fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "WorkflowStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkflowStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: The fetched WorkflowStatisticsInstance + """ + return await self._proxy.fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkflowStatisticsInstance {}>".format(context) + + +class WorkflowStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): + """ + Initialize the WorkflowStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workflow to fetch. + :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + self._uri = ( + "/Workspaces/{workspace_sid}/Workflows/{workflow_sid}/Statistics".format( + **self._solution + ) + ) + + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkflowStatisticsInstance: + """ + Fetch the WorkflowStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: The fetched WorkflowStatisticsInstance + """ + + data = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkflowStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkflowStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkflowStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: The fetched WorkflowStatisticsInstance + """ + + data = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkflowStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkflowStatisticsContext {}>".format(context) + + +class WorkflowStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): + """ + Initialize the WorkflowStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace with the Workflow to fetch. + :param workflow_sid: Returns the list of Tasks that are being controlled by the Workflow with the specified SID value. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + "workflow_sid": workflow_sid, + } + + def get(self) -> WorkflowStatisticsContext: + """ + Constructs a WorkflowStatisticsContext + + """ + return WorkflowStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + def __call__(self) -> WorkflowStatisticsContext: + """ + Constructs a WorkflowStatisticsContext + + """ + return WorkflowStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + workflow_sid=self._solution["workflow_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.WorkflowStatisticsList>" diff --git a/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py b/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py new file mode 100644 index 0000000000..3747b395d2 --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py @@ -0,0 +1,356 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WorkspaceCumulativeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workspace resource. + :ivar avg_task_acceptance_time: The average time in seconds between Task creation and acceptance. + :ivar start_time: The beginning of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar end_time: The end of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar reservations_created: The total number of Reservations that were created for Workers. + :ivar reservations_accepted: The total number of Reservations accepted by Workers. + :ivar reservations_rejected: The total number of Reservations that were rejected. + :ivar reservations_timed_out: The total number of Reservations that were timed out. + :ivar reservations_canceled: The total number of Reservations that were canceled. + :ivar reservations_rescinded: The total number of Reservations that were rescinded. + :ivar split_by_wait_time: A list of objects that describe the number of Tasks canceled and reservations accepted above and below the thresholds specified in seconds. + :ivar wait_duration_until_accepted: The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks that were accepted. + :ivar wait_duration_until_canceled: The wait duration statistics (`avg`, `min`, `max`, `total`) for Tasks that were canceled. + :ivar tasks_canceled: The total number of Tasks that were canceled. + :ivar tasks_completed: The total number of Tasks that were completed. + :ivar tasks_created: The total number of Tasks created. + :ivar tasks_deleted: The total number of Tasks that were deleted. + :ivar tasks_moved: The total number of Tasks that were moved from one queue to another. + :ivar tasks_timed_out_in_workflow: The total number of Tasks that were timed out of their Workflows (and deleted). + :ivar workspace_sid: The SID of the Workspace. + :ivar url: The absolute URL of the Workspace statistics resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.avg_task_acceptance_time: Optional[int] = deserialize.integer( + payload.get("avg_task_acceptance_time") + ) + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.reservations_created: Optional[int] = deserialize.integer( + payload.get("reservations_created") + ) + self.reservations_accepted: Optional[int] = deserialize.integer( + payload.get("reservations_accepted") + ) + self.reservations_rejected: Optional[int] = deserialize.integer( + payload.get("reservations_rejected") + ) + self.reservations_timed_out: Optional[int] = deserialize.integer( + payload.get("reservations_timed_out") + ) + self.reservations_canceled: Optional[int] = deserialize.integer( + payload.get("reservations_canceled") + ) + self.reservations_rescinded: Optional[int] = deserialize.integer( + payload.get("reservations_rescinded") + ) + self.split_by_wait_time: Optional[Dict[str, object]] = payload.get( + "split_by_wait_time" + ) + self.wait_duration_until_accepted: Optional[Dict[str, object]] = payload.get( + "wait_duration_until_accepted" + ) + self.wait_duration_until_canceled: Optional[Dict[str, object]] = payload.get( + "wait_duration_until_canceled" + ) + self.tasks_canceled: Optional[int] = deserialize.integer( + payload.get("tasks_canceled") + ) + self.tasks_completed: Optional[int] = deserialize.integer( + payload.get("tasks_completed") + ) + self.tasks_created: Optional[int] = deserialize.integer( + payload.get("tasks_created") + ) + self.tasks_deleted: Optional[int] = deserialize.integer( + payload.get("tasks_deleted") + ) + self.tasks_moved: Optional[int] = deserialize.integer( + payload.get("tasks_moved") + ) + self.tasks_timed_out_in_workflow: Optional[int] = deserialize.integer( + payload.get("tasks_timed_out_in_workflow") + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + } + self._context: Optional[WorkspaceCumulativeStatisticsContext] = None + + @property + def _proxy(self) -> "WorkspaceCumulativeStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkspaceCumulativeStatisticsContext for this WorkspaceCumulativeStatisticsInstance + """ + if self._context is None: + self._context = WorkspaceCumulativeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + ) + return self._context + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "WorkspaceCumulativeStatisticsInstance": + """ + Fetch the WorkspaceCumulativeStatisticsInstance + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: The fetched WorkspaceCumulativeStatisticsInstance + """ + return self._proxy.fetch( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "WorkspaceCumulativeStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkspaceCumulativeStatisticsInstance + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: The fetched WorkspaceCumulativeStatisticsInstance + """ + return await self._proxy.fetch_async( + end_date=end_date, + minutes=minutes, + start_date=start_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkspaceCumulativeStatisticsInstance {}>".format( + context + ) + + +class WorkspaceCumulativeStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkspaceCumulativeStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/CumulativeStatistics".format( + **self._solution + ) + + def fetch( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkspaceCumulativeStatisticsInstance: + """ + Fetch the WorkspaceCumulativeStatisticsInstance + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: The fetched WorkspaceCumulativeStatisticsInstance + """ + + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkspaceCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + async def fetch_async( + self, + end_date: Union[datetime, object] = values.unset, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkspaceCumulativeStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkspaceCumulativeStatisticsInstance + + :param end_date: Only include usage that occurred on or before this date, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param task_channel: Only calculate cumulative statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. TaskRouter will calculate statistics on up to 10,000 Tasks for any given threshold. + + :returns: The fetched WorkspaceCumulativeStatisticsInstance + """ + + data = values.of( + { + "EndDate": serialize.iso8601_datetime(end_date), + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkspaceCumulativeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkspaceCumulativeStatisticsContext {}>".format( + context + ) + + +class WorkspaceCumulativeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkspaceCumulativeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + + def get(self) -> WorkspaceCumulativeStatisticsContext: + """ + Constructs a WorkspaceCumulativeStatisticsContext + + """ + return WorkspaceCumulativeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __call__(self) -> WorkspaceCumulativeStatisticsContext: + """ + Constructs a WorkspaceCumulativeStatisticsContext + + """ + return WorkspaceCumulativeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.WorkspaceCumulativeStatisticsList>" diff --git a/twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py b/twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py new file mode 100644 index 0000000000..923a94bf3a --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py @@ -0,0 +1,259 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WorkspaceRealTimeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workspace resource. + :ivar activity_statistics: The number of current Workers by Activity. + :ivar longest_task_waiting_age: The age of the longest waiting Task. + :ivar longest_task_waiting_sid: The SID of the longest waiting Task. + :ivar tasks_by_priority: The number of Tasks by priority. For example: `{\"0\": \"10\", \"99\": \"5\"}` shows 10 Tasks at priority 0 and 5 at priority 99. + :ivar tasks_by_status: The number of Tasks by their current status. For example: `{\"pending\": \"1\", \"reserved\": \"3\", \"assigned\": \"2\", \"completed\": \"5\"}`. + :ivar total_tasks: The total number of Tasks. + :ivar total_workers: The total number of Workers in the Workspace. + :ivar workspace_sid: The SID of the Workspace. + :ivar url: The absolute URL of the Workspace statistics resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.activity_statistics: Optional[List[Dict[str, object]]] = payload.get( + "activity_statistics" + ) + self.longest_task_waiting_age: Optional[int] = deserialize.integer( + payload.get("longest_task_waiting_age") + ) + self.longest_task_waiting_sid: Optional[str] = payload.get( + "longest_task_waiting_sid" + ) + self.tasks_by_priority: Optional[Dict[str, object]] = payload.get( + "tasks_by_priority" + ) + self.tasks_by_status: Optional[Dict[str, object]] = payload.get( + "tasks_by_status" + ) + self.total_tasks: Optional[int] = deserialize.integer( + payload.get("total_tasks") + ) + self.total_workers: Optional[int] = deserialize.integer( + payload.get("total_workers") + ) + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + } + self._context: Optional[WorkspaceRealTimeStatisticsContext] = None + + @property + def _proxy(self) -> "WorkspaceRealTimeStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkspaceRealTimeStatisticsContext for this WorkspaceRealTimeStatisticsInstance + """ + if self._context is None: + self._context = WorkspaceRealTimeStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + ) + return self._context + + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkspaceRealTimeStatisticsInstance": + """ + Fetch the WorkspaceRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkspaceRealTimeStatisticsInstance + """ + return self._proxy.fetch( + task_channel=task_channel, + ) + + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> "WorkspaceRealTimeStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkspaceRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkspaceRealTimeStatisticsInstance + """ + return await self._proxy.fetch_async( + task_channel=task_channel, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkspaceRealTimeStatisticsInstance {}>".format( + context + ) + + +class WorkspaceRealTimeStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkspaceRealTimeStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/RealTimeStatistics".format( + **self._solution + ) + + def fetch( + self, task_channel: Union[str, object] = values.unset + ) -> WorkspaceRealTimeStatisticsInstance: + """ + Fetch the WorkspaceRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkspaceRealTimeStatisticsInstance + """ + + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkspaceRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + async def fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> WorkspaceRealTimeStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkspaceRealTimeStatisticsInstance + + :param task_channel: Only calculate real-time statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + + :returns: The fetched WorkspaceRealTimeStatisticsInstance + """ + + data = values.of( + { + "TaskChannel": task_channel, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkspaceRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkspaceRealTimeStatisticsContext {}>".format( + context + ) + + +class WorkspaceRealTimeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkspaceRealTimeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + + def get(self) -> WorkspaceRealTimeStatisticsContext: + """ + Constructs a WorkspaceRealTimeStatisticsContext + + """ + return WorkspaceRealTimeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __call__(self) -> WorkspaceRealTimeStatisticsContext: + """ + Constructs a WorkspaceRealTimeStatisticsContext + + """ + return WorkspaceRealTimeStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.WorkspaceRealTimeStatisticsList>" diff --git a/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py b/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py new file mode 100644 index 0000000000..b8414a5c6c --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py @@ -0,0 +1,282 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class WorkspaceStatisticsInstance(InstanceResource): + """ + :ivar realtime: An object that contains the real-time statistics for the Workspace. + :ivar cumulative: An object that contains the cumulative statistics for the Workspace. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workspace resource. + :ivar workspace_sid: The SID of the Workspace. + :ivar url: The absolute URL of the Workspace statistics resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.realtime: Optional[Dict[str, object]] = payload.get("realtime") + self.cumulative: Optional[Dict[str, object]] = payload.get("cumulative") + self.account_sid: Optional[str] = payload.get("account_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_sid, + } + self._context: Optional[WorkspaceStatisticsContext] = None + + @property + def _proxy(self) -> "WorkspaceStatisticsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WorkspaceStatisticsContext for this WorkspaceStatisticsInstance + """ + if self._context is None: + self._context = WorkspaceStatisticsContext( + self._version, + workspace_sid=self._solution["workspace_sid"], + ) + return self._context + + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "WorkspaceStatisticsInstance": + """ + Fetch the WorkspaceStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: The fetched WorkspaceStatisticsInstance + """ + return self._proxy.fetch( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> "WorkspaceStatisticsInstance": + """ + Asynchronous coroutine to fetch the WorkspaceStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: The fetched WorkspaceStatisticsInstance + """ + return await self._proxy.fetch_async( + minutes=minutes, + start_date=start_date, + end_date=end_date, + task_channel=task_channel, + split_by_wait_time=split_by_wait_time, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkspaceStatisticsInstance {}>".format(context) + + +class WorkspaceStatisticsContext(InstanceContext): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkspaceStatisticsContext + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/Statistics".format(**self._solution) + + def fetch( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkspaceStatisticsInstance: + """ + Fetch the WorkspaceStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: The fetched WorkspaceStatisticsInstance + """ + + data = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkspaceStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + async def fetch_async( + self, + minutes: Union[int, object] = values.unset, + start_date: Union[datetime, object] = values.unset, + end_date: Union[datetime, object] = values.unset, + task_channel: Union[str, object] = values.unset, + split_by_wait_time: Union[str, object] = values.unset, + ) -> WorkspaceStatisticsInstance: + """ + Asynchronous coroutine to fetch the WorkspaceStatisticsInstance + + :param minutes: Only calculate statistics since this many minutes in the past. The default 15 minutes. This is helpful for displaying statistics for the last 15 minutes, 240 minutes (4 hours), and 480 minutes (8 hours) to see trends. + :param start_date: Only calculate statistics from this date and time and later, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :param end_date: Only calculate statistics from this date and time and earlier, specified in GMT as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time. + :param task_channel: Only calculate statistics on this TaskChannel. Can be the TaskChannel's SID or its `unique_name`, such as `voice`, `sms`, or `default`. + :param split_by_wait_time: A comma separated list of values that describes the thresholds, in seconds, to calculate statistics on. For each threshold specified, the number of Tasks canceled and reservations accepted above and below the specified thresholds in seconds are computed. For example, `5,30` would show splits of Tasks that were canceled or accepted before and after 5 seconds and before and after 30 seconds. This can be used to show short abandoned Tasks or Tasks that failed to meet an SLA. + + :returns: The fetched WorkspaceStatisticsInstance + """ + + data = values.of( + { + "Minutes": minutes, + "StartDate": serialize.iso8601_datetime(start_date), + "EndDate": serialize.iso8601_datetime(end_date), + "TaskChannel": task_channel, + "SplitByWaitTime": split_by_wait_time, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return WorkspaceStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Taskrouter.V1.WorkspaceStatisticsContext {}>".format(context) + + +class WorkspaceStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the WorkspaceStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The SID of the Workspace to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + + def get(self) -> WorkspaceStatisticsContext: + """ + Constructs a WorkspaceStatisticsContext + + """ + return WorkspaceStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __call__(self) -> WorkspaceStatisticsContext: + """ + Constructs a WorkspaceStatisticsContext + + """ + return WorkspaceStatisticsContext( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Taskrouter.V1.WorkspaceStatisticsList>" diff --git a/twilio/rest/trunking/TrunkingBase.py b/twilio/rest/trunking/TrunkingBase.py new file mode 100644 index 0000000000..bed8f9a2a9 --- /dev/null +++ b/twilio/rest/trunking/TrunkingBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.trunking.v1 import V1 + + +class TrunkingBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Trunking Domain + + :returns: Domain for Trunking + """ + super().__init__(twilio, "https://trunking.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Trunking + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Trunking>" diff --git a/twilio/rest/trunking/__init__.py b/twilio/rest/trunking/__init__.py new file mode 100644 index 0000000000..14bd6be655 --- /dev/null +++ b/twilio/rest/trunking/__init__.py @@ -0,0 +1,15 @@ +from warnings import warn + +from twilio.rest.trunking.TrunkingBase import TrunkingBase +from twilio.rest.trunking.v1.trunk import TrunkList + + +class Trunking(TrunkingBase): + @property + def trunks(self) -> TrunkList: + warn( + "trunks is deprecated. Use v1.trunks instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.trunks diff --git a/twilio/rest/trunking/v1/__init__.py b/twilio/rest/trunking/v1/__init__.py new file mode 100644 index 0000000000..af530b97c7 --- /dev/null +++ b/twilio/rest/trunking/v1/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trunking + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.trunking.v1.trunk import TrunkList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Trunking + + :param domain: The Twilio.trunking domain + """ + super().__init__(domain, "v1") + self._trunks: Optional[TrunkList] = None + + @property + def trunks(self) -> TrunkList: + if self._trunks is None: + self._trunks = TrunkList(self) + return self._trunks + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Trunking.V1>" diff --git a/twilio/rest/trunking/v1/trunk/__init__.py b/twilio/rest/trunking/v1/trunk/__init__.py new file mode 100644 index 0000000000..6a93a83233 --- /dev/null +++ b/twilio/rest/trunking/v1/trunk/__init__.py @@ -0,0 +1,887 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trunking + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.trunking.v1.trunk.credential_list import CredentialListList +from twilio.rest.trunking.v1.trunk.ip_access_control_list import IpAccessControlListList +from twilio.rest.trunking.v1.trunk.origination_url import OriginationUrlList +from twilio.rest.trunking.v1.trunk.phone_number import PhoneNumberList +from twilio.rest.trunking.v1.trunk.recording import RecordingList + + +class TrunkInstance(InstanceResource): + + class TransferCallerId(object): + FROM_TRANSFEREE = "from-transferee" + FROM_TRANSFEROR = "from-transferor" + + class TransferSetting(object): + DISABLE_ALL = "disable-all" + ENABLE_ALL = "enable-all" + SIP_ONLY = "sip-only" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Trunk resource. + :ivar domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :ivar disaster_recovery_method: The HTTP method we use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :ivar disaster_recovery_url: The URL we call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from this URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :ivar recording: The recording settings for the trunk. Can be: `do-not-record`, `record-from-ringing`, `record-from-answer`. If set to `record-from-ringing` or `record-from-answer`, all calls going through the trunk will be recorded. The only way to change recording parameters is on a sub-resource of a Trunk after it has been created. e.g.`/Trunks/[Trunk_SID]/Recording -XPOST -d'Mode=record-from-answer'`. See [Recording](https://www.twilio.com/docs/sip-trunking#recording) for more information. + :ivar transfer_mode: + :ivar transfer_caller_id: + :ivar cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :ivar auth_type: The types of authentication mapped to the domain. Can be: `IP_ACL` and `CREDENTIAL_LIST`. If both are mapped, the values are returned in a comma delimited list. If empty, the domain will not receive any traffic. + :ivar auth_type_set: Reserved. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar sid: The unique string that we created to identify the Trunk resource. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.domain_name: Optional[str] = payload.get("domain_name") + self.disaster_recovery_method: Optional[str] = payload.get( + "disaster_recovery_method" + ) + self.disaster_recovery_url: Optional[str] = payload.get("disaster_recovery_url") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.secure: Optional[bool] = payload.get("secure") + self.recording: Optional[Dict[str, object]] = payload.get("recording") + self.transfer_mode: Optional["TrunkInstance.TransferSetting"] = payload.get( + "transfer_mode" + ) + self.transfer_caller_id: Optional["TrunkInstance.TransferCallerId"] = ( + payload.get("transfer_caller_id") + ) + self.cnam_lookup_enabled: Optional[bool] = payload.get("cnam_lookup_enabled") + self.auth_type: Optional[str] = payload.get("auth_type") + self.auth_type_set: Optional[List[str]] = payload.get("auth_type_set") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sid: Optional[str] = payload.get("sid") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[TrunkContext] = None + + @property + def _proxy(self) -> "TrunkContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TrunkContext for this TrunkInstance + """ + if self._context is None: + self._context = TrunkContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TrunkInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TrunkInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TrunkInstance": + """ + Fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TrunkInstance": + """ + Asynchronous coroutine to fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> "TrunkInstance": + """ + Update the TrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: The updated TrunkInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> "TrunkInstance": + """ + Asynchronous coroutine to update the TrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: The updated TrunkInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + domain_name=domain_name, + disaster_recovery_url=disaster_recovery_url, + disaster_recovery_method=disaster_recovery_method, + transfer_mode=transfer_mode, + secure=secure, + cnam_lookup_enabled=cnam_lookup_enabled, + transfer_caller_id=transfer_caller_id, + ) + + @property + def credentials_lists(self) -> CredentialListList: + """ + Access the credentials_lists + """ + return self._proxy.credentials_lists + + @property + def ip_access_control_lists(self) -> IpAccessControlListList: + """ + Access the ip_access_control_lists + """ + return self._proxy.ip_access_control_lists + + @property + def origination_urls(self) -> OriginationUrlList: + """ + Access the origination_urls + """ + return self._proxy.origination_urls + + @property + def phone_numbers(self) -> PhoneNumberList: + """ + Access the phone_numbers + """ + return self._proxy.phone_numbers + + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + return self._proxy.recordings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trunking.V1.TrunkInstance {}>".format(context) + + +class TrunkContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the TrunkContext + + :param version: Version that contains the resource + :param sid: The unique string that we created to identify the OriginationUrl resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Trunks/{sid}".format(**self._solution) + + self._credentials_lists: Optional[CredentialListList] = None + self._ip_access_control_lists: Optional[IpAccessControlListList] = None + self._origination_urls: Optional[OriginationUrlList] = None + self._phone_numbers: Optional[PhoneNumberList] = None + self._recordings: Optional[RecordingList] = None + + def delete(self) -> bool: + """ + Deletes the TrunkInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TrunkInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TrunkInstance: + """ + Fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TrunkInstance: + """ + Asynchronous coroutine to fetch the TrunkInstance + + + :returns: The fetched TrunkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> TrunkInstance: + """ + Update the TrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: The updated TrunkInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DomainName": domain_name, + "DisasterRecoveryUrl": disaster_recovery_url, + "DisasterRecoveryMethod": disaster_recovery_method, + "TransferMode": transfer_mode, + "Secure": serialize.boolean_to_string(secure), + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "TransferCallerId": transfer_caller_id, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrunkInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> TrunkInstance: + """ + Asynchronous coroutine to update the TrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: The updated TrunkInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DomainName": domain_name, + "DisasterRecoveryUrl": disaster_recovery_url, + "DisasterRecoveryMethod": disaster_recovery_method, + "TransferMode": transfer_mode, + "Secure": serialize.boolean_to_string(secure), + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "TransferCallerId": transfer_caller_id, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrunkInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def credentials_lists(self) -> CredentialListList: + """ + Access the credentials_lists + """ + if self._credentials_lists is None: + self._credentials_lists = CredentialListList( + self._version, + self._solution["sid"], + ) + return self._credentials_lists + + @property + def ip_access_control_lists(self) -> IpAccessControlListList: + """ + Access the ip_access_control_lists + """ + if self._ip_access_control_lists is None: + self._ip_access_control_lists = IpAccessControlListList( + self._version, + self._solution["sid"], + ) + return self._ip_access_control_lists + + @property + def origination_urls(self) -> OriginationUrlList: + """ + Access the origination_urls + """ + if self._origination_urls is None: + self._origination_urls = OriginationUrlList( + self._version, + self._solution["sid"], + ) + return self._origination_urls + + @property + def phone_numbers(self) -> PhoneNumberList: + """ + Access the phone_numbers + """ + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList( + self._version, + self._solution["sid"], + ) + return self._phone_numbers + + @property + def recordings(self) -> RecordingList: + """ + Access the recordings + """ + if self._recordings is None: + self._recordings = RecordingList( + self._version, + self._solution["sid"], + ) + return self._recordings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trunking.V1.TrunkContext {}>".format(context) + + +class TrunkPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TrunkInstance: + """ + Build an instance of TrunkInstance + + :param payload: Payload response from the API + """ + return TrunkInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trunking.V1.TrunkPage>" + + +class TrunkList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TrunkList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Trunks" + + def create( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> TrunkInstance: + """ + Create the TrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: The created TrunkInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DomainName": domain_name, + "DisasterRecoveryUrl": disaster_recovery_url, + "DisasterRecoveryMethod": disaster_recovery_method, + "TransferMode": transfer_mode, + "Secure": serialize.boolean_to_string(secure), + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "TransferCallerId": transfer_caller_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrunkInstance(self._version, payload) + + async def create_async( + self, + friendly_name: Union[str, object] = values.unset, + domain_name: Union[str, object] = values.unset, + disaster_recovery_url: Union[str, object] = values.unset, + disaster_recovery_method: Union[str, object] = values.unset, + transfer_mode: Union["TrunkInstance.TransferSetting", object] = values.unset, + secure: Union[bool, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + transfer_caller_id: Union[ + "TrunkInstance.TransferCallerId", object + ] = values.unset, + ) -> TrunkInstance: + """ + Asynchronously create the TrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param domain_name: The unique address you reserve on Twilio to which you route your SIP traffic. Domain names can contain letters, digits, and `-` and must end with `pstn.twilio.com`. See [Termination Settings](https://www.twilio.com/docs/sip-trunking#termination) for more information. + :param disaster_recovery_url: The URL we should call using the `disaster_recovery_method` if an error occurs while sending SIP traffic towards the configured Origination URL. We retrieve TwiML from the URL and execute the instructions like any other normal TwiML call. See [Disaster Recovery](https://www.twilio.com/docs/sip-trunking#disaster-recovery) for more information. + :param disaster_recovery_method: The HTTP method we should use to call the `disaster_recovery_url`. Can be: `GET` or `POST`. + :param transfer_mode: + :param secure: Whether Secure Trunking is enabled for the trunk. If enabled, all calls going through the trunk will be secure using SRTP for media and TLS for signaling. If disabled, then RTP will be used for media. See [Secure Trunking](https://www.twilio.com/docs/sip-trunking#securetrunking) for more information. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup should be enabled for the trunk. If enabled, all inbound calls to the SIP Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param transfer_caller_id: + + :returns: The created TrunkInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DomainName": domain_name, + "DisasterRecoveryUrl": disaster_recovery_url, + "DisasterRecoveryMethod": disaster_recovery_method, + "TransferMode": transfer_mode, + "Secure": serialize.boolean_to_string(secure), + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "TransferCallerId": transfer_caller_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrunkInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TrunkInstance]: + """ + Streams TrunkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TrunkInstance]: + """ + Asynchronously streams TrunkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrunkInstance]: + """ + Lists TrunkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrunkInstance]: + """ + Asynchronously lists TrunkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrunkPage: + """ + Retrieve a single page of TrunkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrunkInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrunkPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrunkPage: + """ + Asynchronously retrieve a single page of TrunkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrunkInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrunkPage(self._version, response) + + def get_page(self, target_url: str) -> TrunkPage: + """ + Retrieve a specific page of TrunkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrunkInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TrunkPage(self._version, response) + + async def get_page_async(self, target_url: str) -> TrunkPage: + """ + Asynchronously retrieve a specific page of TrunkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrunkInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TrunkPage(self._version, response) + + def get(self, sid: str) -> TrunkContext: + """ + Constructs a TrunkContext + + :param sid: The unique string that we created to identify the OriginationUrl resource to update. + """ + return TrunkContext(self._version, sid=sid) + + def __call__(self, sid: str) -> TrunkContext: + """ + Constructs a TrunkContext + + :param sid: The unique string that we created to identify the OriginationUrl resource to update. + """ + return TrunkContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trunking.V1.TrunkList>" diff --git a/twilio/rest/trunking/v1/trunk/credential_list.py b/twilio/rest/trunking/v1/trunk/credential_list.py new file mode 100644 index 0000000000..09ffc99260 --- /dev/null +++ b/twilio/rest/trunking/v1/trunk/credential_list.py @@ -0,0 +1,538 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trunking + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CredentialListInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialList resource. + :ivar sid: The unique string that we created to identify the CredentialList resource. + :ivar trunk_sid: The SID of the Trunk the credential list in associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + trunk_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid or self.sid, + } + self._context: Optional[CredentialListContext] = None + + @property + def _proxy(self) -> "CredentialListContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CredentialListContext for this CredentialListInstance + """ + if self._context is None: + self._context = CredentialListContext( + self._version, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CredentialListInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialListInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CredentialListInstance": + """ + Fetch the CredentialListInstance + + + :returns: The fetched CredentialListInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CredentialListInstance": + """ + Asynchronous coroutine to fetch the CredentialListInstance + + + :returns: The fetched CredentialListInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trunking.V1.CredentialListInstance {}>".format(context) + + +class CredentialListContext(InstanceContext): + + def __init__(self, version: Version, trunk_sid: str, sid: str): + """ + Initialize the CredentialListContext + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to fetch the credential list. + :param sid: The unique string that we created to identify the CredentialList resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid, + } + self._uri = "/Trunks/{trunk_sid}/CredentialLists/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CredentialListInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CredentialListInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CredentialListInstance: + """ + Fetch the CredentialListInstance + + + :returns: The fetched CredentialListInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CredentialListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CredentialListInstance: + """ + Asynchronous coroutine to fetch the CredentialListInstance + + + :returns: The fetched CredentialListInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CredentialListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trunking.V1.CredentialListContext {}>".format(context) + + +class CredentialListPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CredentialListInstance: + """ + Build an instance of CredentialListInstance + + :param payload: Payload response from the API + """ + return CredentialListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trunking.V1.CredentialListPage>" + + +class CredentialListList(ListResource): + + def __init__(self, version: Version, trunk_sid: str): + """ + Initialize the CredentialListList + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to read the credential lists. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + } + self._uri = "/Trunks/{trunk_sid}/CredentialLists".format(**self._solution) + + def create(self, credential_list_sid: str) -> CredentialListInstance: + """ + Create the CredentialListInstance + + :param credential_list_sid: The SID of the [Credential List](https://www.twilio.com/docs/voice/sip/api/sip-credentiallist-resource) that you want to associate with the trunk. Once associated, we will authenticate access to the trunk against this list. + + :returns: The created CredentialListInstance + """ + + data = values.of( + { + "CredentialListSid": credential_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + async def create_async(self, credential_list_sid: str) -> CredentialListInstance: + """ + Asynchronously create the CredentialListInstance + + :param credential_list_sid: The SID of the [Credential List](https://www.twilio.com/docs/voice/sip/api/sip-credentiallist-resource) that you want to associate with the trunk. Once associated, we will authenticate access to the trunk against this list. + + :returns: The created CredentialListInstance + """ + + data = values.of( + { + "CredentialListSid": credential_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CredentialListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CredentialListInstance]: + """ + Streams CredentialListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CredentialListInstance]: + """ + Asynchronously streams CredentialListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListInstance]: + """ + Lists CredentialListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CredentialListInstance]: + """ + Asynchronously lists CredentialListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialListPage: + """ + Retrieve a single page of CredentialListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialListInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialListPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CredentialListPage: + """ + Asynchronously retrieve a single page of CredentialListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CredentialListInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialListPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> CredentialListPage: + """ + Retrieve a specific page of CredentialListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialListInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CredentialListPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> CredentialListPage: + """ + Asynchronously retrieve a specific page of CredentialListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CredentialListInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CredentialListPage(self._version, response, self._solution) + + def get(self, sid: str) -> CredentialListContext: + """ + Constructs a CredentialListContext + + :param sid: The unique string that we created to identify the CredentialList resource to fetch. + """ + return CredentialListContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) + + def __call__(self, sid: str) -> CredentialListContext: + """ + Constructs a CredentialListContext + + :param sid: The unique string that we created to identify the CredentialList resource to fetch. + """ + return CredentialListContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trunking.V1.CredentialListList>" diff --git a/twilio/rest/trunking/v1/trunk/ip_access_control_list.py b/twilio/rest/trunking/v1/trunk/ip_access_control_list.py new file mode 100644 index 0000000000..ec5a59de69 --- /dev/null +++ b/twilio/rest/trunking/v1/trunk/ip_access_control_list.py @@ -0,0 +1,542 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trunking + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class IpAccessControlListInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IpAccessControlList resource. + :ivar sid: The unique string that we created to identify the IpAccessControlList resource. + :ivar trunk_sid: The SID of the Trunk the resource is associated with. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + trunk_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid or self.sid, + } + self._context: Optional[IpAccessControlListContext] = None + + @property + def _proxy(self) -> "IpAccessControlListContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: IpAccessControlListContext for this IpAccessControlListInstance + """ + if self._context is None: + self._context = IpAccessControlListContext( + self._version, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the IpAccessControlListInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "IpAccessControlListInstance": + """ + Fetch the IpAccessControlListInstance + + + :returns: The fetched IpAccessControlListInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "IpAccessControlListInstance": + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance + + + :returns: The fetched IpAccessControlListInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trunking.V1.IpAccessControlListInstance {}>".format(context) + + +class IpAccessControlListContext(InstanceContext): + + def __init__(self, version: Version, trunk_sid: str, sid: str): + """ + Initialize the IpAccessControlListContext + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to fetch the IP Access Control List. + :param sid: The unique string that we created to identify the IpAccessControlList resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid, + } + self._uri = "/Trunks/{trunk_sid}/IpAccessControlLists/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the IpAccessControlListInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpAccessControlListInstance: + """ + Fetch the IpAccessControlListInstance + + + :returns: The fetched IpAccessControlListInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return IpAccessControlListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> IpAccessControlListInstance: + """ + Asynchronous coroutine to fetch the IpAccessControlListInstance + + + :returns: The fetched IpAccessControlListInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return IpAccessControlListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trunking.V1.IpAccessControlListContext {}>".format(context) + + +class IpAccessControlListPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> IpAccessControlListInstance: + """ + Build an instance of IpAccessControlListInstance + + :param payload: Payload response from the API + """ + return IpAccessControlListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trunking.V1.IpAccessControlListPage>" + + +class IpAccessControlListList(ListResource): + + def __init__(self, version: Version, trunk_sid: str): + """ + Initialize the IpAccessControlListList + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to read the IP Access Control Lists. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + } + self._uri = "/Trunks/{trunk_sid}/IpAccessControlLists".format(**self._solution) + + def create(self, ip_access_control_list_sid: str) -> IpAccessControlListInstance: + """ + Create the IpAccessControlListInstance + + :param ip_access_control_list_sid: The SID of the [IP Access Control List](https://www.twilio.com/docs/voice/sip/api/sip-ipaccesscontrollist-resource) that you want to associate with the trunk. + + :returns: The created IpAccessControlListInstance + """ + + data = values.of( + { + "IpAccessControlListSid": ip_access_control_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAccessControlListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + async def create_async( + self, ip_access_control_list_sid: str + ) -> IpAccessControlListInstance: + """ + Asynchronously create the IpAccessControlListInstance + + :param ip_access_control_list_sid: The SID of the [IP Access Control List](https://www.twilio.com/docs/voice/sip/api/sip-ipaccesscontrollist-resource) that you want to associate with the trunk. + + :returns: The created IpAccessControlListInstance + """ + + data = values.of( + { + "IpAccessControlListSid": ip_access_control_list_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpAccessControlListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[IpAccessControlListInstance]: + """ + Streams IpAccessControlListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpAccessControlListInstance]: + """ + Asynchronously streams IpAccessControlListInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListInstance]: + """ + Lists IpAccessControlListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpAccessControlListInstance]: + """ + Asynchronously lists IpAccessControlListInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpAccessControlListPage: + """ + Retrieve a single page of IpAccessControlListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpAccessControlListInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAccessControlListPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpAccessControlListPage: + """ + Asynchronously retrieve a single page of IpAccessControlListInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpAccessControlListInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpAccessControlListPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> IpAccessControlListPage: + """ + Retrieve a specific page of IpAccessControlListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpAccessControlListInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return IpAccessControlListPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> IpAccessControlListPage: + """ + Asynchronously retrieve a specific page of IpAccessControlListInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpAccessControlListInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpAccessControlListPage(self._version, response, self._solution) + + def get(self, sid: str) -> IpAccessControlListContext: + """ + Constructs a IpAccessControlListContext + + :param sid: The unique string that we created to identify the IpAccessControlList resource to fetch. + """ + return IpAccessControlListContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) + + def __call__(self, sid: str) -> IpAccessControlListContext: + """ + Constructs a IpAccessControlListContext + + :param sid: The unique string that we created to identify the IpAccessControlList resource to fetch. + """ + return IpAccessControlListContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trunking.V1.IpAccessControlListList>" diff --git a/twilio/rest/trunking/v1/trunk/origination_url.py b/twilio/rest/trunking/v1/trunk/origination_url.py new file mode 100644 index 0000000000..082fa34beb --- /dev/null +++ b/twilio/rest/trunking/v1/trunk/origination_url.py @@ -0,0 +1,722 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trunking + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class OriginationUrlInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the OriginationUrl resource. + :ivar sid: The unique string that we created to identify the OriginationUrl resource. + :ivar trunk_sid: The SID of the Trunk that owns the Origination URL. + :ivar weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :ivar enabled: Whether the URL is enabled. The default is `true`. + :ivar sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + trunk_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.weight: Optional[int] = deserialize.integer(payload.get("weight")) + self.enabled: Optional[bool] = payload.get("enabled") + self.sip_url: Optional[str] = payload.get("sip_url") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.priority: Optional[int] = deserialize.integer(payload.get("priority")) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid or self.sid, + } + self._context: Optional[OriginationUrlContext] = None + + @property + def _proxy(self) -> "OriginationUrlContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OriginationUrlContext for this OriginationUrlInstance + """ + if self._context is None: + self._context = OriginationUrlContext( + self._version, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the OriginationUrlInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OriginationUrlInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "OriginationUrlInstance": + """ + Fetch the OriginationUrlInstance + + + :returns: The fetched OriginationUrlInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OriginationUrlInstance": + """ + Asynchronous coroutine to fetch the OriginationUrlInstance + + + :returns: The fetched OriginationUrlInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + weight: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sip_url: Union[str, object] = values.unset, + ) -> "OriginationUrlInstance": + """ + Update the OriginationUrlInstance + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. `sips` is NOT supported. + + :returns: The updated OriginationUrlInstance + """ + return self._proxy.update( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + + async def update_async( + self, + weight: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sip_url: Union[str, object] = values.unset, + ) -> "OriginationUrlInstance": + """ + Asynchronous coroutine to update the OriginationUrlInstance + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. `sips` is NOT supported. + + :returns: The updated OriginationUrlInstance + """ + return await self._proxy.update_async( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trunking.V1.OriginationUrlInstance {}>".format(context) + + +class OriginationUrlContext(InstanceContext): + + def __init__(self, version: Version, trunk_sid: str, sid: str): + """ + Initialize the OriginationUrlContext + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to update the OriginationUrl. + :param sid: The unique string that we created to identify the OriginationUrl resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid, + } + self._uri = "/Trunks/{trunk_sid}/OriginationUrls/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the OriginationUrlInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OriginationUrlInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> OriginationUrlInstance: + """ + Fetch the OriginationUrlInstance + + + :returns: The fetched OriginationUrlInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> OriginationUrlInstance: + """ + Asynchronous coroutine to fetch the OriginationUrlInstance + + + :returns: The fetched OriginationUrlInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + weight: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sip_url: Union[str, object] = values.unset, + ) -> OriginationUrlInstance: + """ + Update the OriginationUrlInstance + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. `sips` is NOT supported. + + :returns: The updated OriginationUrlInstance + """ + + data = values.of( + { + "Weight": weight, + "Priority": priority, + "Enabled": serialize.boolean_to_string(enabled), + "FriendlyName": friendly_name, + "SipUrl": sip_url, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + weight: Union[int, object] = values.unset, + priority: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + sip_url: Union[str, object] = values.unset, + ) -> OriginationUrlInstance: + """ + Asynchronous coroutine to update the OriginationUrlInstance + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. `sips` is NOT supported. + + :returns: The updated OriginationUrlInstance + """ + + data = values.of( + { + "Weight": weight, + "Priority": priority, + "Enabled": serialize.boolean_to_string(enabled), + "FriendlyName": friendly_name, + "SipUrl": sip_url, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trunking.V1.OriginationUrlContext {}>".format(context) + + +class OriginationUrlPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> OriginationUrlInstance: + """ + Build an instance of OriginationUrlInstance + + :param payload: Payload response from the API + """ + return OriginationUrlInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trunking.V1.OriginationUrlPage>" + + +class OriginationUrlList(ListResource): + + def __init__(self, version: Version, trunk_sid: str): + """ + Initialize the OriginationUrlList + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to read the OriginationUrl. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + } + self._uri = "/Trunks/{trunk_sid}/OriginationUrls".format(**self._solution) + + def create( + self, + weight: int, + priority: int, + enabled: bool, + friendly_name: str, + sip_url: str, + ) -> OriginationUrlInstance: + """ + Create the OriginationUrlInstance + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. + + :returns: The created OriginationUrlInstance + """ + + data = values.of( + { + "Weight": weight, + "Priority": priority, + "Enabled": serialize.boolean_to_string(enabled), + "FriendlyName": friendly_name, + "SipUrl": sip_url, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return OriginationUrlInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + async def create_async( + self, + weight: int, + priority: int, + enabled: bool, + friendly_name: str, + sip_url: str, + ) -> OriginationUrlInstance: + """ + Asynchronously create the OriginationUrlInstance + + :param weight: The value that determines the relative share of the load the URI should receive compared to other URIs with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. URLs with higher values receive more load than those with lower ones with the same priority. + :param priority: The relative importance of the URI. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important URI. + :param enabled: Whether the URL is enabled. The default is `true`. + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 64 characters long. + :param sip_url: The SIP address you want Twilio to route your Origination calls to. This must be a `sip:` schema. + + :returns: The created OriginationUrlInstance + """ + + data = values.of( + { + "Weight": weight, + "Priority": priority, + "Enabled": serialize.boolean_to_string(enabled), + "FriendlyName": friendly_name, + "SipUrl": sip_url, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return OriginationUrlInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[OriginationUrlInstance]: + """ + Streams OriginationUrlInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[OriginationUrlInstance]: + """ + Asynchronously streams OriginationUrlInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OriginationUrlInstance]: + """ + Lists OriginationUrlInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OriginationUrlInstance]: + """ + Asynchronously lists OriginationUrlInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OriginationUrlPage: + """ + Retrieve a single page of OriginationUrlInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OriginationUrlInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OriginationUrlPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OriginationUrlPage: + """ + Asynchronously retrieve a single page of OriginationUrlInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of OriginationUrlInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OriginationUrlPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> OriginationUrlPage: + """ + Retrieve a specific page of OriginationUrlInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OriginationUrlInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return OriginationUrlPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> OriginationUrlPage: + """ + Asynchronously retrieve a specific page of OriginationUrlInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OriginationUrlInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return OriginationUrlPage(self._version, response, self._solution) + + def get(self, sid: str) -> OriginationUrlContext: + """ + Constructs a OriginationUrlContext + + :param sid: The unique string that we created to identify the OriginationUrl resource to update. + """ + return OriginationUrlContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) + + def __call__(self, sid: str) -> OriginationUrlContext: + """ + Constructs a OriginationUrlContext + + :param sid: The unique string that we created to identify the OriginationUrl resource to update. + """ + return OriginationUrlContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trunking.V1.OriginationUrlList>" diff --git a/twilio/rest/trunking/v1/trunk/phone_number.py b/twilio/rest/trunking/v1/trunk/phone_number.py new file mode 100644 index 0000000000..a7c3dbe20d --- /dev/null +++ b/twilio/rest/trunking/v1/trunk/phone_number.py @@ -0,0 +1,589 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trunking + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PhoneNumberInstance(InstanceResource): + + class AddressRequirement(object): + NONE = "none" + ANY = "any" + LOCAL = "local" + FOREIGN = "foreign" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the PhoneNumber resource. + :ivar address_requirements: + :ivar api_version: The API version used to start a new TwiML session. + :ivar beta: Whether the phone number is new to the Twilio platform. Can be: `true` or `false`. + :ivar capabilities: The set of Boolean properties that indicate whether a phone number can receive calls or messages. Capabilities are `Voice`, `SMS`, and `MMS` and each capability can be: `true` or `false`. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar links: The URLs of related resources. + :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. + :ivar sid: The unique string that we created to identify the PhoneNumber resource. + :ivar sms_application_sid: The SID of the application that handles SMS messages sent to the phone number. If an `sms_application_sid` is present, we ignore all `sms_*_url` values and use those of the application. + :ivar sms_fallback_method: The HTTP method we use to call `sms_fallback_url`. Can be: `GET` or `POST`. + :ivar sms_fallback_url: The URL that we call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML from `sms_url`. + :ivar sms_method: The HTTP method we use to call `sms_url`. Can be: `GET` or `POST`. + :ivar sms_url: The URL we call using the `sms_method` when the phone number receives an incoming SMS message. + :ivar status_callback: The URL we call using the `status_callback_method` to send status information to your application. + :ivar status_callback_method: The HTTP method we use to call `status_callback`. Can be: `GET` or `POST`. + :ivar trunk_sid: The SID of the Trunk that handles calls to the phone number. If a `trunk_sid` is present, we ignore all of the voice URLs and voice applications and use those set on the Trunk. Setting a `trunk_sid` will automatically delete your `voice_application_sid` and vice versa. + :ivar url: The absolute URL of the resource. + :ivar voice_application_sid: The SID of the application that handles calls to the phone number. If a `voice_application_sid` is present, we ignore all of the voice URLs and use those set on the application. Setting a `voice_application_sid` will automatically delete your `trunk_sid` and vice versa. + :ivar voice_caller_id_lookup: Whether we look up the caller's caller-ID name from the CNAM database ($0.01 per look up). Can be: `true` or `false`. + :ivar voice_fallback_method: The HTTP method that we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call using the `voice_fallback_method` when an error occurs retrieving or executing the TwiML requested by `url`. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_url: The URL we call using the `voice_method` when the phone number receives a call. The `voice_url` is not be used if a `voice_application_sid` or a `trunk_sid` is set. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + trunk_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.address_requirements: Optional[ + "PhoneNumberInstance.AddressRequirement" + ] = payload.get("address_requirements") + self.api_version: Optional[str] = payload.get("api_version") + self.beta: Optional[bool] = payload.get("beta") + self.capabilities: Optional[Dict[str, object]] = payload.get("capabilities") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.phone_number: Optional[str] = payload.get("phone_number") + self.sid: Optional[str] = payload.get("sid") + self.sms_application_sid: Optional[str] = payload.get("sms_application_sid") + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_url: Optional[str] = payload.get("sms_url") + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.trunk_sid: Optional[str] = payload.get("trunk_sid") + self.url: Optional[str] = payload.get("url") + self.voice_application_sid: Optional[str] = payload.get("voice_application_sid") + self.voice_caller_id_lookup: Optional[bool] = payload.get( + "voice_caller_id_lookup" + ) + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_url: Optional[str] = payload.get("voice_url") + + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid or self.sid, + } + self._context: Optional[PhoneNumberContext] = None + + @property + def _proxy(self) -> "PhoneNumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PhoneNumberContext for this PhoneNumberInstance + """ + if self._context is None: + self._context = PhoneNumberContext( + self._version, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "PhoneNumberInstance": + """ + Fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PhoneNumberInstance": + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trunking.V1.PhoneNumberInstance {}>".format(context) + + +class PhoneNumberContext(InstanceContext): + + def __init__(self, version: Version, trunk_sid: str, sid: str): + """ + Initialize the PhoneNumberContext + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to fetch the PhoneNumber resource. + :param sid: The unique string that we created to identify the PhoneNumber resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + "sid": sid, + } + self._uri = "/Trunks/{trunk_sid}/PhoneNumbers/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> PhoneNumberInstance: + """ + Fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PhoneNumberInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> PhoneNumberInstance: + """ + Asynchronous coroutine to fetch the PhoneNumberInstance + + + :returns: The fetched PhoneNumberInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PhoneNumberInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trunking.V1.PhoneNumberContext {}>".format(context) + + +class PhoneNumberPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: + """ + Build an instance of PhoneNumberInstance + + :param payload: Payload response from the API + """ + return PhoneNumberInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trunking.V1.PhoneNumberPage>" + + +class PhoneNumberList(ListResource): + + def __init__(self, version: Version, trunk_sid: str): + """ + Initialize the PhoneNumberList + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to read the PhoneNumber resources. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + } + self._uri = "/Trunks/{trunk_sid}/PhoneNumbers".format(**self._solution) + + def create(self, phone_number_sid: str) -> PhoneNumberInstance: + """ + Create the PhoneNumberInstance + + :param phone_number_sid: The SID of the [Incoming Phone Number](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) that you want to associate with the trunk. + + :returns: The created PhoneNumberInstance + """ + + data = values.of( + { + "PhoneNumberSid": phone_number_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + async def create_async(self, phone_number_sid: str) -> PhoneNumberInstance: + """ + Asynchronously create the PhoneNumberInstance + + :param phone_number_sid: The SID of the [Incoming Phone Number](https://www.twilio.com/docs/phone-numbers/api/incomingphonenumber-resource) that you want to associate with the trunk. + + :returns: The created PhoneNumberInstance + """ + + data = values.of( + { + "PhoneNumberSid": phone_number_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return PhoneNumberInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PhoneNumberInstance]: + """ + Streams PhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PhoneNumberInstance]: + """ + Asynchronously streams PhoneNumberInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PhoneNumberInstance]: + """ + Lists PhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PhoneNumberInstance]: + """ + Asynchronously lists PhoneNumberInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PhoneNumberPage: + """ + Retrieve a single page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PhoneNumberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PhoneNumberPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PhoneNumberPage: + """ + Asynchronously retrieve a single page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PhoneNumberInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PhoneNumberPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> PhoneNumberPage: + """ + Retrieve a specific page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PhoneNumberInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PhoneNumberPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> PhoneNumberPage: + """ + Asynchronously retrieve a specific page of PhoneNumberInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PhoneNumberInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PhoneNumberPage(self._version, response, self._solution) + + def get(self, sid: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param sid: The unique string that we created to identify the PhoneNumber resource to fetch. + """ + return PhoneNumberContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) + + def __call__(self, sid: str) -> PhoneNumberContext: + """ + Constructs a PhoneNumberContext + + :param sid: The unique string that we created to identify the PhoneNumber resource to fetch. + """ + return PhoneNumberContext( + self._version, trunk_sid=self._solution["trunk_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trunking.V1.PhoneNumberList>" diff --git a/twilio/rest/trunking/v1/trunk/recording.py b/twilio/rest/trunking/v1/trunk/recording.py new file mode 100644 index 0000000000..0507662f24 --- /dev/null +++ b/twilio/rest/trunking/v1/trunk/recording.py @@ -0,0 +1,305 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trunking + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class RecordingInstance(InstanceResource): + + class RecordingMode(object): + DO_NOT_RECORD = "do-not-record" + RECORD_FROM_RINGING = "record-from-ringing" + RECORD_FROM_ANSWER = "record-from-answer" + RECORD_FROM_RINGING_DUAL = "record-from-ringing-dual" + RECORD_FROM_ANSWER_DUAL = "record-from-answer-dual" + + class RecordingTrim(object): + TRIM_SILENCE = "trim-silence" + DO_NOT_TRIM = "do-not-trim" + + """ + :ivar mode: + :ivar trim: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], trunk_sid: str): + super().__init__(version) + + self.mode: Optional["RecordingInstance.RecordingMode"] = payload.get("mode") + self.trim: Optional["RecordingInstance.RecordingTrim"] = payload.get("trim") + + self._solution = { + "trunk_sid": trunk_sid, + } + self._context: Optional[RecordingContext] = None + + @property + def _proxy(self) -> "RecordingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RecordingContext for this RecordingInstance + """ + if self._context is None: + self._context = RecordingContext( + self._version, + trunk_sid=self._solution["trunk_sid"], + ) + return self._context + + def fetch(self) -> "RecordingInstance": + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RecordingInstance": + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> "RecordingInstance": + """ + Update the RecordingInstance + + :param mode: + :param trim: + + :returns: The updated RecordingInstance + """ + return self._proxy.update( + mode=mode, + trim=trim, + ) + + async def update_async( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> "RecordingInstance": + """ + Asynchronous coroutine to update the RecordingInstance + + :param mode: + :param trim: + + :returns: The updated RecordingInstance + """ + return await self._proxy.update_async( + mode=mode, + trim=trim, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trunking.V1.RecordingInstance {}>".format(context) + + +class RecordingContext(InstanceContext): + + def __init__(self, version: Version, trunk_sid: str): + """ + Initialize the RecordingContext + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk that will have its recording settings updated. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + } + self._uri = "/Trunks/{trunk_sid}/Recording".format(**self._solution) + + def fetch(self) -> RecordingInstance: + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RecordingInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + ) + + async def fetch_async(self) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + ) + + def update( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> RecordingInstance: + """ + Update the RecordingInstance + + :param mode: + :param trim: + + :returns: The updated RecordingInstance + """ + + data = values.of( + { + "Mode": mode, + "Trim": trim, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + async def update_async( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> RecordingInstance: + """ + Asynchronous coroutine to update the RecordingInstance + + :param mode: + :param trim: + + :returns: The updated RecordingInstance + """ + + data = values.of( + { + "Mode": mode, + "Trim": trim, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trunking.V1.RecordingContext {}>".format(context) + + +class RecordingList(ListResource): + + def __init__(self, version: Version, trunk_sid: str): + """ + Initialize the RecordingList + + :param version: Version that contains the resource + :param trunk_sid: The SID of the Trunk from which to fetch the recording settings. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trunk_sid": trunk_sid, + } + + def get(self) -> RecordingContext: + """ + Constructs a RecordingContext + + """ + return RecordingContext(self._version, trunk_sid=self._solution["trunk_sid"]) + + def __call__(self) -> RecordingContext: + """ + Constructs a RecordingContext + + """ + return RecordingContext(self._version, trunk_sid=self._solution["trunk_sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trunking.V1.RecordingList>" diff --git a/twilio/rest/trusthub/TrusthubBase.py b/twilio/rest/trusthub/TrusthubBase.py new file mode 100644 index 0000000000..97fd32f9b7 --- /dev/null +++ b/twilio/rest/trusthub/TrusthubBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.trusthub.v1 import V1 + + +class TrusthubBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Trusthub Domain + + :returns: Domain for Trusthub + """ + super().__init__(twilio, "https://trusthub.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Trusthub + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub>" diff --git a/twilio/rest/trusthub/__init__.py b/twilio/rest/trusthub/__init__.py new file mode 100644 index 0000000000..3da2fcfd68 --- /dev/null +++ b/twilio/rest/trusthub/__init__.py @@ -0,0 +1,75 @@ +from warnings import warn + +from twilio.rest.trusthub.TrusthubBase import TrusthubBase +from twilio.rest.trusthub.v1.customer_profiles import CustomerProfilesList +from twilio.rest.trusthub.v1.end_user import EndUserList +from twilio.rest.trusthub.v1.end_user_type import EndUserTypeList +from twilio.rest.trusthub.v1.policies import PoliciesList +from twilio.rest.trusthub.v1.supporting_document import SupportingDocumentList +from twilio.rest.trusthub.v1.supporting_document_type import SupportingDocumentTypeList +from twilio.rest.trusthub.v1.trust_products import TrustProductsList + + +class Trusthub(TrusthubBase): + @property + def customer_profiles(self) -> CustomerProfilesList: + warn( + "customer_profiles is deprecated. Use v1.customer_profiles instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.customer_profiles + + @property + def end_users(self) -> EndUserList: + warn( + "end_users is deprecated. Use v1.end_users instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.end_users + + @property + def end_user_types(self) -> EndUserTypeList: + warn( + "end_user_types is deprecated. Use v1.end_user_types instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.end_user_types + + @property + def policies(self) -> PoliciesList: + warn( + "policies is deprecated. Use v1.policies instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.policies + + @property + def supporting_documents(self) -> SupportingDocumentList: + warn( + "supporting_documents is deprecated. Use v1.supporting_documents instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.supporting_documents + + @property + def supporting_document_types(self) -> SupportingDocumentTypeList: + warn( + "supporting_document_types is deprecated. Use v1.supporting_document_types instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.supporting_document_types + + @property + def trust_products(self) -> TrustProductsList: + warn( + "trust_products is deprecated. Use v1.trust_products instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.trust_products diff --git a/twilio/rest/trusthub/v1/__init__.py b/twilio/rest/trusthub/v1/__init__.py new file mode 100644 index 0000000000..596c5ea758 --- /dev/null +++ b/twilio/rest/trusthub/v1/__init__.py @@ -0,0 +1,125 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.trusthub.v1.compliance_inquiries import ComplianceInquiriesList +from twilio.rest.trusthub.v1.compliance_registration_inquiries import ( + ComplianceRegistrationInquiriesList, +) +from twilio.rest.trusthub.v1.compliance_tollfree_inquiries import ( + ComplianceTollfreeInquiriesList, +) +from twilio.rest.trusthub.v1.customer_profiles import CustomerProfilesList +from twilio.rest.trusthub.v1.end_user import EndUserList +from twilio.rest.trusthub.v1.end_user_type import EndUserTypeList +from twilio.rest.trusthub.v1.policies import PoliciesList +from twilio.rest.trusthub.v1.supporting_document import SupportingDocumentList +from twilio.rest.trusthub.v1.supporting_document_type import SupportingDocumentTypeList +from twilio.rest.trusthub.v1.trust_products import TrustProductsList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Trusthub + + :param domain: The Twilio.trusthub domain + """ + super().__init__(domain, "v1") + self._compliance_inquiries: Optional[ComplianceInquiriesList] = None + self._compliance_registration_inquiries: Optional[ + ComplianceRegistrationInquiriesList + ] = None + self._compliance_tollfree_inquiries: Optional[ + ComplianceTollfreeInquiriesList + ] = None + self._customer_profiles: Optional[CustomerProfilesList] = None + self._end_users: Optional[EndUserList] = None + self._end_user_types: Optional[EndUserTypeList] = None + self._policies: Optional[PoliciesList] = None + self._supporting_documents: Optional[SupportingDocumentList] = None + self._supporting_document_types: Optional[SupportingDocumentTypeList] = None + self._trust_products: Optional[TrustProductsList] = None + + @property + def compliance_inquiries(self) -> ComplianceInquiriesList: + if self._compliance_inquiries is None: + self._compliance_inquiries = ComplianceInquiriesList(self) + return self._compliance_inquiries + + @property + def compliance_registration_inquiries(self) -> ComplianceRegistrationInquiriesList: + if self._compliance_registration_inquiries is None: + self._compliance_registration_inquiries = ( + ComplianceRegistrationInquiriesList(self) + ) + return self._compliance_registration_inquiries + + @property + def compliance_tollfree_inquiries(self) -> ComplianceTollfreeInquiriesList: + if self._compliance_tollfree_inquiries is None: + self._compliance_tollfree_inquiries = ComplianceTollfreeInquiriesList(self) + return self._compliance_tollfree_inquiries + + @property + def customer_profiles(self) -> CustomerProfilesList: + if self._customer_profiles is None: + self._customer_profiles = CustomerProfilesList(self) + return self._customer_profiles + + @property + def end_users(self) -> EndUserList: + if self._end_users is None: + self._end_users = EndUserList(self) + return self._end_users + + @property + def end_user_types(self) -> EndUserTypeList: + if self._end_user_types is None: + self._end_user_types = EndUserTypeList(self) + return self._end_user_types + + @property + def policies(self) -> PoliciesList: + if self._policies is None: + self._policies = PoliciesList(self) + return self._policies + + @property + def supporting_documents(self) -> SupportingDocumentList: + if self._supporting_documents is None: + self._supporting_documents = SupportingDocumentList(self) + return self._supporting_documents + + @property + def supporting_document_types(self) -> SupportingDocumentTypeList: + if self._supporting_document_types is None: + self._supporting_document_types = SupportingDocumentTypeList(self) + return self._supporting_document_types + + @property + def trust_products(self) -> TrustProductsList: + if self._trust_products is None: + self._trust_products = TrustProductsList(self) + return self._trust_products + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1>" diff --git a/twilio/rest/trusthub/v1/compliance_inquiries.py b/twilio/rest/trusthub/v1/compliance_inquiries.py new file mode 100644 index 0000000000..3c1abd596a --- /dev/null +++ b/twilio/rest/trusthub/v1/compliance_inquiries.py @@ -0,0 +1,304 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ComplianceInquiriesInstance(InstanceResource): + """ + :ivar inquiry_id: The unique ID used to start an embedded compliance registration session. + :ivar inquiry_session_token: The session token used to start an embedded compliance registration session. + :ivar customer_id: The CustomerID matching the Customer Profile that should be resumed or resubmitted for editing. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + customer_id: Optional[str] = None, + ): + super().__init__(version) + + self.inquiry_id: Optional[str] = payload.get("inquiry_id") + self.inquiry_session_token: Optional[str] = payload.get("inquiry_session_token") + self.customer_id: Optional[str] = payload.get("customer_id") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "customer_id": customer_id or self.customer_id, + } + self._context: Optional[ComplianceInquiriesContext] = None + + @property + def _proxy(self) -> "ComplianceInquiriesContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ComplianceInquiriesContext for this ComplianceInquiriesInstance + """ + if self._context is None: + self._context = ComplianceInquiriesContext( + self._version, + customer_id=self._solution["customer_id"], + ) + return self._context + + def update( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> "ComplianceInquiriesInstance": + """ + Update the ComplianceInquiriesInstance + + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceInquiriesInstance + """ + return self._proxy.update( + primary_profile_sid=primary_profile_sid, + theme_set_id=theme_set_id, + ) + + async def update_async( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> "ComplianceInquiriesInstance": + """ + Asynchronous coroutine to update the ComplianceInquiriesInstance + + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceInquiriesInstance + """ + return await self._proxy.update_async( + primary_profile_sid=primary_profile_sid, + theme_set_id=theme_set_id, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.ComplianceInquiriesInstance {}>".format(context) + + +class ComplianceInquiriesContext(InstanceContext): + + def __init__(self, version: Version, customer_id: str): + """ + Initialize the ComplianceInquiriesContext + + :param version: Version that contains the resource + :param customer_id: The unique CustomerId matching the Customer Profile/Compliance Inquiry that should be resumed or resubmitted. This value will have been returned by the initial Compliance Inquiry creation call. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "customer_id": customer_id, + } + self._uri = "/ComplianceInquiries/Customers/{customer_id}/Initialize".format( + **self._solution + ) + + def update( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> ComplianceInquiriesInstance: + """ + Update the ComplianceInquiriesInstance + + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceInquiriesInstance + """ + + data = values.of( + { + "PrimaryProfileSid": primary_profile_sid, + "ThemeSetId": theme_set_id, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ComplianceInquiriesInstance( + self._version, payload, customer_id=self._solution["customer_id"] + ) + + async def update_async( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> ComplianceInquiriesInstance: + """ + Asynchronous coroutine to update the ComplianceInquiriesInstance + + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceInquiriesInstance + """ + + data = values.of( + { + "PrimaryProfileSid": primary_profile_sid, + "ThemeSetId": theme_set_id, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ComplianceInquiriesInstance( + self._version, payload, customer_id=self._solution["customer_id"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.ComplianceInquiriesContext {}>".format(context) + + +class ComplianceInquiriesList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ComplianceInquiriesList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ComplianceInquiries/Customers/Initialize" + + def create( + self, + primary_profile_sid: str, + notification_email: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ComplianceInquiriesInstance: + """ + Create the ComplianceInquiriesInstance + + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + :param notification_email: The email address that approval status updates will be sent to. If not specified, the email address associated with your primary customer profile will be used. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The created ComplianceInquiriesInstance + """ + + data = values.of( + { + "PrimaryProfileSid": primary_profile_sid, + "NotificationEmail": notification_email, + "ThemeSetId": theme_set_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ComplianceInquiriesInstance(self._version, payload) + + async def create_async( + self, + primary_profile_sid: str, + notification_email: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ComplianceInquiriesInstance: + """ + Asynchronously create the ComplianceInquiriesInstance + + :param primary_profile_sid: The unique SID identifier of the Primary Customer Profile that should be used as a parent. Only necessary when creating a secondary Customer Profile. + :param notification_email: The email address that approval status updates will be sent to. If not specified, the email address associated with your primary customer profile will be used. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The created ComplianceInquiriesInstance + """ + + data = values.of( + { + "PrimaryProfileSid": primary_profile_sid, + "NotificationEmail": notification_email, + "ThemeSetId": theme_set_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ComplianceInquiriesInstance(self._version, payload) + + def get(self, customer_id: str) -> ComplianceInquiriesContext: + """ + Constructs a ComplianceInquiriesContext + + :param customer_id: The unique CustomerId matching the Customer Profile/Compliance Inquiry that should be resumed or resubmitted. This value will have been returned by the initial Compliance Inquiry creation call. + """ + return ComplianceInquiriesContext(self._version, customer_id=customer_id) + + def __call__(self, customer_id: str) -> ComplianceInquiriesContext: + """ + Constructs a ComplianceInquiriesContext + + :param customer_id: The unique CustomerId matching the Customer Profile/Compliance Inquiry that should be resumed or resubmitted. This value will have been returned by the initial Compliance Inquiry creation call. + """ + return ComplianceInquiriesContext(self._version, customer_id=customer_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.ComplianceInquiriesList>" diff --git a/twilio/rest/trusthub/v1/compliance_registration_inquiries.py b/twilio/rest/trusthub/v1/compliance_registration_inquiries.py new file mode 100644 index 0000000000..eccd1ac8cf --- /dev/null +++ b/twilio/rest/trusthub/v1/compliance_registration_inquiries.py @@ -0,0 +1,579 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ComplianceRegistrationInquiriesInstance(InstanceResource): + + class BusinessIdentityType(object): + DIRECT_CUSTOMER = "direct_customer" + ISV_RESELLER_OR_PARTNER = "isv_reseller_or_partner" + UNKNOWN = "unknown" + + class BusinessRegistrationAuthority(object): + UK_CRN = "UK:CRN" + US_EIN = "US:EIN" + CA_CBN = "CA:CBN" + AU_ACN = "AU:ACN" + OTHER = "Other" + + class EndUserType(object): + INDIVIDUAL = "Individual" + BUSINESS = "Business" + + class PhoneNumberType(object): + LOCAL = "local" + NATIONAL = "national" + MOBILE = "mobile" + TOLL_FREE = "toll-free" + + """ + :ivar inquiry_id: The unique ID used to start an embedded compliance registration session. + :ivar inquiry_session_token: The session token used to start an embedded compliance registration session. + :ivar registration_id: The RegistrationId matching the Registration Profile that should be resumed or resubmitted for editing. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + registration_id: Optional[str] = None, + ): + super().__init__(version) + + self.inquiry_id: Optional[str] = payload.get("inquiry_id") + self.inquiry_session_token: Optional[str] = payload.get("inquiry_session_token") + self.registration_id: Optional[str] = payload.get("registration_id") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "registration_id": registration_id or self.registration_id, + } + self._context: Optional[ComplianceRegistrationInquiriesContext] = None + + @property + def _proxy(self) -> "ComplianceRegistrationInquiriesContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ComplianceRegistrationInquiriesContext for this ComplianceRegistrationInquiriesInstance + """ + if self._context is None: + self._context = ComplianceRegistrationInquiriesContext( + self._version, + registration_id=self._solution["registration_id"], + ) + return self._context + + def update( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> "ComplianceRegistrationInquiriesInstance": + """ + Update the ComplianceRegistrationInquiriesInstance + + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceRegistrationInquiriesInstance + """ + return self._proxy.update( + is_isv_embed=is_isv_embed, + theme_set_id=theme_set_id, + ) + + async def update_async( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> "ComplianceRegistrationInquiriesInstance": + """ + Asynchronous coroutine to update the ComplianceRegistrationInquiriesInstance + + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceRegistrationInquiriesInstance + """ + return await self._proxy.update_async( + is_isv_embed=is_isv_embed, + theme_set_id=theme_set_id, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.ComplianceRegistrationInquiriesInstance {}>".format( + context + ) + + +class ComplianceRegistrationInquiriesContext(InstanceContext): + + def __init__(self, version: Version, registration_id: str): + """ + Initialize the ComplianceRegistrationInquiriesContext + + :param version: Version that contains the resource + :param registration_id: The unique RegistrationId matching the Regulatory Compliance Inquiry that should be resumed or resubmitted. This value will have been returned by the initial Regulatory Compliance Inquiry creation call. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "registration_id": registration_id, + } + self._uri = "/ComplianceInquiries/Registration/{registration_id}/RegulatoryCompliance/GB/Initialize".format( + **self._solution + ) + + def update( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ComplianceRegistrationInquiriesInstance: + """ + Update the ComplianceRegistrationInquiriesInstance + + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceRegistrationInquiriesInstance + """ + + data = values.of( + { + "IsIsvEmbed": serialize.boolean_to_string(is_isv_embed), + "ThemeSetId": theme_set_id, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ComplianceRegistrationInquiriesInstance( + self._version, payload, registration_id=self._solution["registration_id"] + ) + + async def update_async( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ComplianceRegistrationInquiriesInstance: + """ + Asynchronous coroutine to update the ComplianceRegistrationInquiriesInstance + + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The updated ComplianceRegistrationInquiriesInstance + """ + + data = values.of( + { + "IsIsvEmbed": serialize.boolean_to_string(is_isv_embed), + "ThemeSetId": theme_set_id, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ComplianceRegistrationInquiriesInstance( + self._version, payload, registration_id=self._solution["registration_id"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.ComplianceRegistrationInquiriesContext {}>".format( + context + ) + + +class ComplianceRegistrationInquiriesList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ComplianceRegistrationInquiriesList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = ( + "/ComplianceInquiries/Registration/RegulatoryCompliance/GB/Initialize" + ) + + def create( + self, + end_user_type: "ComplianceRegistrationInquiriesInstance.EndUserType", + phone_number_type: "ComplianceRegistrationInquiriesInstance.PhoneNumberType", + business_identity_type: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessIdentityType", object + ] = values.unset, + business_registration_authority: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessRegistrationAuthority", + object, + ] = values.unset, + business_legal_name: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + accepted_notification_receipt: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_website_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + authorized_representative1_first_name: Union[str, object] = values.unset, + authorized_representative1_last_name: Union[str, object] = values.unset, + authorized_representative1_phone: Union[str, object] = values.unset, + authorized_representative1_email: Union[str, object] = values.unset, + authorized_representative1_date_of_birth: Union[str, object] = values.unset, + address_street: Union[str, object] = values.unset, + address_street_secondary: Union[str, object] = values.unset, + address_city: Union[str, object] = values.unset, + address_subdivision: Union[str, object] = values.unset, + address_postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + emergency_address_street: Union[str, object] = values.unset, + emergency_address_street_secondary: Union[str, object] = values.unset, + emergency_address_city: Union[str, object] = values.unset, + emergency_address_subdivision: Union[str, object] = values.unset, + emergency_address_postal_code: Union[str, object] = values.unset, + emergency_address_country_code: Union[str, object] = values.unset, + use_address_as_emergency_address: Union[bool, object] = values.unset, + file_name: Union[str, object] = values.unset, + file: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + individual_email: Union[str, object] = values.unset, + individual_phone: Union[str, object] = values.unset, + is_isv_embed: Union[bool, object] = values.unset, + isv_registering_for_self_or_tenant: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ComplianceRegistrationInquiriesInstance: + """ + Create the ComplianceRegistrationInquiriesInstance + + :param end_user_type: + :param phone_number_type: + :param business_identity_type: + :param business_registration_authority: + :param business_legal_name: he name of the business or organization using the Tollfree number. + :param notification_email: he email address to receive the notification about the verification result. + :param accepted_notification_receipt: The email address to receive the notification about the verification result. + :param business_registration_number: Business registration number of the business + :param business_website_url: The URL of the business website + :param friendly_name: Friendly name for your business information + :param authorized_representative1_first_name: First name of the authorized representative + :param authorized_representative1_last_name: Last name of the authorized representative + :param authorized_representative1_phone: Phone number of the authorized representative + :param authorized_representative1_email: Email address of the authorized representative + :param authorized_representative1_date_of_birth: Birthdate of the authorized representative + :param address_street: Street address of the business + :param address_street_secondary: Street address of the business + :param address_city: City of the business + :param address_subdivision: State or province of the business + :param address_postal_code: Postal code of the business + :param address_country_code: Country code of the business + :param emergency_address_street: Street address of the business + :param emergency_address_street_secondary: Street address of the business + :param emergency_address_city: City of the business + :param emergency_address_subdivision: State or province of the business + :param emergency_address_postal_code: Postal code of the business + :param emergency_address_country_code: Country code of the business + :param use_address_as_emergency_address: Use the business address as the emergency address + :param file_name: The name of the verification document to upload + :param file: The verification document to upload + :param first_name: The first name of the Individual User. + :param last_name: The last name of the Individual User. + :param date_of_birth: The date of birth of the Individual User. + :param individual_email: The email address of the Individual User. + :param individual_phone: The phone number of the Individual User. + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param isv_registering_for_self_or_tenant: Indicates if the isv registering for self or tenant. + :param status_callback_url: The url we call to inform you of bundle changes. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The created ComplianceRegistrationInquiriesInstance + """ + + data = values.of( + { + "EndUserType": end_user_type, + "PhoneNumberType": phone_number_type, + "BusinessIdentityType": business_identity_type, + "BusinessRegistrationAuthority": business_registration_authority, + "BusinessLegalName": business_legal_name, + "NotificationEmail": notification_email, + "AcceptedNotificationReceipt": serialize.boolean_to_string( + accepted_notification_receipt + ), + "BusinessRegistrationNumber": business_registration_number, + "BusinessWebsiteUrl": business_website_url, + "FriendlyName": friendly_name, + "AuthorizedRepresentative1FirstName": authorized_representative1_first_name, + "AuthorizedRepresentative1LastName": authorized_representative1_last_name, + "AuthorizedRepresentative1Phone": authorized_representative1_phone, + "AuthorizedRepresentative1Email": authorized_representative1_email, + "AuthorizedRepresentative1DateOfBirth": authorized_representative1_date_of_birth, + "AddressStreet": address_street, + "AddressStreetSecondary": address_street_secondary, + "AddressCity": address_city, + "AddressSubdivision": address_subdivision, + "AddressPostalCode": address_postal_code, + "AddressCountryCode": address_country_code, + "EmergencyAddressStreet": emergency_address_street, + "EmergencyAddressStreetSecondary": emergency_address_street_secondary, + "EmergencyAddressCity": emergency_address_city, + "EmergencyAddressSubdivision": emergency_address_subdivision, + "EmergencyAddressPostalCode": emergency_address_postal_code, + "EmergencyAddressCountryCode": emergency_address_country_code, + "UseAddressAsEmergencyAddress": serialize.boolean_to_string( + use_address_as_emergency_address + ), + "FileName": file_name, + "File": file, + "FirstName": first_name, + "LastName": last_name, + "DateOfBirth": date_of_birth, + "IndividualEmail": individual_email, + "IndividualPhone": individual_phone, + "IsIsvEmbed": serialize.boolean_to_string(is_isv_embed), + "IsvRegisteringForSelfOrTenant": isv_registering_for_self_or_tenant, + "StatusCallbackUrl": status_callback_url, + "ThemeSetId": theme_set_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ComplianceRegistrationInquiriesInstance(self._version, payload) + + async def create_async( + self, + end_user_type: "ComplianceRegistrationInquiriesInstance.EndUserType", + phone_number_type: "ComplianceRegistrationInquiriesInstance.PhoneNumberType", + business_identity_type: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessIdentityType", object + ] = values.unset, + business_registration_authority: Union[ + "ComplianceRegistrationInquiriesInstance.BusinessRegistrationAuthority", + object, + ] = values.unset, + business_legal_name: Union[str, object] = values.unset, + notification_email: Union[str, object] = values.unset, + accepted_notification_receipt: Union[bool, object] = values.unset, + business_registration_number: Union[str, object] = values.unset, + business_website_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + authorized_representative1_first_name: Union[str, object] = values.unset, + authorized_representative1_last_name: Union[str, object] = values.unset, + authorized_representative1_phone: Union[str, object] = values.unset, + authorized_representative1_email: Union[str, object] = values.unset, + authorized_representative1_date_of_birth: Union[str, object] = values.unset, + address_street: Union[str, object] = values.unset, + address_street_secondary: Union[str, object] = values.unset, + address_city: Union[str, object] = values.unset, + address_subdivision: Union[str, object] = values.unset, + address_postal_code: Union[str, object] = values.unset, + address_country_code: Union[str, object] = values.unset, + emergency_address_street: Union[str, object] = values.unset, + emergency_address_street_secondary: Union[str, object] = values.unset, + emergency_address_city: Union[str, object] = values.unset, + emergency_address_subdivision: Union[str, object] = values.unset, + emergency_address_postal_code: Union[str, object] = values.unset, + emergency_address_country_code: Union[str, object] = values.unset, + use_address_as_emergency_address: Union[bool, object] = values.unset, + file_name: Union[str, object] = values.unset, + file: Union[str, object] = values.unset, + first_name: Union[str, object] = values.unset, + last_name: Union[str, object] = values.unset, + date_of_birth: Union[str, object] = values.unset, + individual_email: Union[str, object] = values.unset, + individual_phone: Union[str, object] = values.unset, + is_isv_embed: Union[bool, object] = values.unset, + isv_registering_for_self_or_tenant: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> ComplianceRegistrationInquiriesInstance: + """ + Asynchronously create the ComplianceRegistrationInquiriesInstance + + :param end_user_type: + :param phone_number_type: + :param business_identity_type: + :param business_registration_authority: + :param business_legal_name: he name of the business or organization using the Tollfree number. + :param notification_email: he email address to receive the notification about the verification result. + :param accepted_notification_receipt: The email address to receive the notification about the verification result. + :param business_registration_number: Business registration number of the business + :param business_website_url: The URL of the business website + :param friendly_name: Friendly name for your business information + :param authorized_representative1_first_name: First name of the authorized representative + :param authorized_representative1_last_name: Last name of the authorized representative + :param authorized_representative1_phone: Phone number of the authorized representative + :param authorized_representative1_email: Email address of the authorized representative + :param authorized_representative1_date_of_birth: Birthdate of the authorized representative + :param address_street: Street address of the business + :param address_street_secondary: Street address of the business + :param address_city: City of the business + :param address_subdivision: State or province of the business + :param address_postal_code: Postal code of the business + :param address_country_code: Country code of the business + :param emergency_address_street: Street address of the business + :param emergency_address_street_secondary: Street address of the business + :param emergency_address_city: City of the business + :param emergency_address_subdivision: State or province of the business + :param emergency_address_postal_code: Postal code of the business + :param emergency_address_country_code: Country code of the business + :param use_address_as_emergency_address: Use the business address as the emergency address + :param file_name: The name of the verification document to upload + :param file: The verification document to upload + :param first_name: The first name of the Individual User. + :param last_name: The last name of the Individual User. + :param date_of_birth: The date of birth of the Individual User. + :param individual_email: The email address of the Individual User. + :param individual_phone: The phone number of the Individual User. + :param is_isv_embed: Indicates if the inquiry is being started from an ISV embedded component. + :param isv_registering_for_self_or_tenant: Indicates if the isv registering for self or tenant. + :param status_callback_url: The url we call to inform you of bundle changes. + :param theme_set_id: Theme id for styling the inquiry form. + + :returns: The created ComplianceRegistrationInquiriesInstance + """ + + data = values.of( + { + "EndUserType": end_user_type, + "PhoneNumberType": phone_number_type, + "BusinessIdentityType": business_identity_type, + "BusinessRegistrationAuthority": business_registration_authority, + "BusinessLegalName": business_legal_name, + "NotificationEmail": notification_email, + "AcceptedNotificationReceipt": serialize.boolean_to_string( + accepted_notification_receipt + ), + "BusinessRegistrationNumber": business_registration_number, + "BusinessWebsiteUrl": business_website_url, + "FriendlyName": friendly_name, + "AuthorizedRepresentative1FirstName": authorized_representative1_first_name, + "AuthorizedRepresentative1LastName": authorized_representative1_last_name, + "AuthorizedRepresentative1Phone": authorized_representative1_phone, + "AuthorizedRepresentative1Email": authorized_representative1_email, + "AuthorizedRepresentative1DateOfBirth": authorized_representative1_date_of_birth, + "AddressStreet": address_street, + "AddressStreetSecondary": address_street_secondary, + "AddressCity": address_city, + "AddressSubdivision": address_subdivision, + "AddressPostalCode": address_postal_code, + "AddressCountryCode": address_country_code, + "EmergencyAddressStreet": emergency_address_street, + "EmergencyAddressStreetSecondary": emergency_address_street_secondary, + "EmergencyAddressCity": emergency_address_city, + "EmergencyAddressSubdivision": emergency_address_subdivision, + "EmergencyAddressPostalCode": emergency_address_postal_code, + "EmergencyAddressCountryCode": emergency_address_country_code, + "UseAddressAsEmergencyAddress": serialize.boolean_to_string( + use_address_as_emergency_address + ), + "FileName": file_name, + "File": file, + "FirstName": first_name, + "LastName": last_name, + "DateOfBirth": date_of_birth, + "IndividualEmail": individual_email, + "IndividualPhone": individual_phone, + "IsIsvEmbed": serialize.boolean_to_string(is_isv_embed), + "IsvRegisteringForSelfOrTenant": isv_registering_for_self_or_tenant, + "StatusCallbackUrl": status_callback_url, + "ThemeSetId": theme_set_id, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ComplianceRegistrationInquiriesInstance(self._version, payload) + + def get(self, registration_id: str) -> ComplianceRegistrationInquiriesContext: + """ + Constructs a ComplianceRegistrationInquiriesContext + + :param registration_id: The unique RegistrationId matching the Regulatory Compliance Inquiry that should be resumed or resubmitted. This value will have been returned by the initial Regulatory Compliance Inquiry creation call. + """ + return ComplianceRegistrationInquiriesContext( + self._version, registration_id=registration_id + ) + + def __call__(self, registration_id: str) -> ComplianceRegistrationInquiriesContext: + """ + Constructs a ComplianceRegistrationInquiriesContext + + :param registration_id: The unique RegistrationId matching the Regulatory Compliance Inquiry that should be resumed or resubmitted. This value will have been returned by the initial Regulatory Compliance Inquiry creation call. + """ + return ComplianceRegistrationInquiriesContext( + self._version, registration_id=registration_id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.ComplianceRegistrationInquiriesList>" diff --git a/twilio/rest/trusthub/v1/compliance_tollfree_inquiries.py b/twilio/rest/trusthub/v1/compliance_tollfree_inquiries.py new file mode 100644 index 0000000000..9cf259a318 --- /dev/null +++ b/twilio/rest/trusthub/v1/compliance_tollfree_inquiries.py @@ -0,0 +1,274 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union +from twilio.base import serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ComplianceTollfreeInquiriesInstance(InstanceResource): + + class OptInType(object): + VERBAL = "VERBAL" + WEB_FORM = "WEB_FORM" + PAPER_FORM = "PAPER_FORM" + VIA_TEXT = "VIA_TEXT" + MOBILE_QR_CODE = "MOBILE_QR_CODE" + + """ + :ivar inquiry_id: The unique ID used to start an embedded compliance registration session. + :ivar inquiry_session_token: The session token used to start an embedded compliance registration session. + :ivar registration_id: The TolfreeId matching the Tollfree Profile that should be resumed or resubmitted for editing. + :ivar url: The URL of this resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.inquiry_id: Optional[str] = payload.get("inquiry_id") + self.inquiry_session_token: Optional[str] = payload.get("inquiry_session_token") + self.registration_id: Optional[str] = payload.get("registration_id") + self.url: Optional[str] = payload.get("url") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Trusthub.V1.ComplianceTollfreeInquiriesInstance>" + + +class ComplianceTollfreeInquiriesList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ComplianceTollfreeInquiriesList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ComplianceInquiries/Tollfree/Initialize" + + def create( + self, + tollfree_phone_number: str, + notification_email: str, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "ComplianceTollfreeInquiriesInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + skip_messaging_use_case: Union[bool, object] = values.unset, + ) -> ComplianceTollfreeInquiriesInstance: + """ + Create the ComplianceTollfreeInquiriesInstance + + :param tollfree_phone_number: The Tollfree phone number to be verified + :param notification_email: The email address to receive the notification about the verification result. + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The phone number of the contact for the business or organization using the Tollfree number. + :param theme_set_id: Theme id for styling the inquiry form. + :param skip_messaging_use_case: Skip the messaging use case screen of the inquiry form. + + :returns: The created ComplianceTollfreeInquiriesInstance + """ + + data = values.of( + { + "TollfreePhoneNumber": tollfree_phone_number, + "NotificationEmail": notification_email, + "BusinessName": business_name, + "BusinessWebsite": business_website, + "UseCaseCategories": serialize.map(use_case_categories, lambda e: e), + "UseCaseSummary": use_case_summary, + "ProductionMessageSample": production_message_sample, + "OptInImageUrls": serialize.map(opt_in_image_urls, lambda e: e), + "OptInType": opt_in_type, + "MessageVolume": message_volume, + "BusinessStreetAddress": business_street_address, + "BusinessStreetAddress2": business_street_address2, + "BusinessCity": business_city, + "BusinessStateProvinceRegion": business_state_province_region, + "BusinessPostalCode": business_postal_code, + "BusinessCountry": business_country, + "AdditionalInformation": additional_information, + "BusinessContactFirstName": business_contact_first_name, + "BusinessContactLastName": business_contact_last_name, + "BusinessContactEmail": business_contact_email, + "BusinessContactPhone": business_contact_phone, + "ThemeSetId": theme_set_id, + "SkipMessagingUseCase": serialize.boolean_to_string( + skip_messaging_use_case + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ComplianceTollfreeInquiriesInstance(self._version, payload) + + async def create_async( + self, + tollfree_phone_number: str, + notification_email: str, + business_name: Union[str, object] = values.unset, + business_website: Union[str, object] = values.unset, + use_case_categories: Union[List[str], object] = values.unset, + use_case_summary: Union[str, object] = values.unset, + production_message_sample: Union[str, object] = values.unset, + opt_in_image_urls: Union[List[str], object] = values.unset, + opt_in_type: Union[ + "ComplianceTollfreeInquiriesInstance.OptInType", object + ] = values.unset, + message_volume: Union[str, object] = values.unset, + business_street_address: Union[str, object] = values.unset, + business_street_address2: Union[str, object] = values.unset, + business_city: Union[str, object] = values.unset, + business_state_province_region: Union[str, object] = values.unset, + business_postal_code: Union[str, object] = values.unset, + business_country: Union[str, object] = values.unset, + additional_information: Union[str, object] = values.unset, + business_contact_first_name: Union[str, object] = values.unset, + business_contact_last_name: Union[str, object] = values.unset, + business_contact_email: Union[str, object] = values.unset, + business_contact_phone: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + skip_messaging_use_case: Union[bool, object] = values.unset, + ) -> ComplianceTollfreeInquiriesInstance: + """ + Asynchronously create the ComplianceTollfreeInquiriesInstance + + :param tollfree_phone_number: The Tollfree phone number to be verified + :param notification_email: The email address to receive the notification about the verification result. + :param business_name: The name of the business or organization using the Tollfree number. + :param business_website: The website of the business or organization using the Tollfree number. + :param use_case_categories: The category of the use case for the Tollfree Number. List as many are applicable.. + :param use_case_summary: Use this to further explain how messaging is used by the business or organization. + :param production_message_sample: An example of message content, i.e. a sample message. + :param opt_in_image_urls: Link to an image that shows the opt-in workflow. Multiple images allowed and must be a publicly hosted URL. + :param opt_in_type: + :param message_volume: Estimate monthly volume of messages from the Tollfree Number. + :param business_street_address: The address of the business or organization using the Tollfree number. + :param business_street_address2: The address of the business or organization using the Tollfree number. + :param business_city: The city of the business or organization using the Tollfree number. + :param business_state_province_region: The state/province/region of the business or organization using the Tollfree number. + :param business_postal_code: The postal code of the business or organization using the Tollfree number. + :param business_country: The country of the business or organization using the Tollfree number. + :param additional_information: Additional information to be provided for verification. + :param business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. + :param business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. + :param business_contact_email: The email address of the contact for the business or organization using the Tollfree number. + :param business_contact_phone: The phone number of the contact for the business or organization using the Tollfree number. + :param theme_set_id: Theme id for styling the inquiry form. + :param skip_messaging_use_case: Skip the messaging use case screen of the inquiry form. + + :returns: The created ComplianceTollfreeInquiriesInstance + """ + + data = values.of( + { + "TollfreePhoneNumber": tollfree_phone_number, + "NotificationEmail": notification_email, + "BusinessName": business_name, + "BusinessWebsite": business_website, + "UseCaseCategories": serialize.map(use_case_categories, lambda e: e), + "UseCaseSummary": use_case_summary, + "ProductionMessageSample": production_message_sample, + "OptInImageUrls": serialize.map(opt_in_image_urls, lambda e: e), + "OptInType": opt_in_type, + "MessageVolume": message_volume, + "BusinessStreetAddress": business_street_address, + "BusinessStreetAddress2": business_street_address2, + "BusinessCity": business_city, + "BusinessStateProvinceRegion": business_state_province_region, + "BusinessPostalCode": business_postal_code, + "BusinessCountry": business_country, + "AdditionalInformation": additional_information, + "BusinessContactFirstName": business_contact_first_name, + "BusinessContactLastName": business_contact_last_name, + "BusinessContactEmail": business_contact_email, + "BusinessContactPhone": business_contact_phone, + "ThemeSetId": theme_set_id, + "SkipMessagingUseCase": serialize.boolean_to_string( + skip_messaging_use_case + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ComplianceTollfreeInquiriesInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.ComplianceTollfreeInquiriesList>" diff --git a/twilio/rest/trusthub/v1/customer_profiles/__init__.py b/twilio/rest/trusthub/v1/customer_profiles/__init__.py new file mode 100644 index 0000000000..bf5264e31d --- /dev/null +++ b/twilio/rest/trusthub/v1/customer_profiles/__init__.py @@ -0,0 +1,833 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.trusthub.v1.customer_profiles.customer_profiles_channel_endpoint_assignment import ( + CustomerProfilesChannelEndpointAssignmentList, +) +from twilio.rest.trusthub.v1.customer_profiles.customer_profiles_entity_assignments import ( + CustomerProfilesEntityAssignmentsList, +) +from twilio.rest.trusthub.v1.customer_profiles.customer_profiles_evaluations import ( + CustomerProfilesEvaluationsList, +) + + +class CustomerProfilesInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PENDING_REVIEW = "pending-review" + IN_REVIEW = "in-review" + TWILIO_REJECTED = "twilio-rejected" + TWILIO_APPROVED = "twilio-approved" + + """ + :ivar sid: The unique string that we created to identify the Customer-Profile resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Customer-Profile resource. + :ivar policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar status: + :ivar valid_until: The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format when the resource will be valid until. + :ivar email: The email address that will receive updates when the Customer-Profile resource changes status. + :ivar status_callback: The URL we call to inform your application of status changes. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Customer-Profile resource. + :ivar links: The URLs of the Assigned Items of the Customer-Profile resource. + :ivar errors: The error codes associated with the rejection of the Customer-Profile. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.policy_sid: Optional[str] = payload.get("policy_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["CustomerProfilesInstance.Status"] = payload.get("status") + self.valid_until: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("valid_until") + ) + self.email: Optional[str] = payload.get("email") + self.status_callback: Optional[str] = payload.get("status_callback") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CustomerProfilesContext] = None + + @property + def _proxy(self) -> "CustomerProfilesContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CustomerProfilesContext for this CustomerProfilesInstance + """ + if self._context is None: + self._context = CustomerProfilesContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CustomerProfilesInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CustomerProfilesInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CustomerProfilesInstance": + """ + Fetch the CustomerProfilesInstance + + + :returns: The fetched CustomerProfilesInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CustomerProfilesInstance": + """ + Asynchronous coroutine to fetch the CustomerProfilesInstance + + + :returns: The fetched CustomerProfilesInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> "CustomerProfilesInstance": + """ + Update the CustomerProfilesInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + + :returns: The updated CustomerProfilesInstance + """ + return self._proxy.update( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + + async def update_async( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> "CustomerProfilesInstance": + """ + Asynchronous coroutine to update the CustomerProfilesInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + + :returns: The updated CustomerProfilesInstance + """ + return await self._proxy.update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + + @property + def customer_profiles_channel_endpoint_assignment( + self, + ) -> CustomerProfilesChannelEndpointAssignmentList: + """ + Access the customer_profiles_channel_endpoint_assignment + """ + return self._proxy.customer_profiles_channel_endpoint_assignment + + @property + def customer_profiles_entity_assignments( + self, + ) -> CustomerProfilesEntityAssignmentsList: + """ + Access the customer_profiles_entity_assignments + """ + return self._proxy.customer_profiles_entity_assignments + + @property + def customer_profiles_evaluations(self) -> CustomerProfilesEvaluationsList: + """ + Access the customer_profiles_evaluations + """ + return self._proxy.customer_profiles_evaluations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.CustomerProfilesInstance {}>".format(context) + + +class CustomerProfilesContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CustomerProfilesContext + + :param version: Version that contains the resource + :param sid: The unique string that we created to identify the Customer-Profile resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/CustomerProfiles/{sid}".format(**self._solution) + + self._customer_profiles_channel_endpoint_assignment: Optional[ + CustomerProfilesChannelEndpointAssignmentList + ] = None + self._customer_profiles_entity_assignments: Optional[ + CustomerProfilesEntityAssignmentsList + ] = None + self._customer_profiles_evaluations: Optional[ + CustomerProfilesEvaluationsList + ] = None + + def delete(self) -> bool: + """ + Deletes the CustomerProfilesInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CustomerProfilesInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CustomerProfilesInstance: + """ + Fetch the CustomerProfilesInstance + + + :returns: The fetched CustomerProfilesInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CustomerProfilesInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CustomerProfilesInstance: + """ + Asynchronous coroutine to fetch the CustomerProfilesInstance + + + :returns: The fetched CustomerProfilesInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CustomerProfilesInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> CustomerProfilesInstance: + """ + Update the CustomerProfilesInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + + :returns: The updated CustomerProfilesInstance + """ + + data = values.of( + { + "Status": status, + "StatusCallback": status_callback, + "FriendlyName": friendly_name, + "Email": email, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomerProfilesInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> CustomerProfilesInstance: + """ + Asynchronous coroutine to update the CustomerProfilesInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + + :returns: The updated CustomerProfilesInstance + """ + + data = values.of( + { + "Status": status, + "StatusCallback": status_callback, + "FriendlyName": friendly_name, + "Email": email, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomerProfilesInstance( + self._version, payload, sid=self._solution["sid"] + ) + + @property + def customer_profiles_channel_endpoint_assignment( + self, + ) -> CustomerProfilesChannelEndpointAssignmentList: + """ + Access the customer_profiles_channel_endpoint_assignment + """ + if self._customer_profiles_channel_endpoint_assignment is None: + self._customer_profiles_channel_endpoint_assignment = ( + CustomerProfilesChannelEndpointAssignmentList( + self._version, + self._solution["sid"], + ) + ) + return self._customer_profiles_channel_endpoint_assignment + + @property + def customer_profiles_entity_assignments( + self, + ) -> CustomerProfilesEntityAssignmentsList: + """ + Access the customer_profiles_entity_assignments + """ + if self._customer_profiles_entity_assignments is None: + self._customer_profiles_entity_assignments = ( + CustomerProfilesEntityAssignmentsList( + self._version, + self._solution["sid"], + ) + ) + return self._customer_profiles_entity_assignments + + @property + def customer_profiles_evaluations(self) -> CustomerProfilesEvaluationsList: + """ + Access the customer_profiles_evaluations + """ + if self._customer_profiles_evaluations is None: + self._customer_profiles_evaluations = CustomerProfilesEvaluationsList( + self._version, + self._solution["sid"], + ) + return self._customer_profiles_evaluations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.CustomerProfilesContext {}>".format(context) + + +class CustomerProfilesPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CustomerProfilesInstance: + """ + Build an instance of CustomerProfilesInstance + + :param payload: Payload response from the API + """ + return CustomerProfilesInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.CustomerProfilesPage>" + + +class CustomerProfilesList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CustomerProfilesList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/CustomerProfiles" + + def create( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> CustomerProfilesInstance: + """ + Create the CustomerProfilesInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + :param policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param status_callback: The URL we call to inform your application of status changes. + + :returns: The created CustomerProfilesInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Email": email, + "PolicySid": policy_sid, + "StatusCallback": status_callback, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomerProfilesInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> CustomerProfilesInstance: + """ + Asynchronously create the CustomerProfilesInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Customer-Profile resource changes status. + :param policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param status_callback: The URL we call to inform your application of status changes. + + :returns: The created CustomerProfilesInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Email": email, + "PolicySid": policy_sid, + "StatusCallback": status_callback, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomerProfilesInstance(self._version, payload) + + def stream( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CustomerProfilesInstance]: + """ + Streams CustomerProfilesInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "CustomerProfilesInstance.Status" status: The verification status of the Customer-Profile resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CustomerProfilesInstance]: + """ + Asynchronously streams CustomerProfilesInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "CustomerProfilesInstance.Status" status: The verification status of the Customer-Profile resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomerProfilesInstance]: + """ + Lists CustomerProfilesInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "CustomerProfilesInstance.Status" status: The verification status of the Customer-Profile resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomerProfilesInstance]: + """ + Asynchronously lists CustomerProfilesInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "CustomerProfilesInstance.Status" status: The verification status of the Customer-Profile resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CustomerProfilesPage: + """ + Retrieve a single page of CustomerProfilesInstance records from the API. + Request is executed immediately + + :param status: The verification status of the Customer-Profile resource. + :param friendly_name: The string that you assigned to describe the resource. + :param policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CustomerProfilesInstance + """ + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "PolicySid": policy_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomerProfilesPage(self._version, response) + + async def page_async( + self, + status: Union["CustomerProfilesInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CustomerProfilesPage: + """ + Asynchronously retrieve a single page of CustomerProfilesInstance records from the API. + Request is executed immediately + + :param status: The verification status of the Customer-Profile resource. + :param friendly_name: The string that you assigned to describe the resource. + :param policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CustomerProfilesInstance + """ + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "PolicySid": policy_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomerProfilesPage(self._version, response) + + def get_page(self, target_url: str) -> CustomerProfilesPage: + """ + Retrieve a specific page of CustomerProfilesInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomerProfilesInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CustomerProfilesPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CustomerProfilesPage: + """ + Asynchronously retrieve a specific page of CustomerProfilesInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomerProfilesInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CustomerProfilesPage(self._version, response) + + def get(self, sid: str) -> CustomerProfilesContext: + """ + Constructs a CustomerProfilesContext + + :param sid: The unique string that we created to identify the Customer-Profile resource. + """ + return CustomerProfilesContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CustomerProfilesContext: + """ + Constructs a CustomerProfilesContext + + :param sid: The unique string that we created to identify the Customer-Profile resource. + """ + return CustomerProfilesContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.CustomerProfilesList>" diff --git a/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_channel_endpoint_assignment.py b/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_channel_endpoint_assignment.py new file mode 100644 index 0000000000..1adca541a8 --- /dev/null +++ b/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_channel_endpoint_assignment.py @@ -0,0 +1,616 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CustomerProfilesChannelEndpointAssignmentInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Item Assignment resource. + :ivar customer_profile_sid: The unique string that we created to identify the CustomerProfile resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Item Assignment resource. + :ivar channel_endpoint_type: The type of channel endpoint. eg: phone-number + :ivar channel_endpoint_sid: The SID of an channel endpoint + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Identity resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + customer_profile_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.customer_profile_sid: Optional[str] = payload.get("customer_profile_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_endpoint_type: Optional[str] = payload.get("channel_endpoint_type") + self.channel_endpoint_sid: Optional[str] = payload.get("channel_endpoint_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "customer_profile_sid": customer_profile_sid, + "sid": sid or self.sid, + } + self._context: Optional[CustomerProfilesChannelEndpointAssignmentContext] = None + + @property + def _proxy(self) -> "CustomerProfilesChannelEndpointAssignmentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CustomerProfilesChannelEndpointAssignmentContext for this CustomerProfilesChannelEndpointAssignmentInstance + """ + if self._context is None: + self._context = CustomerProfilesChannelEndpointAssignmentContext( + self._version, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CustomerProfilesChannelEndpointAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CustomerProfilesChannelEndpointAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CustomerProfilesChannelEndpointAssignmentInstance": + """ + Fetch the CustomerProfilesChannelEndpointAssignmentInstance + + + :returns: The fetched CustomerProfilesChannelEndpointAssignmentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CustomerProfilesChannelEndpointAssignmentInstance": + """ + Asynchronous coroutine to fetch the CustomerProfilesChannelEndpointAssignmentInstance + + + :returns: The fetched CustomerProfilesChannelEndpointAssignmentInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.CustomerProfilesChannelEndpointAssignmentInstance {}>".format( + context + ) + + +class CustomerProfilesChannelEndpointAssignmentContext(InstanceContext): + + def __init__(self, version: Version, customer_profile_sid: str, sid: str): + """ + Initialize the CustomerProfilesChannelEndpointAssignmentContext + + :param version: Version that contains the resource + :param customer_profile_sid: The unique string that we created to identify the CustomerProfile resource. + :param sid: The unique string that we created to identify the resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "customer_profile_sid": customer_profile_sid, + "sid": sid, + } + self._uri = "/CustomerProfiles/{customer_profile_sid}/ChannelEndpointAssignments/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the CustomerProfilesChannelEndpointAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CustomerProfilesChannelEndpointAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CustomerProfilesChannelEndpointAssignmentInstance: + """ + Fetch the CustomerProfilesChannelEndpointAssignmentInstance + + + :returns: The fetched CustomerProfilesChannelEndpointAssignmentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CustomerProfilesChannelEndpointAssignmentInstance: + """ + Asynchronous coroutine to fetch the CustomerProfilesChannelEndpointAssignmentInstance + + + :returns: The fetched CustomerProfilesChannelEndpointAssignmentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.CustomerProfilesChannelEndpointAssignmentContext {}>".format( + context + ) + + +class CustomerProfilesChannelEndpointAssignmentPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> CustomerProfilesChannelEndpointAssignmentInstance: + """ + Build an instance of CustomerProfilesChannelEndpointAssignmentInstance + + :param payload: Payload response from the API + """ + return CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.CustomerProfilesChannelEndpointAssignmentPage>" + + +class CustomerProfilesChannelEndpointAssignmentList(ListResource): + + def __init__(self, version: Version, customer_profile_sid: str): + """ + Initialize the CustomerProfilesChannelEndpointAssignmentList + + :param version: Version that contains the resource + :param customer_profile_sid: The unique string that we created to identify the CustomerProfile resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "customer_profile_sid": customer_profile_sid, + } + self._uri = "/CustomerProfiles/{customer_profile_sid}/ChannelEndpointAssignments".format( + **self._solution + ) + + def create( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> CustomerProfilesChannelEndpointAssignmentInstance: + """ + Create the CustomerProfilesChannelEndpointAssignmentInstance + + :param channel_endpoint_type: The type of channel endpoint. eg: phone-number + :param channel_endpoint_sid: The SID of an channel endpoint + + :returns: The created CustomerProfilesChannelEndpointAssignmentInstance + """ + + data = values.of( + { + "ChannelEndpointType": channel_endpoint_type, + "ChannelEndpointSid": channel_endpoint_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + async def create_async( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> CustomerProfilesChannelEndpointAssignmentInstance: + """ + Asynchronously create the CustomerProfilesChannelEndpointAssignmentInstance + + :param channel_endpoint_type: The type of channel endpoint. eg: phone-number + :param channel_endpoint_sid: The SID of an channel endpoint + + :returns: The created CustomerProfilesChannelEndpointAssignmentInstance + """ + + data = values.of( + { + "ChannelEndpointType": channel_endpoint_type, + "ChannelEndpointSid": channel_endpoint_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + def stream( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CustomerProfilesChannelEndpointAssignmentInstance]: + """ + Streams CustomerProfilesChannelEndpointAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CustomerProfilesChannelEndpointAssignmentInstance]: + """ + Asynchronously streams CustomerProfilesChannelEndpointAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomerProfilesChannelEndpointAssignmentInstance]: + """ + Lists CustomerProfilesChannelEndpointAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomerProfilesChannelEndpointAssignmentInstance]: + """ + Asynchronously lists CustomerProfilesChannelEndpointAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CustomerProfilesChannelEndpointAssignmentPage: + """ + Retrieve a single page of CustomerProfilesChannelEndpointAssignmentInstance records from the API. + Request is executed immediately + + :param channel_endpoint_sid: The SID of an channel endpoint + :param channel_endpoint_sids: comma separated list of channel endpoint sids + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CustomerProfilesChannelEndpointAssignmentInstance + """ + data = values.of( + { + "ChannelEndpointSid": channel_endpoint_sid, + "ChannelEndpointSids": channel_endpoint_sids, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomerProfilesChannelEndpointAssignmentPage( + self._version, response, self._solution + ) + + async def page_async( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CustomerProfilesChannelEndpointAssignmentPage: + """ + Asynchronously retrieve a single page of CustomerProfilesChannelEndpointAssignmentInstance records from the API. + Request is executed immediately + + :param channel_endpoint_sid: The SID of an channel endpoint + :param channel_endpoint_sids: comma separated list of channel endpoint sids + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CustomerProfilesChannelEndpointAssignmentInstance + """ + data = values.of( + { + "ChannelEndpointSid": channel_endpoint_sid, + "ChannelEndpointSids": channel_endpoint_sids, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomerProfilesChannelEndpointAssignmentPage( + self._version, response, self._solution + ) + + def get_page( + self, target_url: str + ) -> CustomerProfilesChannelEndpointAssignmentPage: + """ + Retrieve a specific page of CustomerProfilesChannelEndpointAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomerProfilesChannelEndpointAssignmentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CustomerProfilesChannelEndpointAssignmentPage( + self._version, response, self._solution + ) + + async def get_page_async( + self, target_url: str + ) -> CustomerProfilesChannelEndpointAssignmentPage: + """ + Asynchronously retrieve a specific page of CustomerProfilesChannelEndpointAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomerProfilesChannelEndpointAssignmentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CustomerProfilesChannelEndpointAssignmentPage( + self._version, response, self._solution + ) + + def get(self, sid: str) -> CustomerProfilesChannelEndpointAssignmentContext: + """ + Constructs a CustomerProfilesChannelEndpointAssignmentContext + + :param sid: The unique string that we created to identify the resource. + """ + return CustomerProfilesChannelEndpointAssignmentContext( + self._version, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> CustomerProfilesChannelEndpointAssignmentContext: + """ + Constructs a CustomerProfilesChannelEndpointAssignmentContext + + :param sid: The unique string that we created to identify the resource. + """ + return CustomerProfilesChannelEndpointAssignmentContext( + self._version, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.CustomerProfilesChannelEndpointAssignmentList>" diff --git a/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_entity_assignments.py b/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_entity_assignments.py new file mode 100644 index 0000000000..f8710b9cd8 --- /dev/null +++ b/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_entity_assignments.py @@ -0,0 +1,590 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CustomerProfilesEntityAssignmentsInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Item Assignment resource. + :ivar customer_profile_sid: The unique string that we created to identify the CustomerProfile resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Item Assignment resource. + :ivar object_sid: The SID of an object bag that holds information of the different items. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Identity resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + customer_profile_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.customer_profile_sid: Optional[str] = payload.get("customer_profile_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.object_sid: Optional[str] = payload.get("object_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "customer_profile_sid": customer_profile_sid, + "sid": sid or self.sid, + } + self._context: Optional[CustomerProfilesEntityAssignmentsContext] = None + + @property + def _proxy(self) -> "CustomerProfilesEntityAssignmentsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CustomerProfilesEntityAssignmentsContext for this CustomerProfilesEntityAssignmentsInstance + """ + if self._context is None: + self._context = CustomerProfilesEntityAssignmentsContext( + self._version, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CustomerProfilesEntityAssignmentsInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CustomerProfilesEntityAssignmentsInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CustomerProfilesEntityAssignmentsInstance": + """ + Fetch the CustomerProfilesEntityAssignmentsInstance + + + :returns: The fetched CustomerProfilesEntityAssignmentsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CustomerProfilesEntityAssignmentsInstance": + """ + Asynchronous coroutine to fetch the CustomerProfilesEntityAssignmentsInstance + + + :returns: The fetched CustomerProfilesEntityAssignmentsInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return ( + "<Twilio.Trusthub.V1.CustomerProfilesEntityAssignmentsInstance {}>".format( + context + ) + ) + + +class CustomerProfilesEntityAssignmentsContext(InstanceContext): + + def __init__(self, version: Version, customer_profile_sid: str, sid: str): + """ + Initialize the CustomerProfilesEntityAssignmentsContext + + :param version: Version that contains the resource + :param customer_profile_sid: The unique string that we created to identify the CustomerProfile resource. + :param sid: The unique string that we created to identify the Identity resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "customer_profile_sid": customer_profile_sid, + "sid": sid, + } + self._uri = ( + "/CustomerProfiles/{customer_profile_sid}/EntityAssignments/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the CustomerProfilesEntityAssignmentsInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CustomerProfilesEntityAssignmentsInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CustomerProfilesEntityAssignmentsInstance: + """ + Fetch the CustomerProfilesEntityAssignmentsInstance + + + :returns: The fetched CustomerProfilesEntityAssignmentsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CustomerProfilesEntityAssignmentsInstance: + """ + Asynchronous coroutine to fetch the CustomerProfilesEntityAssignmentsInstance + + + :returns: The fetched CustomerProfilesEntityAssignmentsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return ( + "<Twilio.Trusthub.V1.CustomerProfilesEntityAssignmentsContext {}>".format( + context + ) + ) + + +class CustomerProfilesEntityAssignmentsPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> CustomerProfilesEntityAssignmentsInstance: + """ + Build an instance of CustomerProfilesEntityAssignmentsInstance + + :param payload: Payload response from the API + """ + return CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.CustomerProfilesEntityAssignmentsPage>" + + +class CustomerProfilesEntityAssignmentsList(ListResource): + + def __init__(self, version: Version, customer_profile_sid: str): + """ + Initialize the CustomerProfilesEntityAssignmentsList + + :param version: Version that contains the resource + :param customer_profile_sid: The unique string that we created to identify the CustomerProfile resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "customer_profile_sid": customer_profile_sid, + } + self._uri = "/CustomerProfiles/{customer_profile_sid}/EntityAssignments".format( + **self._solution + ) + + def create(self, object_sid: str) -> CustomerProfilesEntityAssignmentsInstance: + """ + Create the CustomerProfilesEntityAssignmentsInstance + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created CustomerProfilesEntityAssignmentsInstance + """ + + data = values.of( + { + "ObjectSid": object_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + async def create_async( + self, object_sid: str + ) -> CustomerProfilesEntityAssignmentsInstance: + """ + Asynchronously create the CustomerProfilesEntityAssignmentsInstance + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created CustomerProfilesEntityAssignmentsInstance + """ + + data = values.of( + { + "ObjectSid": object_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + def stream( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CustomerProfilesEntityAssignmentsInstance]: + """ + Streams CustomerProfilesEntityAssignmentsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(object_type=object_type, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CustomerProfilesEntityAssignmentsInstance]: + """ + Asynchronously streams CustomerProfilesEntityAssignmentsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + object_type=object_type, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomerProfilesEntityAssignmentsInstance]: + """ + Lists CustomerProfilesEntityAssignmentsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + object_type=object_type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomerProfilesEntityAssignmentsInstance]: + """ + Asynchronously lists CustomerProfilesEntityAssignmentsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + object_type=object_type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + object_type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CustomerProfilesEntityAssignmentsPage: + """ + Retrieve a single page of CustomerProfilesEntityAssignmentsInstance records from the API. + Request is executed immediately + + :param object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CustomerProfilesEntityAssignmentsInstance + """ + data = values.of( + { + "ObjectType": object_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomerProfilesEntityAssignmentsPage( + self._version, response, self._solution + ) + + async def page_async( + self, + object_type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CustomerProfilesEntityAssignmentsPage: + """ + Asynchronously retrieve a single page of CustomerProfilesEntityAssignmentsInstance records from the API. + Request is executed immediately + + :param object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CustomerProfilesEntityAssignmentsInstance + """ + data = values.of( + { + "ObjectType": object_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomerProfilesEntityAssignmentsPage( + self._version, response, self._solution + ) + + def get_page(self, target_url: str) -> CustomerProfilesEntityAssignmentsPage: + """ + Retrieve a specific page of CustomerProfilesEntityAssignmentsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomerProfilesEntityAssignmentsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CustomerProfilesEntityAssignmentsPage( + self._version, response, self._solution + ) + + async def get_page_async( + self, target_url: str + ) -> CustomerProfilesEntityAssignmentsPage: + """ + Asynchronously retrieve a specific page of CustomerProfilesEntityAssignmentsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomerProfilesEntityAssignmentsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CustomerProfilesEntityAssignmentsPage( + self._version, response, self._solution + ) + + def get(self, sid: str) -> CustomerProfilesEntityAssignmentsContext: + """ + Constructs a CustomerProfilesEntityAssignmentsContext + + :param sid: The unique string that we created to identify the Identity resource. + """ + return CustomerProfilesEntityAssignmentsContext( + self._version, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> CustomerProfilesEntityAssignmentsContext: + """ + Constructs a CustomerProfilesEntityAssignmentsContext + + :param sid: The unique string that we created to identify the Identity resource. + """ + return CustomerProfilesEntityAssignmentsContext( + self._version, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.CustomerProfilesEntityAssignmentsList>" diff --git a/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_evaluations.py b/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_evaluations.py new file mode 100644 index 0000000000..648467aac6 --- /dev/null +++ b/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_evaluations.py @@ -0,0 +1,523 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CustomerProfilesEvaluationsInstance(InstanceResource): + + class Status(object): + COMPLIANT = "compliant" + NONCOMPLIANT = "noncompliant" + + """ + :ivar sid: The unique string that identifies the Evaluation resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the customer_profile resource. + :ivar policy_sid: The unique string of a policy that is associated to the customer_profile resource. + :ivar customer_profile_sid: The unique string that we created to identify the customer_profile resource. + :ivar status: + :ivar results: The results of the Evaluation which includes the valid and invalid attributes. + :ivar date_created: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + customer_profile_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.policy_sid: Optional[str] = payload.get("policy_sid") + self.customer_profile_sid: Optional[str] = payload.get("customer_profile_sid") + self.status: Optional["CustomerProfilesEvaluationsInstance.Status"] = ( + payload.get("status") + ) + self.results: Optional[List[Dict[str, object]]] = payload.get("results") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "customer_profile_sid": customer_profile_sid, + "sid": sid or self.sid, + } + self._context: Optional[CustomerProfilesEvaluationsContext] = None + + @property + def _proxy(self) -> "CustomerProfilesEvaluationsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CustomerProfilesEvaluationsContext for this CustomerProfilesEvaluationsInstance + """ + if self._context is None: + self._context = CustomerProfilesEvaluationsContext( + self._version, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "CustomerProfilesEvaluationsInstance": + """ + Fetch the CustomerProfilesEvaluationsInstance + + + :returns: The fetched CustomerProfilesEvaluationsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CustomerProfilesEvaluationsInstance": + """ + Asynchronous coroutine to fetch the CustomerProfilesEvaluationsInstance + + + :returns: The fetched CustomerProfilesEvaluationsInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.CustomerProfilesEvaluationsInstance {}>".format( + context + ) + + +class CustomerProfilesEvaluationsContext(InstanceContext): + + def __init__(self, version: Version, customer_profile_sid: str, sid: str): + """ + Initialize the CustomerProfilesEvaluationsContext + + :param version: Version that contains the resource + :param customer_profile_sid: The unique string that we created to identify the customer_profile resource. + :param sid: The unique string that identifies the Evaluation resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "customer_profile_sid": customer_profile_sid, + "sid": sid, + } + self._uri = "/CustomerProfiles/{customer_profile_sid}/Evaluations/{sid}".format( + **self._solution + ) + + def fetch(self) -> CustomerProfilesEvaluationsInstance: + """ + Fetch the CustomerProfilesEvaluationsInstance + + + :returns: The fetched CustomerProfilesEvaluationsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CustomerProfilesEvaluationsInstance: + """ + Asynchronous coroutine to fetch the CustomerProfilesEvaluationsInstance + + + :returns: The fetched CustomerProfilesEvaluationsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.CustomerProfilesEvaluationsContext {}>".format( + context + ) + + +class CustomerProfilesEvaluationsPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> CustomerProfilesEvaluationsInstance: + """ + Build an instance of CustomerProfilesEvaluationsInstance + + :param payload: Payload response from the API + """ + return CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.CustomerProfilesEvaluationsPage>" + + +class CustomerProfilesEvaluationsList(ListResource): + + def __init__(self, version: Version, customer_profile_sid: str): + """ + Initialize the CustomerProfilesEvaluationsList + + :param version: Version that contains the resource + :param customer_profile_sid: The unique string that we created to identify the CustomerProfile resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "customer_profile_sid": customer_profile_sid, + } + self._uri = "/CustomerProfiles/{customer_profile_sid}/Evaluations".format( + **self._solution + ) + + def create(self, policy_sid: str) -> CustomerProfilesEvaluationsInstance: + """ + Create the CustomerProfilesEvaluationsInstance + + :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. + + :returns: The created CustomerProfilesEvaluationsInstance + """ + + data = values.of( + { + "PolicySid": policy_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + async def create_async( + self, policy_sid: str + ) -> CustomerProfilesEvaluationsInstance: + """ + Asynchronously create the CustomerProfilesEvaluationsInstance + + :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. + + :returns: The created CustomerProfilesEvaluationsInstance + """ + + data = values.of( + { + "PolicySid": policy_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CustomerProfilesEvaluationsInstance]: + """ + Streams CustomerProfilesEvaluationsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CustomerProfilesEvaluationsInstance]: + """ + Asynchronously streams CustomerProfilesEvaluationsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomerProfilesEvaluationsInstance]: + """ + Lists CustomerProfilesEvaluationsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomerProfilesEvaluationsInstance]: + """ + Asynchronously lists CustomerProfilesEvaluationsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CustomerProfilesEvaluationsPage: + """ + Retrieve a single page of CustomerProfilesEvaluationsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CustomerProfilesEvaluationsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomerProfilesEvaluationsPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CustomerProfilesEvaluationsPage: + """ + Asynchronously retrieve a single page of CustomerProfilesEvaluationsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CustomerProfilesEvaluationsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomerProfilesEvaluationsPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> CustomerProfilesEvaluationsPage: + """ + Retrieve a specific page of CustomerProfilesEvaluationsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomerProfilesEvaluationsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CustomerProfilesEvaluationsPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> CustomerProfilesEvaluationsPage: + """ + Asynchronously retrieve a specific page of CustomerProfilesEvaluationsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomerProfilesEvaluationsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CustomerProfilesEvaluationsPage(self._version, response, self._solution) + + def get(self, sid: str) -> CustomerProfilesEvaluationsContext: + """ + Constructs a CustomerProfilesEvaluationsContext + + :param sid: The unique string that identifies the Evaluation resource. + """ + return CustomerProfilesEvaluationsContext( + self._version, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> CustomerProfilesEvaluationsContext: + """ + Constructs a CustomerProfilesEvaluationsContext + + :param sid: The unique string that identifies the Evaluation resource. + """ + return CustomerProfilesEvaluationsContext( + self._version, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.CustomerProfilesEvaluationsList>" diff --git a/twilio/rest/trusthub/v1/end_user.py b/twilio/rest/trusthub/v1/end_user.py new file mode 100644 index 0000000000..5ce3b819d9 --- /dev/null +++ b/twilio/rest/trusthub/v1/end_user.py @@ -0,0 +1,633 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EndUserInstance(InstanceResource): + """ + :ivar sid: The unique string created by Twilio to identify the End User resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the End User resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar type: The type of end user of the Bundle resource - can be `individual` or `business`. + :ivar attributes: The set of parameters that are the attributes of the End Users resource which are listed in the End User Types. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the End User resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.type: Optional[str] = payload.get("type") + self.attributes: Optional[Dict[str, object]] = payload.get("attributes") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[EndUserContext] = None + + @property + def _proxy(self) -> "EndUserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EndUserContext for this EndUserInstance + """ + if self._context is None: + self._context = EndUserContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the EndUserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EndUserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "EndUserInstance": + """ + Fetch the EndUserInstance + + + :returns: The fetched EndUserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EndUserInstance": + """ + Asynchronous coroutine to fetch the EndUserInstance + + + :returns: The fetched EndUserInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "EndUserInstance": + """ + Update the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The updated EndUserInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + attributes=attributes, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "EndUserInstance": + """ + Asynchronous coroutine to update the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The updated EndUserInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + attributes=attributes, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.EndUserInstance {}>".format(context) + + +class EndUserContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the EndUserContext + + :param version: Version that contains the resource + :param sid: The unique string created by Twilio to identify the End User resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/EndUsers/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the EndUserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EndUserInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> EndUserInstance: + """ + Fetch the EndUserInstance + + + :returns: The fetched EndUserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EndUserInstance: + """ + Asynchronous coroutine to fetch the EndUserInstance + + + :returns: The fetched EndUserInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Update the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The updated EndUserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EndUserInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Asynchronous coroutine to update the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The updated EndUserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EndUserInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.EndUserContext {}>".format(context) + + +class EndUserPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EndUserInstance: + """ + Build an instance of EndUserInstance + + :param payload: Payload response from the API + """ + return EndUserInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.EndUserPage>" + + +class EndUserList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the EndUserList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/EndUsers" + + def create( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Create the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of end user of the Bundle resource - can be `individual` or `business`. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The created EndUserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EndUserInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> EndUserInstance: + """ + Asynchronously create the EndUserInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of end user of the Bundle resource - can be `individual` or `business`. + :param attributes: The set of parameters that are the attributes of the End User resource which are derived End User Types. + + :returns: The created EndUserInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EndUserInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EndUserInstance]: + """ + Streams EndUserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EndUserInstance]: + """ + Asynchronously streams EndUserInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EndUserInstance]: + """ + Lists EndUserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EndUserInstance]: + """ + Asynchronously lists EndUserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EndUserPage: + """ + Retrieve a single page of EndUserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EndUserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EndUserPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EndUserPage: + """ + Asynchronously retrieve a single page of EndUserInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EndUserInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EndUserPage(self._version, response) + + def get_page(self, target_url: str) -> EndUserPage: + """ + Retrieve a specific page of EndUserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EndUserInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EndUserPage(self._version, response) + + async def get_page_async(self, target_url: str) -> EndUserPage: + """ + Asynchronously retrieve a specific page of EndUserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EndUserInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EndUserPage(self._version, response) + + def get(self, sid: str) -> EndUserContext: + """ + Constructs a EndUserContext + + :param sid: The unique string created by Twilio to identify the End User resource. + """ + return EndUserContext(self._version, sid=sid) + + def __call__(self, sid: str) -> EndUserContext: + """ + Constructs a EndUserContext + + :param sid: The unique string created by Twilio to identify the End User resource. + """ + return EndUserContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.EndUserList>" diff --git a/twilio/rest/trusthub/v1/end_user_type.py b/twilio/rest/trusthub/v1/end_user_type.py new file mode 100644 index 0000000000..0eb2957e0a --- /dev/null +++ b/twilio/rest/trusthub/v1/end_user_type.py @@ -0,0 +1,408 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class EndUserTypeInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies the End-User Type resource. + :ivar friendly_name: A human-readable description that is assigned to describe the End-User Type resource. Examples can include first name, last name, email, business name, etc + :ivar machine_name: A machine-readable description of the End-User Type resource. Examples can include first_name, last_name, email, business_name, etc. + :ivar fields: The required information for creating an End-User. The required fields will change as regulatory needs change and will differ for businesses and individuals. + :ivar url: The absolute URL of the End-User Type resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.machine_name: Optional[str] = payload.get("machine_name") + self.fields: Optional[List[Dict[str, object]]] = payload.get("fields") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[EndUserTypeContext] = None + + @property + def _proxy(self) -> "EndUserTypeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EndUserTypeContext for this EndUserTypeInstance + """ + if self._context is None: + self._context = EndUserTypeContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "EndUserTypeInstance": + """ + Fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EndUserTypeInstance": + """ + Asynchronous coroutine to fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.EndUserTypeInstance {}>".format(context) + + +class EndUserTypeContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the EndUserTypeContext + + :param version: Version that contains the resource + :param sid: The unique string that identifies the End-User Type resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/EndUserTypes/{sid}".format(**self._solution) + + def fetch(self) -> EndUserTypeInstance: + """ + Fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> EndUserTypeInstance: + """ + Asynchronous coroutine to fetch the EndUserTypeInstance + + + :returns: The fetched EndUserTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.EndUserTypeContext {}>".format(context) + + +class EndUserTypePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EndUserTypeInstance: + """ + Build an instance of EndUserTypeInstance + + :param payload: Payload response from the API + """ + return EndUserTypeInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.EndUserTypePage>" + + +class EndUserTypeList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the EndUserTypeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/EndUserTypes" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EndUserTypeInstance]: + """ + Streams EndUserTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EndUserTypeInstance]: + """ + Asynchronously streams EndUserTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EndUserTypeInstance]: + """ + Lists EndUserTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EndUserTypeInstance]: + """ + Asynchronously lists EndUserTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EndUserTypePage: + """ + Retrieve a single page of EndUserTypeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EndUserTypeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EndUserTypePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EndUserTypePage: + """ + Asynchronously retrieve a single page of EndUserTypeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EndUserTypeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EndUserTypePage(self._version, response) + + def get_page(self, target_url: str) -> EndUserTypePage: + """ + Retrieve a specific page of EndUserTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EndUserTypeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EndUserTypePage(self._version, response) + + async def get_page_async(self, target_url: str) -> EndUserTypePage: + """ + Asynchronously retrieve a specific page of EndUserTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EndUserTypeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EndUserTypePage(self._version, response) + + def get(self, sid: str) -> EndUserTypeContext: + """ + Constructs a EndUserTypeContext + + :param sid: The unique string that identifies the End-User Type resource. + """ + return EndUserTypeContext(self._version, sid=sid) + + def __call__(self, sid: str) -> EndUserTypeContext: + """ + Constructs a EndUserTypeContext + + :param sid: The unique string that identifies the End-User Type resource. + """ + return EndUserTypeContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.EndUserTypeList>" diff --git a/twilio/rest/trusthub/v1/policies.py b/twilio/rest/trusthub/v1/policies.py new file mode 100644 index 0000000000..36a0916c51 --- /dev/null +++ b/twilio/rest/trusthub/v1/policies.py @@ -0,0 +1,406 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PoliciesInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies the Policy resource. + :ivar friendly_name: A human-readable description that is assigned to describe the Policy resource. Examples can include Primary Customer profile policy + :ivar requirements: The SID of an object that holds the policy information + :ivar url: The absolute URL of the Policy resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.requirements: Optional[Dict[str, object]] = payload.get("requirements") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[PoliciesContext] = None + + @property + def _proxy(self) -> "PoliciesContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PoliciesContext for this PoliciesInstance + """ + if self._context is None: + self._context = PoliciesContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "PoliciesInstance": + """ + Fetch the PoliciesInstance + + + :returns: The fetched PoliciesInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PoliciesInstance": + """ + Asynchronous coroutine to fetch the PoliciesInstance + + + :returns: The fetched PoliciesInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.PoliciesInstance {}>".format(context) + + +class PoliciesContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PoliciesContext + + :param version: Version that contains the resource + :param sid: The unique string that identifies the Policy resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Policies/{sid}".format(**self._solution) + + def fetch(self) -> PoliciesInstance: + """ + Fetch the PoliciesInstance + + + :returns: The fetched PoliciesInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PoliciesInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> PoliciesInstance: + """ + Asynchronous coroutine to fetch the PoliciesInstance + + + :returns: The fetched PoliciesInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PoliciesInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.PoliciesContext {}>".format(context) + + +class PoliciesPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PoliciesInstance: + """ + Build an instance of PoliciesInstance + + :param payload: Payload response from the API + """ + return PoliciesInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.PoliciesPage>" + + +class PoliciesList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PoliciesList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Policies" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PoliciesInstance]: + """ + Streams PoliciesInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PoliciesInstance]: + """ + Asynchronously streams PoliciesInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PoliciesInstance]: + """ + Lists PoliciesInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PoliciesInstance]: + """ + Asynchronously lists PoliciesInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PoliciesPage: + """ + Retrieve a single page of PoliciesInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PoliciesInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PoliciesPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PoliciesPage: + """ + Asynchronously retrieve a single page of PoliciesInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PoliciesInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PoliciesPage(self._version, response) + + def get_page(self, target_url: str) -> PoliciesPage: + """ + Retrieve a specific page of PoliciesInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PoliciesInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PoliciesPage(self._version, response) + + async def get_page_async(self, target_url: str) -> PoliciesPage: + """ + Asynchronously retrieve a specific page of PoliciesInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PoliciesInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PoliciesPage(self._version, response) + + def get(self, sid: str) -> PoliciesContext: + """ + Constructs a PoliciesContext + + :param sid: The unique string that identifies the Policy resource. + """ + return PoliciesContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PoliciesContext: + """ + Constructs a PoliciesContext + + :param sid: The unique string that identifies the Policy resource. + """ + return PoliciesContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.PoliciesList>" diff --git a/twilio/rest/trusthub/v1/supporting_document.py b/twilio/rest/trusthub/v1/supporting_document.py new file mode 100644 index 0000000000..f2fd3b7e1c --- /dev/null +++ b/twilio/rest/trusthub/v1/supporting_document.py @@ -0,0 +1,652 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SupportingDocumentInstance(InstanceResource): + + class Status(object): + DRAFT = "DRAFT" + PENDING_REVIEW = "PENDING_REVIEW" + REJECTED = "REJECTED" + APPROVED = "APPROVED" + EXPIRED = "EXPIRED" + PROVISIONALLY_APPROVED = "PROVISIONALLY_APPROVED" + + """ + :ivar sid: The unique string created by Twilio to identify the Supporting Document resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Document resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar mime_type: The image type uploaded in the Supporting Document container. + :ivar status: + :ivar type: The type of the Supporting Document. + :ivar attributes: The set of parameters that are the attributes of the Supporting Documents resource which are listed in the Supporting Document Types. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Supporting Document resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.mime_type: Optional[str] = payload.get("mime_type") + self.status: Optional["SupportingDocumentInstance.Status"] = payload.get( + "status" + ) + self.type: Optional[str] = payload.get("type") + self.attributes: Optional[Dict[str, object]] = payload.get("attributes") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SupportingDocumentContext] = None + + @property + def _proxy(self) -> "SupportingDocumentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SupportingDocumentContext for this SupportingDocumentInstance + """ + if self._context is None: + self._context = SupportingDocumentContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SupportingDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SupportingDocumentInstance": + """ + Fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SupportingDocumentInstance": + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "SupportingDocumentInstance": + """ + Update the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: The updated SupportingDocumentInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + attributes=attributes, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> "SupportingDocumentInstance": + """ + Asynchronous coroutine to update the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: The updated SupportingDocumentInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + attributes=attributes, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.SupportingDocumentInstance {}>".format(context) + + +class SupportingDocumentContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SupportingDocumentContext + + :param version: Version that contains the resource + :param sid: The unique string created by Twilio to identify the Supporting Document resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/SupportingDocuments/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the SupportingDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SupportingDocumentInstance: + """ + Fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SupportingDocumentInstance: + """ + Asynchronous coroutine to fetch the SupportingDocumentInstance + + + :returns: The fetched SupportingDocumentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Update the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: The updated SupportingDocumentInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Asynchronous coroutine to update the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param attributes: The set of parameters that are the attributes of the Supporting Document resource which are derived Supporting Document Types. + + :returns: The updated SupportingDocumentInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.SupportingDocumentContext {}>".format(context) + + +class SupportingDocumentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentInstance: + """ + Build an instance of SupportingDocumentInstance + + :param payload: Payload response from the API + """ + return SupportingDocumentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.SupportingDocumentPage>" + + +class SupportingDocumentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SupportingDocumentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SupportingDocuments" + + def create( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Create the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of the Supporting Document. + :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. + + :returns: The created SupportingDocumentInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SupportingDocumentInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> SupportingDocumentInstance: + """ + Asynchronously create the SupportingDocumentInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param type: The type of the Supporting Document. + :param attributes: The set of parameters that are the attributes of the Supporting Documents resource which are derived Supporting Document Types. + + :returns: The created SupportingDocumentInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Attributes": serialize.object(attributes), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SupportingDocumentInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SupportingDocumentInstance]: + """ + Streams SupportingDocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SupportingDocumentInstance]: + """ + Asynchronously streams SupportingDocumentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentInstance]: + """ + Lists SupportingDocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentInstance]: + """ + Asynchronously lists SupportingDocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SupportingDocumentPage: + """ + Retrieve a single page of SupportingDocumentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SupportingDocumentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SupportingDocumentPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SupportingDocumentPage: + """ + Asynchronously retrieve a single page of SupportingDocumentInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SupportingDocumentInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SupportingDocumentPage(self._version, response) + + def get_page(self, target_url: str) -> SupportingDocumentPage: + """ + Retrieve a specific page of SupportingDocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SupportingDocumentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SupportingDocumentPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SupportingDocumentPage: + """ + Asynchronously retrieve a specific page of SupportingDocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SupportingDocumentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SupportingDocumentPage(self._version, response) + + def get(self, sid: str) -> SupportingDocumentContext: + """ + Constructs a SupportingDocumentContext + + :param sid: The unique string created by Twilio to identify the Supporting Document resource. + """ + return SupportingDocumentContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SupportingDocumentContext: + """ + Constructs a SupportingDocumentContext + + :param sid: The unique string created by Twilio to identify the Supporting Document resource. + """ + return SupportingDocumentContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.SupportingDocumentList>" diff --git a/twilio/rest/trusthub/v1/supporting_document_type.py b/twilio/rest/trusthub/v1/supporting_document_type.py new file mode 100644 index 0000000000..f107397a4c --- /dev/null +++ b/twilio/rest/trusthub/v1/supporting_document_type.py @@ -0,0 +1,408 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SupportingDocumentTypeInstance(InstanceResource): + """ + :ivar sid: The unique string that identifies the Supporting Document Type resource. + :ivar friendly_name: A human-readable description of the Supporting Document Type resource. + :ivar machine_name: The machine-readable description of the Supporting Document Type resource. + :ivar fields: The required information for creating a Supporting Document. The required fields will change as regulatory needs change and will differ for businesses and individuals. + :ivar url: The absolute URL of the Supporting Document Type resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.machine_name: Optional[str] = payload.get("machine_name") + self.fields: Optional[List[Dict[str, object]]] = payload.get("fields") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SupportingDocumentTypeContext] = None + + @property + def _proxy(self) -> "SupportingDocumentTypeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SupportingDocumentTypeContext for this SupportingDocumentTypeInstance + """ + if self._context is None: + self._context = SupportingDocumentTypeContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "SupportingDocumentTypeInstance": + """ + Fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SupportingDocumentTypeInstance": + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.SupportingDocumentTypeInstance {}>".format(context) + + +class SupportingDocumentTypeContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SupportingDocumentTypeContext + + :param version: Version that contains the resource + :param sid: The unique string that identifies the Supporting Document Type resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/SupportingDocumentTypes/{sid}".format(**self._solution) + + def fetch(self) -> SupportingDocumentTypeInstance: + """ + Fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SupportingDocumentTypeInstance: + """ + Asynchronous coroutine to fetch the SupportingDocumentTypeInstance + + + :returns: The fetched SupportingDocumentTypeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.SupportingDocumentTypeContext {}>".format(context) + + +class SupportingDocumentTypePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentTypeInstance: + """ + Build an instance of SupportingDocumentTypeInstance + + :param payload: Payload response from the API + """ + return SupportingDocumentTypeInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.SupportingDocumentTypePage>" + + +class SupportingDocumentTypeList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SupportingDocumentTypeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SupportingDocumentTypes" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SupportingDocumentTypeInstance]: + """ + Streams SupportingDocumentTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SupportingDocumentTypeInstance]: + """ + Asynchronously streams SupportingDocumentTypeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentTypeInstance]: + """ + Lists SupportingDocumentTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SupportingDocumentTypeInstance]: + """ + Asynchronously lists SupportingDocumentTypeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SupportingDocumentTypePage: + """ + Retrieve a single page of SupportingDocumentTypeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SupportingDocumentTypeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SupportingDocumentTypePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SupportingDocumentTypePage: + """ + Asynchronously retrieve a single page of SupportingDocumentTypeInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SupportingDocumentTypeInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SupportingDocumentTypePage(self._version, response) + + def get_page(self, target_url: str) -> SupportingDocumentTypePage: + """ + Retrieve a specific page of SupportingDocumentTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SupportingDocumentTypeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SupportingDocumentTypePage(self._version, response) + + async def get_page_async(self, target_url: str) -> SupportingDocumentTypePage: + """ + Asynchronously retrieve a specific page of SupportingDocumentTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SupportingDocumentTypeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SupportingDocumentTypePage(self._version, response) + + def get(self, sid: str) -> SupportingDocumentTypeContext: + """ + Constructs a SupportingDocumentTypeContext + + :param sid: The unique string that identifies the Supporting Document Type resource. + """ + return SupportingDocumentTypeContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SupportingDocumentTypeContext: + """ + Constructs a SupportingDocumentTypeContext + + :param sid: The unique string that identifies the Supporting Document Type resource. + """ + return SupportingDocumentTypeContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.SupportingDocumentTypeList>" diff --git a/twilio/rest/trusthub/v1/trust_products/__init__.py b/twilio/rest/trusthub/v1/trust_products/__init__.py new file mode 100644 index 0000000000..6bb01d61dc --- /dev/null +++ b/twilio/rest/trusthub/v1/trust_products/__init__.py @@ -0,0 +1,823 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.trusthub.v1.trust_products.trust_products_channel_endpoint_assignment import ( + TrustProductsChannelEndpointAssignmentList, +) +from twilio.rest.trusthub.v1.trust_products.trust_products_entity_assignments import ( + TrustProductsEntityAssignmentsList, +) +from twilio.rest.trusthub.v1.trust_products.trust_products_evaluations import ( + TrustProductsEvaluationsList, +) + + +class TrustProductsInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PENDING_REVIEW = "pending-review" + IN_REVIEW = "in-review" + TWILIO_REJECTED = "twilio-rejected" + TWILIO_APPROVED = "twilio-approved" + + """ + :ivar sid: The unique string that we created to identify the Trust Product resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Trust Product resource. + :ivar policy_sid: The unique string of the policy that is associated with the Trust Product resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar status: + :ivar valid_until: The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format until which the resource will be valid. + :ivar email: The email address that will receive updates when the Trust Product resource changes status. + :ivar status_callback: The URL we call to inform your application of status changes. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Trust Product resource. + :ivar links: The URLs of the Assigned Items of the Trust Product resource. + :ivar errors: The error codes associated with the rejection of the Trust Product. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.policy_sid: Optional[str] = payload.get("policy_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["TrustProductsInstance.Status"] = payload.get("status") + self.valid_until: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("valid_until") + ) + self.email: Optional[str] = payload.get("email") + self.status_callback: Optional[str] = payload.get("status_callback") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[TrustProductsContext] = None + + @property + def _proxy(self) -> "TrustProductsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TrustProductsContext for this TrustProductsInstance + """ + if self._context is None: + self._context = TrustProductsContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TrustProductsInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TrustProductsInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TrustProductsInstance": + """ + Fetch the TrustProductsInstance + + + :returns: The fetched TrustProductsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TrustProductsInstance": + """ + Asynchronous coroutine to fetch the TrustProductsInstance + + + :returns: The fetched TrustProductsInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> "TrustProductsInstance": + """ + Update the TrustProductsInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + + :returns: The updated TrustProductsInstance + """ + return self._proxy.update( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + + async def update_async( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> "TrustProductsInstance": + """ + Asynchronous coroutine to update the TrustProductsInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + + :returns: The updated TrustProductsInstance + """ + return await self._proxy.update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, + ) + + @property + def trust_products_channel_endpoint_assignment( + self, + ) -> TrustProductsChannelEndpointAssignmentList: + """ + Access the trust_products_channel_endpoint_assignment + """ + return self._proxy.trust_products_channel_endpoint_assignment + + @property + def trust_products_entity_assignments(self) -> TrustProductsEntityAssignmentsList: + """ + Access the trust_products_entity_assignments + """ + return self._proxy.trust_products_entity_assignments + + @property + def trust_products_evaluations(self) -> TrustProductsEvaluationsList: + """ + Access the trust_products_evaluations + """ + return self._proxy.trust_products_evaluations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.TrustProductsInstance {}>".format(context) + + +class TrustProductsContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the TrustProductsContext + + :param version: Version that contains the resource + :param sid: The unique string that we created to identify the Trust Product resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/TrustProducts/{sid}".format(**self._solution) + + self._trust_products_channel_endpoint_assignment: Optional[ + TrustProductsChannelEndpointAssignmentList + ] = None + self._trust_products_entity_assignments: Optional[ + TrustProductsEntityAssignmentsList + ] = None + self._trust_products_evaluations: Optional[TrustProductsEvaluationsList] = None + + def delete(self) -> bool: + """ + Deletes the TrustProductsInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TrustProductsInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TrustProductsInstance: + """ + Fetch the TrustProductsInstance + + + :returns: The fetched TrustProductsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TrustProductsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TrustProductsInstance: + """ + Asynchronous coroutine to fetch the TrustProductsInstance + + + :returns: The fetched TrustProductsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TrustProductsInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> TrustProductsInstance: + """ + Update the TrustProductsInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + + :returns: The updated TrustProductsInstance + """ + + data = values.of( + { + "Status": status, + "StatusCallback": status_callback, + "FriendlyName": friendly_name, + "Email": email, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrustProductsInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + status_callback: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + email: Union[str, object] = values.unset, + ) -> TrustProductsInstance: + """ + Asynchronous coroutine to update the TrustProductsInstance + + :param status: + :param status_callback: The URL we call to inform your application of status changes. + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + + :returns: The updated TrustProductsInstance + """ + + data = values.of( + { + "Status": status, + "StatusCallback": status_callback, + "FriendlyName": friendly_name, + "Email": email, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrustProductsInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def trust_products_channel_endpoint_assignment( + self, + ) -> TrustProductsChannelEndpointAssignmentList: + """ + Access the trust_products_channel_endpoint_assignment + """ + if self._trust_products_channel_endpoint_assignment is None: + self._trust_products_channel_endpoint_assignment = ( + TrustProductsChannelEndpointAssignmentList( + self._version, + self._solution["sid"], + ) + ) + return self._trust_products_channel_endpoint_assignment + + @property + def trust_products_entity_assignments(self) -> TrustProductsEntityAssignmentsList: + """ + Access the trust_products_entity_assignments + """ + if self._trust_products_entity_assignments is None: + self._trust_products_entity_assignments = ( + TrustProductsEntityAssignmentsList( + self._version, + self._solution["sid"], + ) + ) + return self._trust_products_entity_assignments + + @property + def trust_products_evaluations(self) -> TrustProductsEvaluationsList: + """ + Access the trust_products_evaluations + """ + if self._trust_products_evaluations is None: + self._trust_products_evaluations = TrustProductsEvaluationsList( + self._version, + self._solution["sid"], + ) + return self._trust_products_evaluations + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.TrustProductsContext {}>".format(context) + + +class TrustProductsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TrustProductsInstance: + """ + Build an instance of TrustProductsInstance + + :param payload: Payload response from the API + """ + return TrustProductsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.TrustProductsPage>" + + +class TrustProductsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TrustProductsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/TrustProducts" + + def create( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> TrustProductsInstance: + """ + Create the TrustProductsInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + :param policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param status_callback: The URL we call to inform your application of status changes. + + :returns: The created TrustProductsInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Email": email, + "PolicySid": policy_sid, + "StatusCallback": status_callback, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrustProductsInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> TrustProductsInstance: + """ + Asynchronously create the TrustProductsInstance + + :param friendly_name: The string that you assigned to describe the resource. + :param email: The email address that will receive updates when the Trust Product resource changes status. + :param policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param status_callback: The URL we call to inform your application of status changes. + + :returns: The created TrustProductsInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Email": email, + "PolicySid": policy_sid, + "StatusCallback": status_callback, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrustProductsInstance(self._version, payload) + + def stream( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TrustProductsInstance]: + """ + Streams TrustProductsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "TrustProductsInstance.Status" status: The verification status of the Trust Product resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TrustProductsInstance]: + """ + Asynchronously streams TrustProductsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "TrustProductsInstance.Status" status: The verification status of the Trust Product resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrustProductsInstance]: + """ + Lists TrustProductsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "TrustProductsInstance.Status" status: The verification status of the Trust Product resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrustProductsInstance]: + """ + Asynchronously lists TrustProductsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "TrustProductsInstance.Status" status: The verification status of the Trust Product resource. + :param str friendly_name: The string that you assigned to describe the resource. + :param str policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + friendly_name=friendly_name, + policy_sid=policy_sid, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrustProductsPage: + """ + Retrieve a single page of TrustProductsInstance records from the API. + Request is executed immediately + + :param status: The verification status of the Trust Product resource. + :param friendly_name: The string that you assigned to describe the resource. + :param policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrustProductsInstance + """ + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "PolicySid": policy_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrustProductsPage(self._version, response) + + async def page_async( + self, + status: Union["TrustProductsInstance.Status", object] = values.unset, + friendly_name: Union[str, object] = values.unset, + policy_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrustProductsPage: + """ + Asynchronously retrieve a single page of TrustProductsInstance records from the API. + Request is executed immediately + + :param status: The verification status of the Trust Product resource. + :param friendly_name: The string that you assigned to describe the resource. + :param policy_sid: The unique string of a policy that is associated to the Trust Product resource. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrustProductsInstance + """ + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "PolicySid": policy_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrustProductsPage(self._version, response) + + def get_page(self, target_url: str) -> TrustProductsPage: + """ + Retrieve a specific page of TrustProductsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrustProductsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TrustProductsPage(self._version, response) + + async def get_page_async(self, target_url: str) -> TrustProductsPage: + """ + Asynchronously retrieve a specific page of TrustProductsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrustProductsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TrustProductsPage(self._version, response) + + def get(self, sid: str) -> TrustProductsContext: + """ + Constructs a TrustProductsContext + + :param sid: The unique string that we created to identify the Trust Product resource. + """ + return TrustProductsContext(self._version, sid=sid) + + def __call__(self, sid: str) -> TrustProductsContext: + """ + Constructs a TrustProductsContext + + :param sid: The unique string that we created to identify the Trust Product resource. + """ + return TrustProductsContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.TrustProductsList>" diff --git a/twilio/rest/trusthub/v1/trust_products/trust_products_channel_endpoint_assignment.py b/twilio/rest/trusthub/v1/trust_products/trust_products_channel_endpoint_assignment.py new file mode 100644 index 0000000000..adf9c51f51 --- /dev/null +++ b/twilio/rest/trusthub/v1/trust_products/trust_products_channel_endpoint_assignment.py @@ -0,0 +1,616 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TrustProductsChannelEndpointAssignmentInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Item Assignment resource. + :ivar trust_product_sid: The unique string that we created to identify the CustomerProfile resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Item Assignment resource. + :ivar channel_endpoint_type: The type of channel endpoint. eg: phone-number + :ivar channel_endpoint_sid: The SID of an channel endpoint + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Identity resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + trust_product_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.trust_product_sid: Optional[str] = payload.get("trust_product_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.channel_endpoint_type: Optional[str] = payload.get("channel_endpoint_type") + self.channel_endpoint_sid: Optional[str] = payload.get("channel_endpoint_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "trust_product_sid": trust_product_sid, + "sid": sid or self.sid, + } + self._context: Optional[TrustProductsChannelEndpointAssignmentContext] = None + + @property + def _proxy(self) -> "TrustProductsChannelEndpointAssignmentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TrustProductsChannelEndpointAssignmentContext for this TrustProductsChannelEndpointAssignmentInstance + """ + if self._context is None: + self._context = TrustProductsChannelEndpointAssignmentContext( + self._version, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TrustProductsChannelEndpointAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TrustProductsChannelEndpointAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TrustProductsChannelEndpointAssignmentInstance": + """ + Fetch the TrustProductsChannelEndpointAssignmentInstance + + + :returns: The fetched TrustProductsChannelEndpointAssignmentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TrustProductsChannelEndpointAssignmentInstance": + """ + Asynchronous coroutine to fetch the TrustProductsChannelEndpointAssignmentInstance + + + :returns: The fetched TrustProductsChannelEndpointAssignmentInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.TrustProductsChannelEndpointAssignmentInstance {}>".format( + context + ) + + +class TrustProductsChannelEndpointAssignmentContext(InstanceContext): + + def __init__(self, version: Version, trust_product_sid: str, sid: str): + """ + Initialize the TrustProductsChannelEndpointAssignmentContext + + :param version: Version that contains the resource + :param trust_product_sid: The unique string that we created to identify the CustomerProfile resource. + :param sid: The unique string that we created to identify the resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trust_product_sid": trust_product_sid, + "sid": sid, + } + self._uri = "/TrustProducts/{trust_product_sid}/ChannelEndpointAssignments/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the TrustProductsChannelEndpointAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TrustProductsChannelEndpointAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TrustProductsChannelEndpointAssignmentInstance: + """ + Fetch the TrustProductsChannelEndpointAssignmentInstance + + + :returns: The fetched TrustProductsChannelEndpointAssignmentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TrustProductsChannelEndpointAssignmentInstance: + """ + Asynchronous coroutine to fetch the TrustProductsChannelEndpointAssignmentInstance + + + :returns: The fetched TrustProductsChannelEndpointAssignmentInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.TrustProductsChannelEndpointAssignmentContext {}>".format( + context + ) + + +class TrustProductsChannelEndpointAssignmentPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> TrustProductsChannelEndpointAssignmentInstance: + """ + Build an instance of TrustProductsChannelEndpointAssignmentInstance + + :param payload: Payload response from the API + """ + return TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.TrustProductsChannelEndpointAssignmentPage>" + + +class TrustProductsChannelEndpointAssignmentList(ListResource): + + def __init__(self, version: Version, trust_product_sid: str): + """ + Initialize the TrustProductsChannelEndpointAssignmentList + + :param version: Version that contains the resource + :param trust_product_sid: The unique string that we created to identify the CustomerProfile resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trust_product_sid": trust_product_sid, + } + self._uri = ( + "/TrustProducts/{trust_product_sid}/ChannelEndpointAssignments".format( + **self._solution + ) + ) + + def create( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> TrustProductsChannelEndpointAssignmentInstance: + """ + Create the TrustProductsChannelEndpointAssignmentInstance + + :param channel_endpoint_type: The type of channel endpoint. eg: phone-number + :param channel_endpoint_sid: The SID of an channel endpoint + + :returns: The created TrustProductsChannelEndpointAssignmentInstance + """ + + data = values.of( + { + "ChannelEndpointType": channel_endpoint_type, + "ChannelEndpointSid": channel_endpoint_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + async def create_async( + self, channel_endpoint_type: str, channel_endpoint_sid: str + ) -> TrustProductsChannelEndpointAssignmentInstance: + """ + Asynchronously create the TrustProductsChannelEndpointAssignmentInstance + + :param channel_endpoint_type: The type of channel endpoint. eg: phone-number + :param channel_endpoint_sid: The SID of an channel endpoint + + :returns: The created TrustProductsChannelEndpointAssignmentInstance + """ + + data = values.of( + { + "ChannelEndpointType": channel_endpoint_type, + "ChannelEndpointSid": channel_endpoint_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + def stream( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TrustProductsChannelEndpointAssignmentInstance]: + """ + Streams TrustProductsChannelEndpointAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TrustProductsChannelEndpointAssignmentInstance]: + """ + Asynchronously streams TrustProductsChannelEndpointAssignmentInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrustProductsChannelEndpointAssignmentInstance]: + """ + Lists TrustProductsChannelEndpointAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrustProductsChannelEndpointAssignmentInstance]: + """ + Asynchronously lists TrustProductsChannelEndpointAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str channel_endpoint_sid: The SID of an channel endpoint + :param str channel_endpoint_sids: comma separated list of channel endpoint sids + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + channel_endpoint_sid=channel_endpoint_sid, + channel_endpoint_sids=channel_endpoint_sids, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrustProductsChannelEndpointAssignmentPage: + """ + Retrieve a single page of TrustProductsChannelEndpointAssignmentInstance records from the API. + Request is executed immediately + + :param channel_endpoint_sid: The SID of an channel endpoint + :param channel_endpoint_sids: comma separated list of channel endpoint sids + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrustProductsChannelEndpointAssignmentInstance + """ + data = values.of( + { + "ChannelEndpointSid": channel_endpoint_sid, + "ChannelEndpointSids": channel_endpoint_sids, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrustProductsChannelEndpointAssignmentPage( + self._version, response, self._solution + ) + + async def page_async( + self, + channel_endpoint_sid: Union[str, object] = values.unset, + channel_endpoint_sids: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrustProductsChannelEndpointAssignmentPage: + """ + Asynchronously retrieve a single page of TrustProductsChannelEndpointAssignmentInstance records from the API. + Request is executed immediately + + :param channel_endpoint_sid: The SID of an channel endpoint + :param channel_endpoint_sids: comma separated list of channel endpoint sids + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrustProductsChannelEndpointAssignmentInstance + """ + data = values.of( + { + "ChannelEndpointSid": channel_endpoint_sid, + "ChannelEndpointSids": channel_endpoint_sids, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrustProductsChannelEndpointAssignmentPage( + self._version, response, self._solution + ) + + def get_page(self, target_url: str) -> TrustProductsChannelEndpointAssignmentPage: + """ + Retrieve a specific page of TrustProductsChannelEndpointAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrustProductsChannelEndpointAssignmentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TrustProductsChannelEndpointAssignmentPage( + self._version, response, self._solution + ) + + async def get_page_async( + self, target_url: str + ) -> TrustProductsChannelEndpointAssignmentPage: + """ + Asynchronously retrieve a specific page of TrustProductsChannelEndpointAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrustProductsChannelEndpointAssignmentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TrustProductsChannelEndpointAssignmentPage( + self._version, response, self._solution + ) + + def get(self, sid: str) -> TrustProductsChannelEndpointAssignmentContext: + """ + Constructs a TrustProductsChannelEndpointAssignmentContext + + :param sid: The unique string that we created to identify the resource. + """ + return TrustProductsChannelEndpointAssignmentContext( + self._version, + trust_product_sid=self._solution["trust_product_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> TrustProductsChannelEndpointAssignmentContext: + """ + Constructs a TrustProductsChannelEndpointAssignmentContext + + :param sid: The unique string that we created to identify the resource. + """ + return TrustProductsChannelEndpointAssignmentContext( + self._version, + trust_product_sid=self._solution["trust_product_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.TrustProductsChannelEndpointAssignmentList>" diff --git a/twilio/rest/trusthub/v1/trust_products/trust_products_entity_assignments.py b/twilio/rest/trusthub/v1/trust_products/trust_products_entity_assignments.py new file mode 100644 index 0000000000..ebda7ee8c0 --- /dev/null +++ b/twilio/rest/trusthub/v1/trust_products/trust_products_entity_assignments.py @@ -0,0 +1,584 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TrustProductsEntityAssignmentsInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Item Assignment resource. + :ivar trust_product_sid: The unique string that we created to identify the TrustProduct resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Item Assignment resource. + :ivar object_sid: The SID of an object bag that holds information of the different items. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Identity resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + trust_product_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.trust_product_sid: Optional[str] = payload.get("trust_product_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.object_sid: Optional[str] = payload.get("object_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "trust_product_sid": trust_product_sid, + "sid": sid or self.sid, + } + self._context: Optional[TrustProductsEntityAssignmentsContext] = None + + @property + def _proxy(self) -> "TrustProductsEntityAssignmentsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TrustProductsEntityAssignmentsContext for this TrustProductsEntityAssignmentsInstance + """ + if self._context is None: + self._context = TrustProductsEntityAssignmentsContext( + self._version, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TrustProductsEntityAssignmentsInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TrustProductsEntityAssignmentsInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "TrustProductsEntityAssignmentsInstance": + """ + Fetch the TrustProductsEntityAssignmentsInstance + + + :returns: The fetched TrustProductsEntityAssignmentsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TrustProductsEntityAssignmentsInstance": + """ + Asynchronous coroutine to fetch the TrustProductsEntityAssignmentsInstance + + + :returns: The fetched TrustProductsEntityAssignmentsInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.TrustProductsEntityAssignmentsInstance {}>".format( + context + ) + + +class TrustProductsEntityAssignmentsContext(InstanceContext): + + def __init__(self, version: Version, trust_product_sid: str, sid: str): + """ + Initialize the TrustProductsEntityAssignmentsContext + + :param version: Version that contains the resource + :param trust_product_sid: The unique string that we created to identify the TrustProduct resource. + :param sid: The unique string that we created to identify the Identity resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trust_product_sid": trust_product_sid, + "sid": sid, + } + self._uri = "/TrustProducts/{trust_product_sid}/EntityAssignments/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the TrustProductsEntityAssignmentsInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TrustProductsEntityAssignmentsInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> TrustProductsEntityAssignmentsInstance: + """ + Fetch the TrustProductsEntityAssignmentsInstance + + + :returns: The fetched TrustProductsEntityAssignmentsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TrustProductsEntityAssignmentsInstance: + """ + Asynchronous coroutine to fetch the TrustProductsEntityAssignmentsInstance + + + :returns: The fetched TrustProductsEntityAssignmentsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.TrustProductsEntityAssignmentsContext {}>".format( + context + ) + + +class TrustProductsEntityAssignmentsPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> TrustProductsEntityAssignmentsInstance: + """ + Build an instance of TrustProductsEntityAssignmentsInstance + + :param payload: Payload response from the API + """ + return TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.TrustProductsEntityAssignmentsPage>" + + +class TrustProductsEntityAssignmentsList(ListResource): + + def __init__(self, version: Version, trust_product_sid: str): + """ + Initialize the TrustProductsEntityAssignmentsList + + :param version: Version that contains the resource + :param trust_product_sid: The unique string that we created to identify the TrustProduct resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trust_product_sid": trust_product_sid, + } + self._uri = "/TrustProducts/{trust_product_sid}/EntityAssignments".format( + **self._solution + ) + + def create(self, object_sid: str) -> TrustProductsEntityAssignmentsInstance: + """ + Create the TrustProductsEntityAssignmentsInstance + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created TrustProductsEntityAssignmentsInstance + """ + + data = values.of( + { + "ObjectSid": object_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + async def create_async( + self, object_sid: str + ) -> TrustProductsEntityAssignmentsInstance: + """ + Asynchronously create the TrustProductsEntityAssignmentsInstance + + :param object_sid: The SID of an object bag that holds information of the different items. + + :returns: The created TrustProductsEntityAssignmentsInstance + """ + + data = values.of( + { + "ObjectSid": object_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + def stream( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TrustProductsEntityAssignmentsInstance]: + """ + Streams TrustProductsEntityAssignmentsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(object_type=object_type, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TrustProductsEntityAssignmentsInstance]: + """ + Asynchronously streams TrustProductsEntityAssignmentsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + object_type=object_type, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrustProductsEntityAssignmentsInstance]: + """ + Lists TrustProductsEntityAssignmentsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + object_type=object_type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + object_type: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrustProductsEntityAssignmentsInstance]: + """ + Asynchronously lists TrustProductsEntityAssignmentsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + object_type=object_type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + object_type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrustProductsEntityAssignmentsPage: + """ + Retrieve a single page of TrustProductsEntityAssignmentsInstance records from the API. + Request is executed immediately + + :param object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrustProductsEntityAssignmentsInstance + """ + data = values.of( + { + "ObjectType": object_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrustProductsEntityAssignmentsPage( + self._version, response, self._solution + ) + + async def page_async( + self, + object_type: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrustProductsEntityAssignmentsPage: + """ + Asynchronously retrieve a single page of TrustProductsEntityAssignmentsInstance records from the API. + Request is executed immediately + + :param object_type: A string to filter the results by (EndUserType or SupportingDocumentType) machine-name. This is useful when you want to retrieve the entity-assignment of a specific end-user or supporting document. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrustProductsEntityAssignmentsInstance + """ + data = values.of( + { + "ObjectType": object_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrustProductsEntityAssignmentsPage( + self._version, response, self._solution + ) + + def get_page(self, target_url: str) -> TrustProductsEntityAssignmentsPage: + """ + Retrieve a specific page of TrustProductsEntityAssignmentsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrustProductsEntityAssignmentsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TrustProductsEntityAssignmentsPage( + self._version, response, self._solution + ) + + async def get_page_async( + self, target_url: str + ) -> TrustProductsEntityAssignmentsPage: + """ + Asynchronously retrieve a specific page of TrustProductsEntityAssignmentsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrustProductsEntityAssignmentsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TrustProductsEntityAssignmentsPage( + self._version, response, self._solution + ) + + def get(self, sid: str) -> TrustProductsEntityAssignmentsContext: + """ + Constructs a TrustProductsEntityAssignmentsContext + + :param sid: The unique string that we created to identify the Identity resource. + """ + return TrustProductsEntityAssignmentsContext( + self._version, + trust_product_sid=self._solution["trust_product_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> TrustProductsEntityAssignmentsContext: + """ + Constructs a TrustProductsEntityAssignmentsContext + + :param sid: The unique string that we created to identify the Identity resource. + """ + return TrustProductsEntityAssignmentsContext( + self._version, + trust_product_sid=self._solution["trust_product_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.TrustProductsEntityAssignmentsList>" diff --git a/twilio/rest/trusthub/v1/trust_products/trust_products_evaluations.py b/twilio/rest/trusthub/v1/trust_products/trust_products_evaluations.py new file mode 100644 index 0000000000..3691aa017b --- /dev/null +++ b/twilio/rest/trusthub/v1/trust_products/trust_products_evaluations.py @@ -0,0 +1,517 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Trusthub + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TrustProductsEvaluationsInstance(InstanceResource): + + class Status(object): + COMPLIANT = "compliant" + NONCOMPLIANT = "noncompliant" + + """ + :ivar sid: The unique string that identifies the Evaluation resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the trust_product resource. + :ivar policy_sid: The unique string of a policy that is associated to the trust_product resource. + :ivar trust_product_sid: The unique string that we created to identify the trust_product resource. + :ivar status: + :ivar results: The results of the Evaluation which includes the valid and invalid attributes. + :ivar date_created: + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + trust_product_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.policy_sid: Optional[str] = payload.get("policy_sid") + self.trust_product_sid: Optional[str] = payload.get("trust_product_sid") + self.status: Optional["TrustProductsEvaluationsInstance.Status"] = payload.get( + "status" + ) + self.results: Optional[List[Dict[str, object]]] = payload.get("results") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "trust_product_sid": trust_product_sid, + "sid": sid or self.sid, + } + self._context: Optional[TrustProductsEvaluationsContext] = None + + @property + def _proxy(self) -> "TrustProductsEvaluationsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TrustProductsEvaluationsContext for this TrustProductsEvaluationsInstance + """ + if self._context is None: + self._context = TrustProductsEvaluationsContext( + self._version, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "TrustProductsEvaluationsInstance": + """ + Fetch the TrustProductsEvaluationsInstance + + + :returns: The fetched TrustProductsEvaluationsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TrustProductsEvaluationsInstance": + """ + Asynchronous coroutine to fetch the TrustProductsEvaluationsInstance + + + :returns: The fetched TrustProductsEvaluationsInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.TrustProductsEvaluationsInstance {}>".format( + context + ) + + +class TrustProductsEvaluationsContext(InstanceContext): + + def __init__(self, version: Version, trust_product_sid: str, sid: str): + """ + Initialize the TrustProductsEvaluationsContext + + :param version: Version that contains the resource + :param trust_product_sid: The unique string that we created to identify the trust_product resource. + :param sid: The unique string that identifies the Evaluation resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trust_product_sid": trust_product_sid, + "sid": sid, + } + self._uri = "/TrustProducts/{trust_product_sid}/Evaluations/{sid}".format( + **self._solution + ) + + def fetch(self) -> TrustProductsEvaluationsInstance: + """ + Fetch the TrustProductsEvaluationsInstance + + + :returns: The fetched TrustProductsEvaluationsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> TrustProductsEvaluationsInstance: + """ + Asynchronous coroutine to fetch the TrustProductsEvaluationsInstance + + + :returns: The fetched TrustProductsEvaluationsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Trusthub.V1.TrustProductsEvaluationsContext {}>".format(context) + + +class TrustProductsEvaluationsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TrustProductsEvaluationsInstance: + """ + Build an instance of TrustProductsEvaluationsInstance + + :param payload: Payload response from the API + """ + return TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.TrustProductsEvaluationsPage>" + + +class TrustProductsEvaluationsList(ListResource): + + def __init__(self, version: Version, trust_product_sid: str): + """ + Initialize the TrustProductsEvaluationsList + + :param version: Version that contains the resource + :param trust_product_sid: The unique string that we created to identify the trust_product resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "trust_product_sid": trust_product_sid, + } + self._uri = "/TrustProducts/{trust_product_sid}/Evaluations".format( + **self._solution + ) + + def create(self, policy_sid: str) -> TrustProductsEvaluationsInstance: + """ + Create the TrustProductsEvaluationsInstance + + :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. + + :returns: The created TrustProductsEvaluationsInstance + """ + + data = values.of( + { + "PolicySid": policy_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + async def create_async(self, policy_sid: str) -> TrustProductsEvaluationsInstance: + """ + Asynchronously create the TrustProductsEvaluationsInstance + + :param policy_sid: The unique string of a policy that is associated to the customer_profile resource. + + :returns: The created TrustProductsEvaluationsInstance + """ + + data = values.of( + { + "PolicySid": policy_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TrustProductsEvaluationsInstance]: + """ + Streams TrustProductsEvaluationsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TrustProductsEvaluationsInstance]: + """ + Asynchronously streams TrustProductsEvaluationsInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrustProductsEvaluationsInstance]: + """ + Lists TrustProductsEvaluationsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TrustProductsEvaluationsInstance]: + """ + Asynchronously lists TrustProductsEvaluationsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrustProductsEvaluationsPage: + """ + Retrieve a single page of TrustProductsEvaluationsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrustProductsEvaluationsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrustProductsEvaluationsPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TrustProductsEvaluationsPage: + """ + Asynchronously retrieve a single page of TrustProductsEvaluationsInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TrustProductsEvaluationsInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TrustProductsEvaluationsPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> TrustProductsEvaluationsPage: + """ + Retrieve a specific page of TrustProductsEvaluationsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrustProductsEvaluationsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TrustProductsEvaluationsPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> TrustProductsEvaluationsPage: + """ + Asynchronously retrieve a specific page of TrustProductsEvaluationsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TrustProductsEvaluationsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TrustProductsEvaluationsPage(self._version, response, self._solution) + + def get(self, sid: str) -> TrustProductsEvaluationsContext: + """ + Constructs a TrustProductsEvaluationsContext + + :param sid: The unique string that identifies the Evaluation resource. + """ + return TrustProductsEvaluationsContext( + self._version, + trust_product_sid=self._solution["trust_product_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> TrustProductsEvaluationsContext: + """ + Constructs a TrustProductsEvaluationsContext + + :param sid: The unique string that identifies the Evaluation resource. + """ + return TrustProductsEvaluationsContext( + self._version, + trust_product_sid=self._solution["trust_product_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Trusthub.V1.TrustProductsEvaluationsList>" diff --git a/twilio/rest/verify/VerifyBase.py b/twilio/rest/verify/VerifyBase.py new file mode 100644 index 0000000000..076f063147 --- /dev/null +++ b/twilio/rest/verify/VerifyBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.verify.v2 import V2 + + +class VerifyBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Verify Domain + + :returns: Domain for Verify + """ + super().__init__(twilio, "https://verify.twilio.com") + self._v2: Optional[V2] = None + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Verify + """ + if self._v2 is None: + self._v2 = V2(self) + return self._v2 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Verify>" diff --git a/twilio/rest/verify/__init__.py b/twilio/rest/verify/__init__.py new file mode 100644 index 0000000000..a66b3333b0 --- /dev/null +++ b/twilio/rest/verify/__init__.py @@ -0,0 +1,67 @@ +from warnings import warn + +from twilio.rest.verify.VerifyBase import VerifyBase +from twilio.rest.verify.v2.form import FormList +from twilio.rest.verify.v2.safelist import SafelistList +from twilio.rest.verify.v2.service import ServiceList +from twilio.rest.verify.v2.template import TemplateList +from twilio.rest.verify.v2.verification_attempt import VerificationAttemptList +from twilio.rest.verify.v2.verification_attempts_summary import ( + VerificationAttemptsSummaryList, +) + + +class Verify(VerifyBase): + @property + def forms(self) -> FormList: + warn( + "forms is deprecated. Use v2.forms instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.forms + + @property + def safelist(self) -> SafelistList: + warn( + "safelist is deprecated. Use v2.safelist instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.safelist + + @property + def services(self) -> ServiceList: + warn( + "services is deprecated. Use v2.services instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.services + + @property + def verification_attempts(self) -> VerificationAttemptList: + warn( + "verification_attempts is deprecated. Use v2.verification_attempts instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.verification_attempts + + @property + def verification_attempts_summary(self) -> VerificationAttemptsSummaryList: + warn( + "verification_attempts_summary is deprecated. Use v2.verification_attempts_summary instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.verification_attempts_summary + + @property + def templates(self) -> TemplateList: + warn( + "templates is deprecated. Use v2.templates instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v2.templates diff --git a/twilio/rest/verify/v2/__init__.py b/twilio/rest/verify/v2/__init__.py new file mode 100644 index 0000000000..01bee13b0d --- /dev/null +++ b/twilio/rest/verify/v2/__init__.py @@ -0,0 +1,87 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.verify.v2.form import FormList +from twilio.rest.verify.v2.safelist import SafelistList +from twilio.rest.verify.v2.service import ServiceList +from twilio.rest.verify.v2.template import TemplateList +from twilio.rest.verify.v2.verification_attempt import VerificationAttemptList +from twilio.rest.verify.v2.verification_attempts_summary import ( + VerificationAttemptsSummaryList, +) + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Verify + + :param domain: The Twilio.verify domain + """ + super().__init__(domain, "v2") + self._forms: Optional[FormList] = None + self._safelist: Optional[SafelistList] = None + self._services: Optional[ServiceList] = None + self._templates: Optional[TemplateList] = None + self._verification_attempts: Optional[VerificationAttemptList] = None + self._verification_attempts_summary: Optional[ + VerificationAttemptsSummaryList + ] = None + + @property + def forms(self) -> FormList: + if self._forms is None: + self._forms = FormList(self) + return self._forms + + @property + def safelist(self) -> SafelistList: + if self._safelist is None: + self._safelist = SafelistList(self) + return self._safelist + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + @property + def templates(self) -> TemplateList: + if self._templates is None: + self._templates = TemplateList(self) + return self._templates + + @property + def verification_attempts(self) -> VerificationAttemptList: + if self._verification_attempts is None: + self._verification_attempts = VerificationAttemptList(self) + return self._verification_attempts + + @property + def verification_attempts_summary(self) -> VerificationAttemptsSummaryList: + if self._verification_attempts_summary is None: + self._verification_attempts_summary = VerificationAttemptsSummaryList(self) + return self._verification_attempts_summary + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2>" diff --git a/twilio/rest/verify/v2/form.py b/twilio/rest/verify/v2/form.py new file mode 100644 index 0000000000..454030208d --- /dev/null +++ b/twilio/rest/verify/v2/form.py @@ -0,0 +1,198 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class FormInstance(InstanceResource): + + class FormTypes(object): + FORM_PUSH = "form-push" + + """ + :ivar form_type: + :ivar forms: Object that contains the available forms for this type. This available forms are given in the standard [JSON Schema](https://json-schema.org/) format + :ivar form_meta: Additional information for the available forms for this type. E.g. The separator string used for `binding` in a Factor push. + :ivar url: The URL to access the forms for this type. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + form_type: Optional[FormTypes] = None, + ): + super().__init__(version) + + self.form_type: Optional["FormInstance.FormTypes"] = payload.get("form_type") + self.forms: Optional[Dict[str, object]] = payload.get("forms") + self.form_meta: Optional[Dict[str, object]] = payload.get("form_meta") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "form_type": form_type or self.form_type, + } + self._context: Optional[FormContext] = None + + @property + def _proxy(self) -> "FormContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FormContext for this FormInstance + """ + if self._context is None: + self._context = FormContext( + self._version, + form_type=self._solution["form_type"], + ) + return self._context + + def fetch(self) -> "FormInstance": + """ + Fetch the FormInstance + + + :returns: The fetched FormInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FormInstance": + """ + Asynchronous coroutine to fetch the FormInstance + + + :returns: The fetched FormInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.FormInstance {}>".format(context) + + +class FormContext(InstanceContext): + + def __init__(self, version: Version, form_type: "FormInstance.FormTypes"): + """ + Initialize the FormContext + + :param version: Version that contains the resource + :param form_type: The Type of this Form. Currently only `form-push` is supported. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "form_type": form_type, + } + self._uri = "/Forms/{form_type}".format(**self._solution) + + def fetch(self) -> FormInstance: + """ + Fetch the FormInstance + + + :returns: The fetched FormInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FormInstance( + self._version, + payload, + form_type=self._solution["form_type"], + ) + + async def fetch_async(self) -> FormInstance: + """ + Asynchronous coroutine to fetch the FormInstance + + + :returns: The fetched FormInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FormInstance( + self._version, + payload, + form_type=self._solution["form_type"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.FormContext {}>".format(context) + + +class FormList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the FormList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, form_type: "FormInstance.FormTypes") -> FormContext: + """ + Constructs a FormContext + + :param form_type: The Type of this Form. Currently only `form-push` is supported. + """ + return FormContext(self._version, form_type=form_type) + + def __call__(self, form_type: "FormInstance.FormTypes") -> FormContext: + """ + Constructs a FormContext + + :param form_type: The Type of this Form. Currently only `form-push` is supported. + """ + return FormContext(self._version, form_type=form_type) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.FormList>" diff --git a/twilio/rest/verify/v2/safelist.py b/twilio/rest/verify/v2/safelist.py new file mode 100644 index 0000000000..00fc0976f7 --- /dev/null +++ b/twilio/rest/verify/v2/safelist.py @@ -0,0 +1,290 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SafelistInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the SafeList resource. + :ivar phone_number: The phone number in SafeList. + :ivar url: The absolute URL of the SafeList resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + phone_number: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "phone_number": phone_number or self.phone_number, + } + self._context: Optional[SafelistContext] = None + + @property + def _proxy(self) -> "SafelistContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SafelistContext for this SafelistInstance + """ + if self._context is None: + self._context = SafelistContext( + self._version, + phone_number=self._solution["phone_number"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SafelistInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SafelistInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SafelistInstance": + """ + Fetch the SafelistInstance + + + :returns: The fetched SafelistInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SafelistInstance": + """ + Asynchronous coroutine to fetch the SafelistInstance + + + :returns: The fetched SafelistInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.SafelistInstance {}>".format(context) + + +class SafelistContext(InstanceContext): + + def __init__(self, version: Version, phone_number: str): + """ + Initialize the SafelistContext + + :param version: Version that contains the resource + :param phone_number: The phone number to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + """ + super().__init__(version) + + # Path Solution + self._solution = { + "phone_number": phone_number, + } + self._uri = "/SafeList/Numbers/{phone_number}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the SafelistInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SafelistInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SafelistInstance: + """ + Fetch the SafelistInstance + + + :returns: The fetched SafelistInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SafelistInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + async def fetch_async(self) -> SafelistInstance: + """ + Asynchronous coroutine to fetch the SafelistInstance + + + :returns: The fetched SafelistInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SafelistInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.SafelistContext {}>".format(context) + + +class SafelistList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SafelistList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SafeList/Numbers" + + def create(self, phone_number: str) -> SafelistInstance: + """ + Create the SafelistInstance + + :param phone_number: The phone number to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + + :returns: The created SafelistInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SafelistInstance(self._version, payload) + + async def create_async(self, phone_number: str) -> SafelistInstance: + """ + Asynchronously create the SafelistInstance + + :param phone_number: The phone number to be added in SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + + :returns: The created SafelistInstance + """ + + data = values.of( + { + "PhoneNumber": phone_number, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SafelistInstance(self._version, payload) + + def get(self, phone_number: str) -> SafelistContext: + """ + Constructs a SafelistContext + + :param phone_number: The phone number to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + """ + return SafelistContext(self._version, phone_number=phone_number) + + def __call__(self, phone_number: str) -> SafelistContext: + """ + Constructs a SafelistContext + + :param phone_number: The phone number to be fetched from SafeList. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + """ + return SafelistContext(self._version, phone_number=phone_number) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.SafelistList>" diff --git a/twilio/rest/verify/v2/service/__init__.py b/twilio/rest/verify/v2/service/__init__.py new file mode 100644 index 0000000000..a64ab7a552 --- /dev/null +++ b/twilio/rest/verify/v2/service/__init__.py @@ -0,0 +1,1157 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.verify.v2.service.access_token import AccessTokenList +from twilio.rest.verify.v2.service.entity import EntityList +from twilio.rest.verify.v2.service.messaging_configuration import ( + MessagingConfigurationList, +) +from twilio.rest.verify.v2.service.rate_limit import RateLimitList +from twilio.rest.verify.v2.service.verification import VerificationList +from twilio.rest.verify.v2.service.verification_check import VerificationCheckList +from twilio.rest.verify.v2.service.webhook import WebhookList + + +class ServiceInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Service resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + :ivar friendly_name: The name that appears in the body of your verification messages. It can be up to 30 characters long and can include letters, numbers, spaces, dashes, underscores. Phone numbers, special characters or links are NOT allowed. It cannot contain more than 4 (consecutive or non-consecutive) digits. **This value should not contain PII.** + :ivar code_length: The length of the verification code to generate. + :ivar lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :ivar psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :ivar skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :ivar dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :ivar tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :ivar do_not_share_warning_enabled: Whether to add a security warning at the end of an SMS verification body. Disabled by default and applies only to SMS. Example SMS body: `Your AppName verification code is: 1234. Don’t share this code with anyone; our employees will never ask for the code` + :ivar custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :ivar push: Configurations for the Push factors (channel) created under this Service. + :ivar totp: Configurations for the TOTP factors (channel) created under this Service. + :ivar default_template_sid: + :ivar whatsapp: + :ivar verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.code_length: Optional[int] = deserialize.integer( + payload.get("code_length") + ) + self.lookup_enabled: Optional[bool] = payload.get("lookup_enabled") + self.psd2_enabled: Optional[bool] = payload.get("psd2_enabled") + self.skip_sms_to_landlines: Optional[bool] = payload.get( + "skip_sms_to_landlines" + ) + self.dtmf_input_required: Optional[bool] = payload.get("dtmf_input_required") + self.tts_name: Optional[str] = payload.get("tts_name") + self.do_not_share_warning_enabled: Optional[bool] = payload.get( + "do_not_share_warning_enabled" + ) + self.custom_code_enabled: Optional[bool] = payload.get("custom_code_enabled") + self.push: Optional[Dict[str, object]] = payload.get("push") + self.totp: Optional[Dict[str, object]] = payload.get("totp") + self.default_template_sid: Optional[str] = payload.get("default_template_sid") + self.whatsapp: Optional[Dict[str, object]] = payload.get("whatsapp") + self.verify_event_subscription_enabled: Optional[bool] = payload.get( + "verify_event_subscription_enabled" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ServiceContext] = None + + @property + def _proxy(self) -> "ServiceContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ServiceContext for this ServiceInstance + """ + if self._context is None: + self._context = ServiceContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ServiceInstance": + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ServiceInstance": + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a privacy warning at the end of an SMS. **Disabled by default and applies only for SMS.** + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. + :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: The updated ServiceInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> "ServiceInstance": + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a privacy warning at the end of an SMS. **Disabled by default and applies only for SMS.** + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. + :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: The updated ServiceInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + code_length=code_length, + lookup_enabled=lookup_enabled, + skip_sms_to_landlines=skip_sms_to_landlines, + dtmf_input_required=dtmf_input_required, + tts_name=tts_name, + psd2_enabled=psd2_enabled, + do_not_share_warning_enabled=do_not_share_warning_enabled, + custom_code_enabled=custom_code_enabled, + push_include_date=push_include_date, + push_apn_credential_sid=push_apn_credential_sid, + push_fcm_credential_sid=push_fcm_credential_sid, + totp_issuer=totp_issuer, + totp_time_step=totp_time_step, + totp_code_length=totp_code_length, + totp_skew=totp_skew, + default_template_sid=default_template_sid, + whatsapp_msg_service_sid=whatsapp_msg_service_sid, + whatsapp_from=whatsapp_from, + verify_event_subscription_enabled=verify_event_subscription_enabled, + ) + + @property + def access_tokens(self) -> AccessTokenList: + """ + Access the access_tokens + """ + return self._proxy.access_tokens + + @property + def entities(self) -> EntityList: + """ + Access the entities + """ + return self._proxy.entities + + @property + def messaging_configurations(self) -> MessagingConfigurationList: + """ + Access the messaging_configurations + """ + return self._proxy.messaging_configurations + + @property + def rate_limits(self) -> RateLimitList: + """ + Access the rate_limits + """ + return self._proxy.rate_limits + + @property + def verifications(self) -> VerificationList: + """ + Access the verifications + """ + return self._proxy.verifications + + @property + def verification_checks(self) -> VerificationCheckList: + """ + Access the verification_checks + """ + return self._proxy.verification_checks + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + return self._proxy.webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.ServiceInstance {}>".format(context) + + +class ServiceContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ServiceContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Services/{sid}".format(**self._solution) + + self._access_tokens: Optional[AccessTokenList] = None + self._entities: Optional[EntityList] = None + self._messaging_configurations: Optional[MessagingConfigurationList] = None + self._rate_limits: Optional[RateLimitList] = None + self._verifications: Optional[VerificationList] = None + self._verification_checks: Optional[VerificationCheckList] = None + self._webhooks: Optional[WebhookList] = None + + def delete(self) -> bool: + """ + Deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ServiceInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ServiceInstance: + """ + Fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ServiceInstance: + """ + Asynchronous coroutine to fetch the ServiceInstance + + + :returns: The fetched ServiceInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a privacy warning at the end of an SMS. **Disabled by default and applies only for SMS.** + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. + :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "CodeLength": code_length, + "LookupEnabled": serialize.boolean_to_string(lookup_enabled), + "SkipSmsToLandlines": serialize.boolean_to_string( + skip_sms_to_landlines + ), + "DtmfInputRequired": serialize.boolean_to_string(dtmf_input_required), + "TtsName": tts_name, + "Psd2Enabled": serialize.boolean_to_string(psd2_enabled), + "DoNotShareWarningEnabled": serialize.boolean_to_string( + do_not_share_warning_enabled + ), + "CustomCodeEnabled": serialize.boolean_to_string(custom_code_enabled), + "Push.IncludeDate": serialize.boolean_to_string(push_include_date), + "Push.ApnCredentialSid": push_apn_credential_sid, + "Push.FcmCredentialSid": push_fcm_credential_sid, + "Totp.Issuer": totp_issuer, + "Totp.TimeStep": totp_time_step, + "Totp.CodeLength": totp_code_length, + "Totp.Skew": totp_skew, + "DefaultTemplateSid": default_template_sid, + "Whatsapp.MsgServiceSid": whatsapp_msg_service_sid, + "Whatsapp.From": whatsapp_from, + "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( + verify_event_subscription_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronous coroutine to update the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a privacy warning at the end of an SMS. **Disabled by default and applies only for SMS.** + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services) to associate with the Verification Service. + :param whatsapp_from: The WhatsApp number to use as the sender of the verification messages. This number must be associated with the WhatsApp Message Service. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: The updated ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "CodeLength": code_length, + "LookupEnabled": serialize.boolean_to_string(lookup_enabled), + "SkipSmsToLandlines": serialize.boolean_to_string( + skip_sms_to_landlines + ), + "DtmfInputRequired": serialize.boolean_to_string(dtmf_input_required), + "TtsName": tts_name, + "Psd2Enabled": serialize.boolean_to_string(psd2_enabled), + "DoNotShareWarningEnabled": serialize.boolean_to_string( + do_not_share_warning_enabled + ), + "CustomCodeEnabled": serialize.boolean_to_string(custom_code_enabled), + "Push.IncludeDate": serialize.boolean_to_string(push_include_date), + "Push.ApnCredentialSid": push_apn_credential_sid, + "Push.FcmCredentialSid": push_fcm_credential_sid, + "Totp.Issuer": totp_issuer, + "Totp.TimeStep": totp_time_step, + "Totp.CodeLength": totp_code_length, + "Totp.Skew": totp_skew, + "DefaultTemplateSid": default_template_sid, + "Whatsapp.MsgServiceSid": whatsapp_msg_service_sid, + "Whatsapp.From": whatsapp_from, + "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( + verify_event_subscription_enabled + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def access_tokens(self) -> AccessTokenList: + """ + Access the access_tokens + """ + if self._access_tokens is None: + self._access_tokens = AccessTokenList( + self._version, + self._solution["sid"], + ) + return self._access_tokens + + @property + def entities(self) -> EntityList: + """ + Access the entities + """ + if self._entities is None: + self._entities = EntityList( + self._version, + self._solution["sid"], + ) + return self._entities + + @property + def messaging_configurations(self) -> MessagingConfigurationList: + """ + Access the messaging_configurations + """ + if self._messaging_configurations is None: + self._messaging_configurations = MessagingConfigurationList( + self._version, + self._solution["sid"], + ) + return self._messaging_configurations + + @property + def rate_limits(self) -> RateLimitList: + """ + Access the rate_limits + """ + if self._rate_limits is None: + self._rate_limits = RateLimitList( + self._version, + self._solution["sid"], + ) + return self._rate_limits + + @property + def verifications(self) -> VerificationList: + """ + Access the verifications + """ + if self._verifications is None: + self._verifications = VerificationList( + self._version, + self._solution["sid"], + ) + return self._verifications + + @property + def verification_checks(self) -> VerificationCheckList: + """ + Access the verification_checks + """ + if self._verification_checks is None: + self._verification_checks = VerificationCheckList( + self._version, + self._solution["sid"], + ) + return self._verification_checks + + @property + def webhooks(self) -> WebhookList: + """ + Access the webhooks + """ + if self._webhooks is None: + self._webhooks = WebhookList( + self._version, + self._solution["sid"], + ) + return self._webhooks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.ServiceContext {}>".format(context) + + +class ServicePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ServiceInstance: + """ + Build an instance of ServiceInstance + + :param payload: Payload response from the API + """ + return ServiceInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.ServicePage>" + + +class ServiceList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ServiceList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Services" + + def create( + self, + friendly_name: str, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a security warning at the end of an SMS verification body. Disabled by default and applies only to SMS. Example SMS body: `Your AppName verification code is: 1234. Don’t share this code with anyone; our employees will never ask for the code` + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. This timestamp value is the same one as the one found in `date_created`, please use that one instead. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. Defaults to the service friendly name if not provided. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the Messaging Service containing WhatsApp Sender(s) that Verify will use to send WhatsApp messages to your users. + :param whatsapp_from: The number to use as the WhatsApp Sender that Verify will use to send WhatsApp messages to your users.This WhatsApp Sender must be associated with a Messaging Service SID. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "CodeLength": code_length, + "LookupEnabled": serialize.boolean_to_string(lookup_enabled), + "SkipSmsToLandlines": serialize.boolean_to_string( + skip_sms_to_landlines + ), + "DtmfInputRequired": serialize.boolean_to_string(dtmf_input_required), + "TtsName": tts_name, + "Psd2Enabled": serialize.boolean_to_string(psd2_enabled), + "DoNotShareWarningEnabled": serialize.boolean_to_string( + do_not_share_warning_enabled + ), + "CustomCodeEnabled": serialize.boolean_to_string(custom_code_enabled), + "Push.IncludeDate": serialize.boolean_to_string(push_include_date), + "Push.ApnCredentialSid": push_apn_credential_sid, + "Push.FcmCredentialSid": push_fcm_credential_sid, + "Totp.Issuer": totp_issuer, + "Totp.TimeStep": totp_time_step, + "Totp.CodeLength": totp_code_length, + "Totp.Skew": totp_skew, + "DefaultTemplateSid": default_template_sid, + "Whatsapp.MsgServiceSid": whatsapp_msg_service_sid, + "Whatsapp.From": whatsapp_from, + "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( + verify_event_subscription_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + code_length: Union[int, object] = values.unset, + lookup_enabled: Union[bool, object] = values.unset, + skip_sms_to_landlines: Union[bool, object] = values.unset, + dtmf_input_required: Union[bool, object] = values.unset, + tts_name: Union[str, object] = values.unset, + psd2_enabled: Union[bool, object] = values.unset, + do_not_share_warning_enabled: Union[bool, object] = values.unset, + custom_code_enabled: Union[bool, object] = values.unset, + push_include_date: Union[bool, object] = values.unset, + push_apn_credential_sid: Union[str, object] = values.unset, + push_fcm_credential_sid: Union[str, object] = values.unset, + totp_issuer: Union[str, object] = values.unset, + totp_time_step: Union[int, object] = values.unset, + totp_code_length: Union[int, object] = values.unset, + totp_skew: Union[int, object] = values.unset, + default_template_sid: Union[str, object] = values.unset, + whatsapp_msg_service_sid: Union[str, object] = values.unset, + whatsapp_from: Union[str, object] = values.unset, + verify_event_subscription_enabled: Union[bool, object] = values.unset, + ) -> ServiceInstance: + """ + Asynchronously create the ServiceInstance + + :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 32 characters long. **This value should not contain PII.** + :param code_length: The length of the verification code to generate. Must be an integer value between 4 and 10, inclusive. + :param lookup_enabled: Whether to perform a lookup with each verification started and return info about the phone number. + :param skip_sms_to_landlines: Whether to skip sending SMS verifications to landlines. Requires `lookup_enabled`. + :param dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. + :param tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. + :param psd2_enabled: Whether to pass PSD2 transaction parameters when starting a verification. + :param do_not_share_warning_enabled: Whether to add a security warning at the end of an SMS verification body. Disabled by default and applies only to SMS. Example SMS body: `Your AppName verification code is: 1234. Don’t share this code with anyone; our employees will never ask for the code` + :param custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. + :param push_include_date: Optional configuration for the Push factors. If true, include the date in the Challenge's response. Otherwise, the date is omitted from the response. See [Challenge](https://www.twilio.com/docs/verify/api/challenge) resource’s details parameter for more info. Default: false. **Deprecated** do not use this parameter. This timestamp value is the same one as the one found in `date_created`, please use that one instead. + :param push_apn_credential_sid: Optional configuration for the Push factors. Set the APN Credential for this service. This will allow to send push notifications to iOS devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param push_fcm_credential_sid: Optional configuration for the Push factors. Set the FCM Credential for this service. This will allow to send push notifications to Android devices. See [Credential Resource](https://www.twilio.com/docs/notify/api/credential-resource) + :param totp_issuer: Optional configuration for the TOTP factors. Set TOTP Issuer for this service. This will allow to configure the issuer of the TOTP URI. Defaults to the service friendly name if not provided. + :param totp_time_step: Optional configuration for the TOTP factors. Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. Defaults to 30 seconds + :param totp_code_length: Optional configuration for the TOTP factors. Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. Defaults to 6 + :param totp_skew: Optional configuration for the TOTP factors. The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. Defaults to 1 + :param default_template_sid: The default message [template](https://www.twilio.com/docs/verify/api/templates). Will be used for all SMS verifications unless explicitly overriden. SMS channel only. + :param whatsapp_msg_service_sid: The SID of the Messaging Service containing WhatsApp Sender(s) that Verify will use to send WhatsApp messages to your users. + :param whatsapp_from: The number to use as the WhatsApp Sender that Verify will use to send WhatsApp messages to your users.This WhatsApp Sender must be associated with a Messaging Service SID. + :param verify_event_subscription_enabled: Whether to allow verifications from the service to reach the stream-events sinks if configured + + :returns: The created ServiceInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "CodeLength": code_length, + "LookupEnabled": serialize.boolean_to_string(lookup_enabled), + "SkipSmsToLandlines": serialize.boolean_to_string( + skip_sms_to_landlines + ), + "DtmfInputRequired": serialize.boolean_to_string(dtmf_input_required), + "TtsName": tts_name, + "Psd2Enabled": serialize.boolean_to_string(psd2_enabled), + "DoNotShareWarningEnabled": serialize.boolean_to_string( + do_not_share_warning_enabled + ), + "CustomCodeEnabled": serialize.boolean_to_string(custom_code_enabled), + "Push.IncludeDate": serialize.boolean_to_string(push_include_date), + "Push.ApnCredentialSid": push_apn_credential_sid, + "Push.FcmCredentialSid": push_fcm_credential_sid, + "Totp.Issuer": totp_issuer, + "Totp.TimeStep": totp_time_step, + "Totp.CodeLength": totp_code_length, + "Totp.Skew": totp_skew, + "DefaultTemplateSid": default_template_sid, + "Whatsapp.MsgServiceSid": whatsapp_msg_service_sid, + "Whatsapp.From": whatsapp_from, + "VerifyEventSubscriptionEnabled": serialize.boolean_to_string( + verify_event_subscription_enabled + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ServiceInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ServiceInstance]: + """ + Streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ServiceInstance]: + """ + Asynchronously streams ServiceInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ServiceInstance]: + """ + Asynchronously lists ServiceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ServicePage: + """ + Asynchronously retrieve a single page of ServiceInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ServiceInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ServicePage(self._version, response) + + def get_page(self, target_url: str) -> ServicePage: + """ + Retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ServicePage(self._version, response) + + async def get_page_async(self, target_url: str) -> ServicePage: + """ + Asynchronously retrieve a specific page of ServiceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ServiceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ServicePage(self._version, response) + + def get(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: The Twilio-provided string that uniquely identifies the Service resource to update. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.ServiceList>" diff --git a/twilio/rest/verify/v2/service/access_token.py b/twilio/rest/verify/v2/service/access_token.py new file mode 100644 index 0000000000..45a0094e52 --- /dev/null +++ b/twilio/rest/verify/v2/service/access_token.py @@ -0,0 +1,315 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class AccessTokenInstance(InstanceResource): + + class FactorTypes(object): + PUSH = "push" + + """ + :ivar sid: A 34 character string that uniquely identifies this Access Token. + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Verify Service. + :ivar entity_identity: The unique external identifier for the Entity of the Service. + :ivar factor_type: + :ivar factor_friendly_name: A human readable description of this factor, up to 64 characters. For a push factor, this can be the device's name. + :ivar token: The access token generated for enrollment, this is an encrypted json web token. + :ivar url: The URL of this resource. + :ivar ttl: How long, in seconds, the access token is valid. Max: 5 minutes + :ivar date_created: The date that this access token was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.entity_identity: Optional[str] = payload.get("entity_identity") + self.factor_type: Optional["AccessTokenInstance.FactorTypes"] = payload.get( + "factor_type" + ) + self.factor_friendly_name: Optional[str] = payload.get("factor_friendly_name") + self.token: Optional[str] = payload.get("token") + self.url: Optional[str] = payload.get("url") + self.ttl: Optional[int] = deserialize.integer(payload.get("ttl")) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[AccessTokenContext] = None + + @property + def _proxy(self) -> "AccessTokenContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AccessTokenContext for this AccessTokenInstance + """ + if self._context is None: + self._context = AccessTokenContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AccessTokenInstance": + """ + Fetch the AccessTokenInstance + + + :returns: The fetched AccessTokenInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AccessTokenInstance": + """ + Asynchronous coroutine to fetch the AccessTokenInstance + + + :returns: The fetched AccessTokenInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.AccessTokenInstance {}>".format(context) + + +class AccessTokenContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the AccessTokenContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param sid: A 34 character string that uniquely identifies this Access Token. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/AccessTokens/{sid}".format( + **self._solution + ) + + def fetch(self) -> AccessTokenInstance: + """ + Fetch the AccessTokenInstance + + + :returns: The fetched AccessTokenInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return AccessTokenInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> AccessTokenInstance: + """ + Asynchronous coroutine to fetch the AccessTokenInstance + + + :returns: The fetched AccessTokenInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return AccessTokenInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.AccessTokenContext {}>".format(context) + + +class AccessTokenList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the AccessTokenList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/AccessTokens".format(**self._solution) + + def create( + self, + identity: str, + factor_type: "AccessTokenInstance.FactorTypes", + factor_friendly_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> AccessTokenInstance: + """ + Create the AccessTokenInstance + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, and generated by your external system, such as your user's UUID, GUID, or SID. + :param factor_type: + :param factor_friendly_name: The friendly name of the factor that is going to be created with this access token + :param ttl: How long, in seconds, the access token is valid. Can be an integer between 60 and 300. Default is 60. + + :returns: The created AccessTokenInstance + """ + + data = values.of( + { + "Identity": identity, + "FactorType": factor_type, + "FactorFriendlyName": factor_friendly_name, + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccessTokenInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + identity: str, + factor_type: "AccessTokenInstance.FactorTypes", + factor_friendly_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> AccessTokenInstance: + """ + Asynchronously create the AccessTokenInstance + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, and generated by your external system, such as your user's UUID, GUID, or SID. + :param factor_type: + :param factor_friendly_name: The friendly name of the factor that is going to be created with this access token + :param ttl: How long, in seconds, the access token is valid. Can be an integer between 60 and 300. Default is 60. + + :returns: The created AccessTokenInstance + """ + + data = values.of( + { + "Identity": identity, + "FactorType": factor_type, + "FactorFriendlyName": factor_friendly_name, + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AccessTokenInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def get(self, sid: str) -> AccessTokenContext: + """ + Constructs a AccessTokenContext + + :param sid: A 34 character string that uniquely identifies this Access Token. + """ + return AccessTokenContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> AccessTokenContext: + """ + Constructs a AccessTokenContext + + :param sid: A 34 character string that uniquely identifies this Access Token. + """ + return AccessTokenContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.AccessTokenList>" diff --git a/twilio/rest/verify/v2/service/entity/__init__.py b/twilio/rest/verify/v2/service/entity/__init__.py new file mode 100644 index 0000000000..fa4bc1df12 --- /dev/null +++ b/twilio/rest/verify/v2/service/entity/__init__.py @@ -0,0 +1,609 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.verify.v2.service.entity.challenge import ChallengeList +from twilio.rest.verify.v2.service.entity.factor import FactorList +from twilio.rest.verify.v2.service.entity.new_factor import NewFactorList + + +class EntityInstance(InstanceResource): + """ + :ivar sid: A 34 character string that uniquely identifies this Entity. + :ivar identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Service. + :ivar date_created: The date that this Entity was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this Entity was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The URL of this resource. + :ivar links: Contains a dictionary of URL links to nested resources of this Entity. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + identity: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.identity: Optional[str] = payload.get("identity") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "identity": identity or self.identity, + } + self._context: Optional[EntityContext] = None + + @property + def _proxy(self) -> "EntityContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: EntityContext for this EntityInstance + """ + if self._context is None: + self._context = EntityContext( + self._version, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the EntityInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EntityInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "EntityInstance": + """ + Fetch the EntityInstance + + + :returns: The fetched EntityInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "EntityInstance": + """ + Asynchronous coroutine to fetch the EntityInstance + + + :returns: The fetched EntityInstance + """ + return await self._proxy.fetch_async() + + @property + def challenges(self) -> ChallengeList: + """ + Access the challenges + """ + return self._proxy.challenges + + @property + def factors(self) -> FactorList: + """ + Access the factors + """ + return self._proxy.factors + + @property + def new_factors(self) -> NewFactorList: + """ + Access the new_factors + """ + return self._proxy.new_factors + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.EntityInstance {}>".format(context) + + +class EntityContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, identity: str): + """ + Initialize the EntityContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "identity": identity, + } + self._uri = "/Services/{service_sid}/Entities/{identity}".format( + **self._solution + ) + + self._challenges: Optional[ChallengeList] = None + self._factors: Optional[FactorList] = None + self._new_factors: Optional[NewFactorList] = None + + def delete(self) -> bool: + """ + Deletes the EntityInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the EntityInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> EntityInstance: + """ + Fetch the EntityInstance + + + :returns: The fetched EntityInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return EntityInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + async def fetch_async(self) -> EntityInstance: + """ + Asynchronous coroutine to fetch the EntityInstance + + + :returns: The fetched EntityInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return EntityInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + @property + def challenges(self) -> ChallengeList: + """ + Access the challenges + """ + if self._challenges is None: + self._challenges = ChallengeList( + self._version, + self._solution["service_sid"], + self._solution["identity"], + ) + return self._challenges + + @property + def factors(self) -> FactorList: + """ + Access the factors + """ + if self._factors is None: + self._factors = FactorList( + self._version, + self._solution["service_sid"], + self._solution["identity"], + ) + return self._factors + + @property + def new_factors(self) -> NewFactorList: + """ + Access the new_factors + """ + if self._new_factors is None: + self._new_factors = NewFactorList( + self._version, + self._solution["service_sid"], + self._solution["identity"], + ) + return self._new_factors + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.EntityContext {}>".format(context) + + +class EntityPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> EntityInstance: + """ + Build an instance of EntityInstance + + :param payload: Payload response from the API + """ + return EntityInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.EntityPage>" + + +class EntityList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the EntityList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Entities".format(**self._solution) + + def create(self, identity: str) -> EntityInstance: + """ + Create the EntityInstance + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + + :returns: The created EntityInstance + """ + + data = values.of( + { + "Identity": identity, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EntityInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async(self, identity: str) -> EntityInstance: + """ + Asynchronously create the EntityInstance + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + + :returns: The created EntityInstance + """ + + data = values.of( + { + "Identity": identity, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return EntityInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[EntityInstance]: + """ + Streams EntityInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[EntityInstance]: + """ + Asynchronously streams EntityInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EntityInstance]: + """ + Lists EntityInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[EntityInstance]: + """ + Asynchronously lists EntityInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EntityPage: + """ + Retrieve a single page of EntityInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EntityInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EntityPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> EntityPage: + """ + Asynchronously retrieve a single page of EntityInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of EntityInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return EntityPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> EntityPage: + """ + Retrieve a specific page of EntityInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EntityInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return EntityPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> EntityPage: + """ + Asynchronously retrieve a specific page of EntityInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of EntityInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return EntityPage(self._version, response, self._solution) + + def get(self, identity: str) -> EntityContext: + """ + Constructs a EntityContext + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + """ + return EntityContext( + self._version, service_sid=self._solution["service_sid"], identity=identity + ) + + def __call__(self, identity: str) -> EntityContext: + """ + Constructs a EntityContext + + :param identity: The unique external identifier for the Entity of the Service. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + """ + return EntityContext( + self._version, service_sid=self._solution["service_sid"], identity=identity + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.EntityList>" diff --git a/twilio/rest/verify/v2/service/entity/challenge/__init__.py b/twilio/rest/verify/v2/service/entity/challenge/__init__.py new file mode 100644 index 0000000000..146a95d959 --- /dev/null +++ b/twilio/rest/verify/v2/service/entity/challenge/__init__.py @@ -0,0 +1,810 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.verify.v2.service.entity.challenge.notification import NotificationList + + +class ChallengeInstance(InstanceResource): + + class ChallengeReasons(object): + NONE = "none" + NOT_NEEDED = "not_needed" + NOT_REQUESTED = "not_requested" + + class ChallengeStatuses(object): + PENDING = "pending" + EXPIRED = "expired" + APPROVED = "approved" + DENIED = "denied" + + class FactorTypes(object): + PUSH = "push" + TOTP = "totp" + + class ListOrders(object): + ASC = "asc" + DESC = "desc" + + """ + :ivar sid: A 34 character string that uniquely identifies this Challenge. + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Service. + :ivar entity_sid: The unique SID identifier of the Entity. + :ivar identity: Customer unique identity for the Entity owner of the Challenge. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + :ivar factor_sid: The unique SID identifier of the Factor. + :ivar date_created: The date that this Challenge was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this Challenge was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_responded: The date that this Challenge was responded, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar expiration_date: The date-time when this Challenge expires, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. The default value is five (5) minutes after Challenge creation. The max value is sixty (60) minutes after creation. + :ivar status: + :ivar responded_reason: + :ivar details: Details provided to give context about the Challenge. Intended to be shown to the end user. + :ivar hidden_details: Details provided to give context about the Challenge. Intended to be hidden from the end user. It must be a stringified JSON with only strings values eg. `{\"ip\": \"172.168.1.234\"}` + :ivar metadata: Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\"os\": \"Android\"}`. Can be up to 1024 characters in length. + :ivar factor_type: + :ivar url: The URL of this resource. + :ivar links: Contains a dictionary of URL links to nested resources of this Challenge. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + identity: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.entity_sid: Optional[str] = payload.get("entity_sid") + self.identity: Optional[str] = payload.get("identity") + self.factor_sid: Optional[str] = payload.get("factor_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.date_responded: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_responded") + ) + self.expiration_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("expiration_date") + ) + self.status: Optional["ChallengeInstance.ChallengeStatuses"] = payload.get( + "status" + ) + self.responded_reason: Optional["ChallengeInstance.ChallengeReasons"] = ( + payload.get("responded_reason") + ) + self.details: Optional[Dict[str, object]] = payload.get("details") + self.hidden_details: Optional[Dict[str, object]] = payload.get("hidden_details") + self.metadata: Optional[Dict[str, object]] = payload.get("metadata") + self.factor_type: Optional["ChallengeInstance.FactorTypes"] = payload.get( + "factor_type" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "identity": identity, + "sid": sid or self.sid, + } + self._context: Optional[ChallengeContext] = None + + @property + def _proxy(self) -> "ChallengeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ChallengeContext for this ChallengeInstance + """ + if self._context is None: + self._context = ChallengeContext( + self._version, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ChallengeInstance": + """ + Fetch the ChallengeInstance + + + :returns: The fetched ChallengeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ChallengeInstance": + """ + Asynchronous coroutine to fetch the ChallengeInstance + + + :returns: The fetched ChallengeInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> "ChallengeInstance": + """ + Update the ChallengeInstance + + :param auth_payload: The optional payload needed to verify the Challenge. E.g., a TOTP would use the numeric code. For `TOTP` this value must be between 3 and 8 characters long. For `Push` this value can be up to 5456 characters in length + :param metadata: Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: The updated ChallengeInstance + """ + return self._proxy.update( + auth_payload=auth_payload, + metadata=metadata, + ) + + async def update_async( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> "ChallengeInstance": + """ + Asynchronous coroutine to update the ChallengeInstance + + :param auth_payload: The optional payload needed to verify the Challenge. E.g., a TOTP would use the numeric code. For `TOTP` this value must be between 3 and 8 characters long. For `Push` this value can be up to 5456 characters in length + :param metadata: Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: The updated ChallengeInstance + """ + return await self._proxy.update_async( + auth_payload=auth_payload, + metadata=metadata, + ) + + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + return self._proxy.notifications + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.ChallengeInstance {}>".format(context) + + +class ChallengeContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, identity: str, sid: str): + """ + Initialize the ChallengeContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param identity: Customer unique identity for the Entity owner of the Challenge. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + :param sid: A 34 character string that uniquely identifies this Challenge. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "identity": identity, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/Entities/{identity}/Challenges/{sid}".format( + **self._solution + ) + ) + + self._notifications: Optional[NotificationList] = None + + def fetch(self) -> ChallengeInstance: + """ + Fetch the ChallengeInstance + + + :returns: The fetched ChallengeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ChallengeInstance: + """ + Asynchronous coroutine to fetch the ChallengeInstance + + + :returns: The fetched ChallengeInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + def update( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> ChallengeInstance: + """ + Update the ChallengeInstance + + :param auth_payload: The optional payload needed to verify the Challenge. E.g., a TOTP would use the numeric code. For `TOTP` this value must be between 3 and 8 characters long. For `Push` this value can be up to 5456 characters in length + :param metadata: Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: The updated ChallengeInstance + """ + + data = values.of( + { + "AuthPayload": auth_payload, + "Metadata": serialize.object(metadata), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + auth_payload: Union[str, object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> ChallengeInstance: + """ + Asynchronous coroutine to update the ChallengeInstance + + :param auth_payload: The optional payload needed to verify the Challenge. E.g., a TOTP would use the numeric code. For `TOTP` this value must be between 3 and 8 characters long. For `Push` this value can be up to 5456 characters in length + :param metadata: Custom metadata associated with the challenge. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: The updated ChallengeInstance + """ + + data = values.of( + { + "AuthPayload": auth_payload, + "Metadata": serialize.object(metadata), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + @property + def notifications(self) -> NotificationList: + """ + Access the notifications + """ + if self._notifications is None: + self._notifications = NotificationList( + self._version, + self._solution["service_sid"], + self._solution["identity"], + self._solution["sid"], + ) + return self._notifications + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.ChallengeContext {}>".format(context) + + +class ChallengePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChallengeInstance: + """ + Build an instance of ChallengeInstance + + :param payload: Payload response from the API + """ + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.ChallengePage>" + + +class ChallengeList(ListResource): + + def __init__(self, version: Version, service_sid: str, identity: str): + """ + Initialize the ChallengeList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param identity: Customer unique identity for the Entity owner of the Challenge. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "identity": identity, + } + self._uri = "/Services/{service_sid}/Entities/{identity}/Challenges".format( + **self._solution + ) + + def create( + self, + factor_sid: str, + expiration_date: Union[datetime, object] = values.unset, + details_message: Union[str, object] = values.unset, + details_fields: Union[List[object], object] = values.unset, + hidden_details: Union[object, object] = values.unset, + auth_payload: Union[str, object] = values.unset, + ) -> ChallengeInstance: + """ + Create the ChallengeInstance + + :param factor_sid: The unique SID identifier of the Factor. + :param expiration_date: The date-time when this Challenge expires, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. The default value is five (5) minutes after Challenge creation. The max value is sixty (60) minutes after creation. + :param details_message: Shown to the user when the push notification arrives. Required when `factor_type` is `push`. Can be up to 256 characters in length + :param details_fields: A list of objects that describe the Fields included in the Challenge. Each object contains the label and value of the field, the label can be up to 36 characters in length and the value can be up to 128 characters in length. Used when `factor_type` is `push`. There can be up to 20 details fields. + :param hidden_details: Details provided to give context about the Challenge. Not shown to the end user. It must be a stringified JSON with only strings values eg. `{\\\"ip\\\": \\\"172.168.1.234\\\"}`. Can be up to 1024 characters in length + :param auth_payload: Optional payload used to verify the Challenge upon creation. Only used with a Factor of type `totp` to carry the TOTP code that needs to be verified. For `TOTP` this value must be between 3 and 8 characters long. + + :returns: The created ChallengeInstance + """ + + data = values.of( + { + "FactorSid": factor_sid, + "ExpirationDate": serialize.iso8601_datetime(expiration_date), + "Details.Message": details_message, + "Details.Fields": serialize.map( + details_fields, lambda e: serialize.object(e) + ), + "HiddenDetails": serialize.object(hidden_details), + "AuthPayload": auth_payload, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + async def create_async( + self, + factor_sid: str, + expiration_date: Union[datetime, object] = values.unset, + details_message: Union[str, object] = values.unset, + details_fields: Union[List[object], object] = values.unset, + hidden_details: Union[object, object] = values.unset, + auth_payload: Union[str, object] = values.unset, + ) -> ChallengeInstance: + """ + Asynchronously create the ChallengeInstance + + :param factor_sid: The unique SID identifier of the Factor. + :param expiration_date: The date-time when this Challenge expires, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. The default value is five (5) minutes after Challenge creation. The max value is sixty (60) minutes after creation. + :param details_message: Shown to the user when the push notification arrives. Required when `factor_type` is `push`. Can be up to 256 characters in length + :param details_fields: A list of objects that describe the Fields included in the Challenge. Each object contains the label and value of the field, the label can be up to 36 characters in length and the value can be up to 128 characters in length. Used when `factor_type` is `push`. There can be up to 20 details fields. + :param hidden_details: Details provided to give context about the Challenge. Not shown to the end user. It must be a stringified JSON with only strings values eg. `{\\\"ip\\\": \\\"172.168.1.234\\\"}`. Can be up to 1024 characters in length + :param auth_payload: Optional payload used to verify the Challenge upon creation. Only used with a Factor of type `totp` to carry the TOTP code that needs to be verified. For `TOTP` this value must be between 3 and 8 characters long. + + :returns: The created ChallengeInstance + """ + + data = values.of( + { + "FactorSid": factor_sid, + "ExpirationDate": serialize.iso8601_datetime(expiration_date), + "Details.Message": details_message, + "Details.Fields": serialize.map( + details_fields, lambda e: serialize.object(e) + ), + "HiddenDetails": serialize.object(hidden_details), + "AuthPayload": auth_payload, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + def stream( + self, + factor_sid: Union[str, object] = values.unset, + status: Union["ChallengeInstance.ChallengeStatuses", object] = values.unset, + order: Union["ChallengeInstance.ListOrders", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ChallengeInstance]: + """ + Streams ChallengeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str factor_sid: The unique SID identifier of the Factor. + :param "ChallengeInstance.ChallengeStatuses" status: The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. + :param "ChallengeInstance.ListOrders" order: The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + factor_sid=factor_sid, + status=status, + order=order, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + factor_sid: Union[str, object] = values.unset, + status: Union["ChallengeInstance.ChallengeStatuses", object] = values.unset, + order: Union["ChallengeInstance.ListOrders", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ChallengeInstance]: + """ + Asynchronously streams ChallengeInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str factor_sid: The unique SID identifier of the Factor. + :param "ChallengeInstance.ChallengeStatuses" status: The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. + :param "ChallengeInstance.ListOrders" order: The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + factor_sid=factor_sid, + status=status, + order=order, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + factor_sid: Union[str, object] = values.unset, + status: Union["ChallengeInstance.ChallengeStatuses", object] = values.unset, + order: Union["ChallengeInstance.ListOrders", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChallengeInstance]: + """ + Lists ChallengeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str factor_sid: The unique SID identifier of the Factor. + :param "ChallengeInstance.ChallengeStatuses" status: The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. + :param "ChallengeInstance.ListOrders" order: The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + factor_sid=factor_sid, + status=status, + order=order, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + factor_sid: Union[str, object] = values.unset, + status: Union["ChallengeInstance.ChallengeStatuses", object] = values.unset, + order: Union["ChallengeInstance.ListOrders", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ChallengeInstance]: + """ + Asynchronously lists ChallengeInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str factor_sid: The unique SID identifier of the Factor. + :param "ChallengeInstance.ChallengeStatuses" status: The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. + :param "ChallengeInstance.ListOrders" order: The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + factor_sid=factor_sid, + status=status, + order=order, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + factor_sid: Union[str, object] = values.unset, + status: Union["ChallengeInstance.ChallengeStatuses", object] = values.unset, + order: Union["ChallengeInstance.ListOrders", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChallengePage: + """ + Retrieve a single page of ChallengeInstance records from the API. + Request is executed immediately + + :param factor_sid: The unique SID identifier of the Factor. + :param status: The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. + :param order: The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChallengeInstance + """ + data = values.of( + { + "FactorSid": factor_sid, + "Status": status, + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChallengePage(self._version, response, self._solution) + + async def page_async( + self, + factor_sid: Union[str, object] = values.unset, + status: Union["ChallengeInstance.ChallengeStatuses", object] = values.unset, + order: Union["ChallengeInstance.ListOrders", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChallengePage: + """ + Asynchronously retrieve a single page of ChallengeInstance records from the API. + Request is executed immediately + + :param factor_sid: The unique SID identifier of the Factor. + :param status: The Status of the Challenges to fetch. One of `pending`, `expired`, `approved` or `denied`. + :param order: The desired sort order of the Challenges list. One of `asc` or `desc` for ascending and descending respectively. Defaults to `asc`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ChallengeInstance + """ + data = values.of( + { + "FactorSid": factor_sid, + "Status": status, + "Order": order, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ChallengePage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ChallengePage: + """ + Retrieve a specific page of ChallengeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChallengeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChallengePage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ChallengePage: + """ + Asynchronously retrieve a specific page of ChallengeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChallengeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChallengePage(self._version, response, self._solution) + + def get(self, sid: str) -> ChallengeContext: + """ + Constructs a ChallengeContext + + :param sid: A 34 character string that uniquely identifies this Challenge. + """ + return ChallengeContext( + self._version, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=sid, + ) + + def __call__(self, sid: str) -> ChallengeContext: + """ + Constructs a ChallengeContext + + :param sid: A 34 character string that uniquely identifies this Challenge. + """ + return ChallengeContext( + self._version, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.ChallengeList>" diff --git a/twilio/rest/verify/v2/service/entity/challenge/notification.py b/twilio/rest/verify/v2/service/entity/challenge/notification.py new file mode 100644 index 0000000000..3802cc1a08 --- /dev/null +++ b/twilio/rest/verify/v2/service/entity/challenge/notification.py @@ -0,0 +1,173 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NotificationInstance(InstanceResource): + """ + :ivar sid: A 34 character string that uniquely identifies this Notification. + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Service. + :ivar entity_sid: The unique SID identifier of the Entity. + :ivar identity: Customer unique identity for the Entity owner of the Challenge. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + :ivar challenge_sid: The unique SID identifier of the Challenge. + :ivar priority: The priority of the notification. For `push` Challenges it's always `high` which sends the notification immediately, and can wake up a sleeping device. + :ivar ttl: How long, in seconds, the notification is valid. Max: 5 minutes + :ivar date_created: The date that this Notification was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + identity: str, + challenge_sid: str, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.entity_sid: Optional[str] = payload.get("entity_sid") + self.identity: Optional[str] = payload.get("identity") + self.challenge_sid: Optional[str] = payload.get("challenge_sid") + self.priority: Optional[str] = payload.get("priority") + self.ttl: Optional[int] = deserialize.integer(payload.get("ttl")) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + + self._solution = { + "service_sid": service_sid, + "identity": identity, + "challenge_sid": challenge_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.NotificationInstance {}>".format(context) + + +class NotificationList(ListResource): + + def __init__( + self, version: Version, service_sid: str, identity: str, challenge_sid: str + ): + """ + Initialize the NotificationList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param identity: Customer unique identity for the Entity owner of the Challenge. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + :param challenge_sid: The unique SID identifier of the Challenge. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "identity": identity, + "challenge_sid": challenge_sid, + } + self._uri = "/Services/{service_sid}/Entities/{identity}/Challenges/{challenge_sid}/Notifications".format( + **self._solution + ) + + def create(self, ttl: Union[int, object] = values.unset) -> NotificationInstance: + """ + Create the NotificationInstance + + :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 300. Default is 300. Delivery is attempted until the TTL elapses, even if the device is offline. 0 means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. + + :returns: The created NotificationInstance + """ + + data = values.of( + { + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NotificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + challenge_sid=self._solution["challenge_sid"], + ) + + async def create_async( + self, ttl: Union[int, object] = values.unset + ) -> NotificationInstance: + """ + Asynchronously create the NotificationInstance + + :param ttl: How long, in seconds, the notification is valid. Can be an integer between 0 and 300. Default is 300. Delivery is attempted until the TTL elapses, even if the device is offline. 0 means that the notification delivery is attempted immediately, only once, and is not stored for future delivery. + + :returns: The created NotificationInstance + """ + + data = values.of( + { + "Ttl": ttl, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NotificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + challenge_sid=self._solution["challenge_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.NotificationList>" diff --git a/twilio/rest/verify/v2/service/entity/factor.py b/twilio/rest/verify/v2/service/entity/factor.py new file mode 100644 index 0000000000..7bf91cd870 --- /dev/null +++ b/twilio/rest/verify/v2/service/entity/factor.py @@ -0,0 +1,728 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class FactorInstance(InstanceResource): + + class FactorStatuses(object): + UNVERIFIED = "unverified" + VERIFIED = "verified" + + class FactorTypes(object): + PUSH = "push" + TOTP = "totp" + + class TotpAlgorithms(object): + SHA1 = "sha1" + SHA256 = "sha256" + SHA512 = "sha512" + + """ + :ivar sid: A 34 character string that uniquely identifies this Factor. + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Service. + :ivar entity_sid: The unique SID identifier of the Entity. + :ivar identity: Customer unique identity for the Entity owner of the Factor. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + :ivar date_created: The date that this Factor was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this Factor was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar friendly_name: A human readable description of this resource, up to 64 characters. For a push factor, this can be the device's name. + :ivar status: + :ivar factor_type: + :ivar config: An object that contains configurations specific to a `factor_type`. + :ivar metadata: Custom metadata associated with the factor. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\"os\": \"Android\"}`. Can be up to 1024 characters in length. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + identity: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.entity_sid: Optional[str] = payload.get("entity_sid") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["FactorInstance.FactorStatuses"] = payload.get("status") + self.factor_type: Optional["FactorInstance.FactorTypes"] = payload.get( + "factor_type" + ) + self.config: Optional[Dict[str, object]] = payload.get("config") + self.metadata: Optional[Dict[str, object]] = payload.get("metadata") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "identity": identity, + "sid": sid or self.sid, + } + self._context: Optional[FactorContext] = None + + @property + def _proxy(self) -> "FactorContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FactorContext for this FactorInstance + """ + if self._context is None: + self._context = FactorContext( + self._version, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the FactorInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FactorInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "FactorInstance": + """ + Fetch the FactorInstance + + + :returns: The fetched FactorInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FactorInstance": + """ + Asynchronous coroutine to fetch the FactorInstance + + + :returns: The fetched FactorInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + auth_payload: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, + config_notification_platform: Union[str, object] = values.unset, + ) -> "FactorInstance": + """ + Update the FactorInstance + + :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. + :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. + :param config_sdk_version: The Verify Push SDK version used to configure the factor + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive + :param config_alg: + :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. + + :returns: The updated FactorInstance + """ + return self._proxy.update( + auth_payload=auth_payload, + friendly_name=friendly_name, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + config_notification_platform=config_notification_platform, + ) + + async def update_async( + self, + auth_payload: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, + config_notification_platform: Union[str, object] = values.unset, + ) -> "FactorInstance": + """ + Asynchronous coroutine to update the FactorInstance + + :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. + :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. + :param config_sdk_version: The Verify Push SDK version used to configure the factor + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive + :param config_alg: + :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. + + :returns: The updated FactorInstance + """ + return await self._proxy.update_async( + auth_payload=auth_payload, + friendly_name=friendly_name, + config_notification_token=config_notification_token, + config_sdk_version=config_sdk_version, + config_time_step=config_time_step, + config_skew=config_skew, + config_code_length=config_code_length, + config_alg=config_alg, + config_notification_platform=config_notification_platform, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.FactorInstance {}>".format(context) + + +class FactorContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, identity: str, sid: str): + """ + Initialize the FactorContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param identity: Customer unique identity for the Entity owner of the Factor. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + :param sid: A 34 character string that uniquely identifies this Factor. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "identity": identity, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Entities/{identity}/Factors/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the FactorInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the FactorInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> FactorInstance: + """ + Fetch the FactorInstance + + + :returns: The fetched FactorInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> FactorInstance: + """ + Asynchronous coroutine to fetch the FactorInstance + + + :returns: The fetched FactorInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + def update( + self, + auth_payload: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, + config_notification_platform: Union[str, object] = values.unset, + ) -> FactorInstance: + """ + Update the FactorInstance + + :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. + :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. + :param config_sdk_version: The Verify Push SDK version used to configure the factor + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive + :param config_alg: + :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. + + :returns: The updated FactorInstance + """ + + data = values.of( + { + "AuthPayload": auth_payload, + "FriendlyName": friendly_name, + "Config.NotificationToken": config_notification_token, + "Config.SdkVersion": config_sdk_version, + "Config.TimeStep": config_time_step, + "Config.Skew": config_skew, + "Config.CodeLength": config_code_length, + "Config.Alg": config_alg, + "Config.NotificationPlatform": config_notification_platform, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + auth_payload: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["FactorInstance.TotpAlgorithms", object] = values.unset, + config_notification_platform: Union[str, object] = values.unset, + ) -> FactorInstance: + """ + Asynchronous coroutine to update the FactorInstance + + :param auth_payload: The optional payload needed to verify the Factor for the first time. E.g. for a TOTP, the numeric code. + :param friendly_name: The new friendly name of this Factor. It can be up to 64 characters. + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Required when `factor_type` is `push`. If specified, this value must be between 32 and 255 characters long. + :param config_sdk_version: The Verify Push SDK version used to configure the factor + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive + :param config_alg: + :param config_notification_platform: The transport technology used to generate the Notification Token. Can be `apn`, `fcm` or `none`. Required when `factor_type` is `push`. + + :returns: The updated FactorInstance + """ + + data = values.of( + { + "AuthPayload": auth_payload, + "FriendlyName": friendly_name, + "Config.NotificationToken": config_notification_token, + "Config.SdkVersion": config_sdk_version, + "Config.TimeStep": config_time_step, + "Config.Skew": config_skew, + "Config.CodeLength": config_code_length, + "Config.Alg": config_alg, + "Config.NotificationPlatform": config_notification_platform, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.FactorContext {}>".format(context) + + +class FactorPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> FactorInstance: + """ + Build an instance of FactorInstance + + :param payload: Payload response from the API + """ + return FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.FactorPage>" + + +class FactorList(ListResource): + + def __init__(self, version: Version, service_sid: str, identity: str): + """ + Initialize the FactorList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param identity: Customer unique identity for the Entity owner of the Factors. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "identity": identity, + } + self._uri = "/Services/{service_sid}/Entities/{identity}/Factors".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[FactorInstance]: + """ + Streams FactorInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[FactorInstance]: + """ + Asynchronously streams FactorInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FactorInstance]: + """ + Lists FactorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[FactorInstance]: + """ + Asynchronously lists FactorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FactorPage: + """ + Retrieve a single page of FactorInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FactorInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FactorPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> FactorPage: + """ + Asynchronously retrieve a single page of FactorInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of FactorInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return FactorPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> FactorPage: + """ + Retrieve a specific page of FactorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FactorInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return FactorPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> FactorPage: + """ + Asynchronously retrieve a specific page of FactorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of FactorInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return FactorPage(self._version, response, self._solution) + + def get(self, sid: str) -> FactorContext: + """ + Constructs a FactorContext + + :param sid: A 34 character string that uniquely identifies this Factor. + """ + return FactorContext( + self._version, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=sid, + ) + + def __call__(self, sid: str) -> FactorContext: + """ + Constructs a FactorContext + + :param sid: A 34 character string that uniquely identifies this Factor. + """ + return FactorContext( + self._version, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.FactorList>" diff --git a/twilio/rest/verify/v2/service/entity/new_factor.py b/twilio/rest/verify/v2/service/entity/new_factor.py new file mode 100644 index 0000000000..2a2d77d512 --- /dev/null +++ b/twilio/rest/verify/v2/service/entity/new_factor.py @@ -0,0 +1,282 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class NewFactorInstance(InstanceResource): + + class FactorStatuses(object): + UNVERIFIED = "unverified" + VERIFIED = "verified" + + class FactorTypes(object): + PUSH = "push" + TOTP = "totp" + + class NotificationPlatforms(object): + APN = "apn" + FCM = "fcm" + NONE = "none" + + class TotpAlgorithms(object): + SHA1 = "sha1" + SHA256 = "sha256" + SHA512 = "sha512" + + """ + :ivar sid: A 34 character string that uniquely identifies this Factor. + :ivar account_sid: The unique SID identifier of the Account. + :ivar service_sid: The unique SID identifier of the Service. + :ivar entity_sid: The unique SID identifier of the Entity. + :ivar identity: Customer unique identity for the Entity owner of the Factor. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + :ivar binding: Contains the `factor_type` specific secret and metadata. For push, this is `binding.public_key` and `binding.alg`. For totp, this is `binding.secret` and `binding.uri`. The `binding.uri` property is generated following the [google authenticator key URI format](https://github.com/google/google-authenticator/wiki/Key-Uri-Format), and `Factor.friendly_name` is used for the “accountname” value and `Service.friendly_name` or `Service.totp.issuer` is used for the `issuer` value. The Binding property is ONLY returned upon Factor creation. + :ivar date_created: The date that this Factor was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this Factor was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar friendly_name: The friendly name of this Factor. This can be any string up to 64 characters, meant for humans to distinguish between Factors. For `factor_type` `push`, this could be a device name. For `factor_type` `totp`, this value is used as the “account name” in constructing the `binding.uri` property. At the same time, we recommend avoiding providing PII. + :ivar status: + :ivar factor_type: + :ivar config: An object that contains configurations specific to a `factor_type`. + :ivar metadata: Custom metadata associated with the factor. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\"os\": \"Android\"}`. Can be up to 1024 characters in length. + :ivar url: The URL of this resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], service_sid: str, identity: str + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.entity_sid: Optional[str] = payload.get("entity_sid") + self.identity: Optional[str] = payload.get("identity") + self.binding: Optional[Dict[str, object]] = payload.get("binding") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["NewFactorInstance.FactorStatuses"] = payload.get( + "status" + ) + self.factor_type: Optional["NewFactorInstance.FactorTypes"] = payload.get( + "factor_type" + ) + self.config: Optional[Dict[str, object]] = payload.get("config") + self.metadata: Optional[Dict[str, object]] = payload.get("metadata") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "identity": identity, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.NewFactorInstance {}>".format(context) + + +class NewFactorList(ListResource): + + def __init__(self, version: Version, service_sid: str, identity: str): + """ + Initialize the NewFactorList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param identity: Customer unique identity for the Entity owner of the Factor. This identifier should be immutable, not PII, length between 8 and 64 characters, and generated by your external system, such as your user's UUID, GUID, or SID. It can only contain dash (-) separated alphanumeric characters. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "identity": identity, + } + self._uri = "/Services/{service_sid}/Entities/{identity}/Factors".format( + **self._solution + ) + + def create( + self, + friendly_name: str, + factor_type: "NewFactorInstance.FactorTypes", + binding_alg: Union[str, object] = values.unset, + binding_public_key: Union[str, object] = values.unset, + config_app_id: Union[str, object] = values.unset, + config_notification_platform: Union[ + "NewFactorInstance.NotificationPlatforms", object + ] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + binding_secret: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["NewFactorInstance.TotpAlgorithms", object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> NewFactorInstance: + """ + Create the NewFactorInstance + + :param friendly_name: The friendly name of this Factor. This can be any string up to 64 characters, meant for humans to distinguish between Factors. For `factor_type` `push`, this could be a device name. For `factor_type` `totp`, this value is used as the “account name” in constructing the `binding.uri` property. At the same time, we recommend avoiding providing PII. + :param factor_type: + :param binding_alg: The algorithm used when `factor_type` is `push`. Algorithm supported: `ES256` + :param binding_public_key: The Ecdsa public key in PKIX, ASN.1 DER format encoded in Base64. Required when `factor_type` is `push` + :param config_app_id: The ID that uniquely identifies your app in the Google or Apple store, such as `com.example.myapp`. It can be up to 100 characters long. Required when `factor_type` is `push`. + :param config_notification_platform: + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Must be between 32 and 255 characters long. Required when `factor_type` is `push`. + :param config_sdk_version: The Verify Push SDK version used to configure the factor Required when `factor_type` is `push` + :param binding_secret: The shared secret for TOTP factors encoded in Base32. This can be provided when creating the Factor, otherwise it will be generated. Used when `factor_type` is `totp` + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. The default value is defined at the service level in the property `totp.time_step`. Defaults to 30 seconds if not configured. Used when `factor_type` is `totp` + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. The default value is defined at the service level in the property `totp.skew`. If not configured defaults to 1. Used when `factor_type` is `totp` + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. The default value is defined at the service level in the property `totp.code_length`. If not configured defaults to 6. Used when `factor_type` is `totp` + :param config_alg: + :param metadata: Custom metadata associated with the factor. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: The created NewFactorInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "FactorType": factor_type, + "Binding.Alg": binding_alg, + "Binding.PublicKey": binding_public_key, + "Config.AppId": config_app_id, + "Config.NotificationPlatform": config_notification_platform, + "Config.NotificationToken": config_notification_token, + "Config.SdkVersion": config_sdk_version, + "Binding.Secret": binding_secret, + "Config.TimeStep": config_time_step, + "Config.Skew": config_skew, + "Config.CodeLength": config_code_length, + "Config.Alg": config_alg, + "Metadata": serialize.object(metadata), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NewFactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + async def create_async( + self, + friendly_name: str, + factor_type: "NewFactorInstance.FactorTypes", + binding_alg: Union[str, object] = values.unset, + binding_public_key: Union[str, object] = values.unset, + config_app_id: Union[str, object] = values.unset, + config_notification_platform: Union[ + "NewFactorInstance.NotificationPlatforms", object + ] = values.unset, + config_notification_token: Union[str, object] = values.unset, + config_sdk_version: Union[str, object] = values.unset, + binding_secret: Union[str, object] = values.unset, + config_time_step: Union[int, object] = values.unset, + config_skew: Union[int, object] = values.unset, + config_code_length: Union[int, object] = values.unset, + config_alg: Union["NewFactorInstance.TotpAlgorithms", object] = values.unset, + metadata: Union[object, object] = values.unset, + ) -> NewFactorInstance: + """ + Asynchronously create the NewFactorInstance + + :param friendly_name: The friendly name of this Factor. This can be any string up to 64 characters, meant for humans to distinguish between Factors. For `factor_type` `push`, this could be a device name. For `factor_type` `totp`, this value is used as the “account name” in constructing the `binding.uri` property. At the same time, we recommend avoiding providing PII. + :param factor_type: + :param binding_alg: The algorithm used when `factor_type` is `push`. Algorithm supported: `ES256` + :param binding_public_key: The Ecdsa public key in PKIX, ASN.1 DER format encoded in Base64. Required when `factor_type` is `push` + :param config_app_id: The ID that uniquely identifies your app in the Google or Apple store, such as `com.example.myapp`. It can be up to 100 characters long. Required when `factor_type` is `push`. + :param config_notification_platform: + :param config_notification_token: For APN, the device token. For FCM, the registration token. It is used to send the push notifications. Must be between 32 and 255 characters long. Required when `factor_type` is `push`. + :param config_sdk_version: The Verify Push SDK version used to configure the factor Required when `factor_type` is `push` + :param binding_secret: The shared secret for TOTP factors encoded in Base32. This can be provided when creating the Factor, otherwise it will be generated. Used when `factor_type` is `totp` + :param config_time_step: Defines how often, in seconds, are TOTP codes generated. i.e, a new TOTP code is generated every time_step seconds. Must be between 20 and 60 seconds, inclusive. The default value is defined at the service level in the property `totp.time_step`. Defaults to 30 seconds if not configured. Used when `factor_type` is `totp` + :param config_skew: The number of time-steps, past and future, that are valid for validation of TOTP codes. Must be between 0 and 2, inclusive. The default value is defined at the service level in the property `totp.skew`. If not configured defaults to 1. Used when `factor_type` is `totp` + :param config_code_length: Number of digits for generated TOTP codes. Must be between 3 and 8, inclusive. The default value is defined at the service level in the property `totp.code_length`. If not configured defaults to 6. Used when `factor_type` is `totp` + :param config_alg: + :param metadata: Custom metadata associated with the factor. This is added by the Device/SDK directly to allow for the inclusion of device information. It must be a stringified JSON with only strings values eg. `{\\\"os\\\": \\\"Android\\\"}`. Can be up to 1024 characters in length. + + :returns: The created NewFactorInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "FactorType": factor_type, + "Binding.Alg": binding_alg, + "Binding.PublicKey": binding_public_key, + "Config.AppId": config_app_id, + "Config.NotificationPlatform": config_notification_platform, + "Config.NotificationToken": config_notification_token, + "Config.SdkVersion": config_sdk_version, + "Binding.Secret": binding_secret, + "Config.TimeStep": config_time_step, + "Config.Skew": config_skew, + "Config.CodeLength": config_code_length, + "Config.Alg": config_alg, + "Metadata": serialize.object(metadata), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return NewFactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.NewFactorList>" diff --git a/twilio/rest/verify/v2/service/messaging_configuration.py b/twilio/rest/verify/v2/service/messaging_configuration.py new file mode 100644 index 0000000000..03f494f6e9 --- /dev/null +++ b/twilio/rest/verify/v2/service/messaging_configuration.py @@ -0,0 +1,640 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class MessagingConfigurationInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) that the resource is associated with. + :ivar country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + :ivar messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + country: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.country: Optional[str] = payload.get("country") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "country": country or self.country, + } + self._context: Optional[MessagingConfigurationContext] = None + + @property + def _proxy(self) -> "MessagingConfigurationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MessagingConfigurationContext for this MessagingConfigurationInstance + """ + if self._context is None: + self._context = MessagingConfigurationContext( + self._version, + service_sid=self._solution["service_sid"], + country=self._solution["country"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the MessagingConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessagingConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "MessagingConfigurationInstance": + """ + Fetch the MessagingConfigurationInstance + + + :returns: The fetched MessagingConfigurationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "MessagingConfigurationInstance": + """ + Asynchronous coroutine to fetch the MessagingConfigurationInstance + + + :returns: The fetched MessagingConfigurationInstance + """ + return await self._proxy.fetch_async() + + def update(self, messaging_service_sid: str) -> "MessagingConfigurationInstance": + """ + Update the MessagingConfigurationInstance + + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The updated MessagingConfigurationInstance + """ + return self._proxy.update( + messaging_service_sid=messaging_service_sid, + ) + + async def update_async( + self, messaging_service_sid: str + ) -> "MessagingConfigurationInstance": + """ + Asynchronous coroutine to update the MessagingConfigurationInstance + + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The updated MessagingConfigurationInstance + """ + return await self._proxy.update_async( + messaging_service_sid=messaging_service_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.MessagingConfigurationInstance {}>".format(context) + + +class MessagingConfigurationContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, country: str): + """ + Initialize the MessagingConfigurationContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) that the resource is associated with. + :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "country": country, + } + self._uri = "/Services/{service_sid}/MessagingConfigurations/{country}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the MessagingConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the MessagingConfigurationInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> MessagingConfigurationInstance: + """ + Fetch the MessagingConfigurationInstance + + + :returns: The fetched MessagingConfigurationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return MessagingConfigurationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + country=self._solution["country"], + ) + + async def fetch_async(self) -> MessagingConfigurationInstance: + """ + Asynchronous coroutine to fetch the MessagingConfigurationInstance + + + :returns: The fetched MessagingConfigurationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return MessagingConfigurationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + country=self._solution["country"], + ) + + def update(self, messaging_service_sid: str) -> MessagingConfigurationInstance: + """ + Update the MessagingConfigurationInstance + + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The updated MessagingConfigurationInstance + """ + + data = values.of( + { + "MessagingServiceSid": messaging_service_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessagingConfigurationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + country=self._solution["country"], + ) + + async def update_async( + self, messaging_service_sid: str + ) -> MessagingConfigurationInstance: + """ + Asynchronous coroutine to update the MessagingConfigurationInstance + + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The updated MessagingConfigurationInstance + """ + + data = values.of( + { + "MessagingServiceSid": messaging_service_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessagingConfigurationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + country=self._solution["country"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.MessagingConfigurationContext {}>".format(context) + + +class MessagingConfigurationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> MessagingConfigurationInstance: + """ + Build an instance of MessagingConfigurationInstance + + :param payload: Payload response from the API + """ + return MessagingConfigurationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.MessagingConfigurationPage>" + + +class MessagingConfigurationList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the MessagingConfigurationList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) that the resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/MessagingConfigurations".format( + **self._solution + ) + + def create( + self, country: str, messaging_service_sid: str + ) -> MessagingConfigurationInstance: + """ + Create the MessagingConfigurationInstance + + :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The created MessagingConfigurationInstance + """ + + data = values.of( + { + "Country": country, + "MessagingServiceSid": messaging_service_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessagingConfigurationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, country: str, messaging_service_sid: str + ) -> MessagingConfigurationInstance: + """ + Asynchronously create the MessagingConfigurationInstance + + :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to be used to send SMS to the country of this configuration. + + :returns: The created MessagingConfigurationInstance + """ + + data = values.of( + { + "Country": country, + "MessagingServiceSid": messaging_service_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return MessagingConfigurationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[MessagingConfigurationInstance]: + """ + Streams MessagingConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[MessagingConfigurationInstance]: + """ + Asynchronously streams MessagingConfigurationInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessagingConfigurationInstance]: + """ + Lists MessagingConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[MessagingConfigurationInstance]: + """ + Asynchronously lists MessagingConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagingConfigurationPage: + """ + Retrieve a single page of MessagingConfigurationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessagingConfigurationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagingConfigurationPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> MessagingConfigurationPage: + """ + Asynchronously retrieve a single page of MessagingConfigurationInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of MessagingConfigurationInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return MessagingConfigurationPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> MessagingConfigurationPage: + """ + Retrieve a specific page of MessagingConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessagingConfigurationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return MessagingConfigurationPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> MessagingConfigurationPage: + """ + Asynchronously retrieve a specific page of MessagingConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of MessagingConfigurationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return MessagingConfigurationPage(self._version, response, self._solution) + + def get(self, country: str) -> MessagingConfigurationContext: + """ + Constructs a MessagingConfigurationContext + + :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + """ + return MessagingConfigurationContext( + self._version, service_sid=self._solution["service_sid"], country=country + ) + + def __call__(self, country: str) -> MessagingConfigurationContext: + """ + Constructs a MessagingConfigurationContext + + :param country: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country this configuration will be applied to. If this is a global configuration, Country will take the value `all`. + """ + return MessagingConfigurationContext( + self._version, service_sid=self._solution["service_sid"], country=country + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.MessagingConfigurationList>" diff --git a/twilio/rest/verify/v2/service/rate_limit/__init__.py b/twilio/rest/verify/v2/service/rate_limit/__init__.py new file mode 100644 index 0000000000..ced5ab6a64 --- /dev/null +++ b/twilio/rest/verify/v2/service/rate_limit/__init__.py @@ -0,0 +1,667 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.verify.v2.service.rate_limit.bucket import BucketList + + +class RateLimitInstance(InstanceResource): + """ + :ivar sid: A 34 character string that uniquely identifies this Rate Limit. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Rate Limit resource. + :ivar unique_name: Provides a unique and addressable name to be assigned to this Rate Limit, assigned by the developer, to be optionally used in addition to SID. **This value should not contain PII.** + :ivar description: Description of this Rate Limit + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The URL of this resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.description: Optional[str] = payload.get("description") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[RateLimitContext] = None + + @property + def _proxy(self) -> "RateLimitContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RateLimitContext for this RateLimitInstance + """ + if self._context is None: + self._context = RateLimitContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RateLimitInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RateLimitInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RateLimitInstance": + """ + Fetch the RateLimitInstance + + + :returns: The fetched RateLimitInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RateLimitInstance": + """ + Asynchronous coroutine to fetch the RateLimitInstance + + + :returns: The fetched RateLimitInstance + """ + return await self._proxy.fetch_async() + + def update( + self, description: Union[str, object] = values.unset + ) -> "RateLimitInstance": + """ + Update the RateLimitInstance + + :param description: Description of this Rate Limit + + :returns: The updated RateLimitInstance + """ + return self._proxy.update( + description=description, + ) + + async def update_async( + self, description: Union[str, object] = values.unset + ) -> "RateLimitInstance": + """ + Asynchronous coroutine to update the RateLimitInstance + + :param description: Description of this Rate Limit + + :returns: The updated RateLimitInstance + """ + return await self._proxy.update_async( + description=description, + ) + + @property + def buckets(self) -> BucketList: + """ + Access the buckets + """ + return self._proxy.buckets + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.RateLimitInstance {}>".format(context) + + +class RateLimitContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the RateLimitContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + :param sid: The Twilio-provided string that uniquely identifies the Rate Limit resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/RateLimits/{sid}".format(**self._solution) + + self._buckets: Optional[BucketList] = None + + def delete(self) -> bool: + """ + Deletes the RateLimitInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RateLimitInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RateLimitInstance: + """ + Fetch the RateLimitInstance + + + :returns: The fetched RateLimitInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RateLimitInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RateLimitInstance: + """ + Asynchronous coroutine to fetch the RateLimitInstance + + + :returns: The fetched RateLimitInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RateLimitInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, description: Union[str, object] = values.unset + ) -> RateLimitInstance: + """ + Update the RateLimitInstance + + :param description: Description of this Rate Limit + + :returns: The updated RateLimitInstance + """ + + data = values.of( + { + "Description": description, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RateLimitInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, description: Union[str, object] = values.unset + ) -> RateLimitInstance: + """ + Asynchronous coroutine to update the RateLimitInstance + + :param description: Description of this Rate Limit + + :returns: The updated RateLimitInstance + """ + + data = values.of( + { + "Description": description, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RateLimitInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + @property + def buckets(self) -> BucketList: + """ + Access the buckets + """ + if self._buckets is None: + self._buckets = BucketList( + self._version, + self._solution["service_sid"], + self._solution["sid"], + ) + return self._buckets + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.RateLimitContext {}>".format(context) + + +class RateLimitPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RateLimitInstance: + """ + Build an instance of RateLimitInstance + + :param payload: Payload response from the API + """ + return RateLimitInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.RateLimitPage>" + + +class RateLimitList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the RateLimitList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/RateLimits".format(**self._solution) + + def create( + self, unique_name: str, description: Union[str, object] = values.unset + ) -> RateLimitInstance: + """ + Create the RateLimitInstance + + :param unique_name: Provides a unique and addressable name to be assigned to this Rate Limit, assigned by the developer, to be optionally used in addition to SID. **This value should not contain PII.** + :param description: Description of this Rate Limit + + :returns: The created RateLimitInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Description": description, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RateLimitInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, unique_name: str, description: Union[str, object] = values.unset + ) -> RateLimitInstance: + """ + Asynchronously create the RateLimitInstance + + :param unique_name: Provides a unique and addressable name to be assigned to this Rate Limit, assigned by the developer, to be optionally used in addition to SID. **This value should not contain PII.** + :param description: Description of this Rate Limit + + :returns: The created RateLimitInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "Description": description, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RateLimitInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RateLimitInstance]: + """ + Streams RateLimitInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RateLimitInstance]: + """ + Asynchronously streams RateLimitInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RateLimitInstance]: + """ + Lists RateLimitInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RateLimitInstance]: + """ + Asynchronously lists RateLimitInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RateLimitPage: + """ + Retrieve a single page of RateLimitInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RateLimitInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RateLimitPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RateLimitPage: + """ + Asynchronously retrieve a single page of RateLimitInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RateLimitInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RateLimitPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RateLimitPage: + """ + Retrieve a specific page of RateLimitInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RateLimitInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RateLimitPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RateLimitPage: + """ + Asynchronously retrieve a specific page of RateLimitInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RateLimitInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RateLimitPage(self._version, response, self._solution) + + def get(self, sid: str) -> RateLimitContext: + """ + Constructs a RateLimitContext + + :param sid: The Twilio-provided string that uniquely identifies the Rate Limit resource to fetch. + """ + return RateLimitContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RateLimitContext: + """ + Constructs a RateLimitContext + + :param sid: The Twilio-provided string that uniquely identifies the Rate Limit resource to fetch. + """ + return RateLimitContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.RateLimitList>" diff --git a/twilio/rest/verify/v2/service/rate_limit/bucket.py b/twilio/rest/verify/v2/service/rate_limit/bucket.py new file mode 100644 index 0000000000..4ac50cfc2f --- /dev/null +++ b/twilio/rest/verify/v2/service/rate_limit/bucket.py @@ -0,0 +1,692 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class BucketInstance(InstanceResource): + """ + :ivar sid: A 34 character string that uniquely identifies this Bucket. + :ivar rate_limit_sid: The Twilio-provided string that uniquely identifies the Rate Limit resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Rate Limit resource. + :ivar max: Maximum number of requests permitted in during the interval. + :ivar interval: Number of seconds that the rate limit will be enforced over. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + rate_limit_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.rate_limit_sid: Optional[str] = payload.get("rate_limit_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.max: Optional[int] = deserialize.integer(payload.get("max")) + self.interval: Optional[int] = deserialize.integer(payload.get("interval")) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "rate_limit_sid": rate_limit_sid, + "sid": sid or self.sid, + } + self._context: Optional[BucketContext] = None + + @property + def _proxy(self) -> "BucketContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BucketContext for this BucketInstance + """ + if self._context is None: + self._context = BucketContext( + self._version, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "BucketInstance": + """ + Fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BucketInstance": + """ + Asynchronous coroutine to fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> "BucketInstance": + """ + Update the BucketInstance + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: The updated BucketInstance + """ + return self._proxy.update( + max=max, + interval=interval, + ) + + async def update_async( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> "BucketInstance": + """ + Asynchronous coroutine to update the BucketInstance + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: The updated BucketInstance + """ + return await self._proxy.update_async( + max=max, + interval=interval, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.BucketInstance {}>".format(context) + + +class BucketContext(InstanceContext): + + def __init__( + self, version: Version, service_sid: str, rate_limit_sid: str, sid: str + ): + """ + Initialize the BucketContext + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + :param rate_limit_sid: The Twilio-provided string that uniquely identifies the Rate Limit resource. + :param sid: A 34 character string that uniquely identifies this Bucket. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "rate_limit_sid": rate_limit_sid, + "sid": sid, + } + self._uri = ( + "/Services/{service_sid}/RateLimits/{rate_limit_sid}/Buckets/{sid}".format( + **self._solution + ) + ) + + def delete(self) -> bool: + """ + Deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the BucketInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> BucketInstance: + """ + Fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> BucketInstance: + """ + Asynchronous coroutine to fetch the BucketInstance + + + :returns: The fetched BucketInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> BucketInstance: + """ + Update the BucketInstance + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: The updated BucketInstance + """ + + data = values.of( + { + "Max": max, + "Interval": interval, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + max: Union[int, object] = values.unset, + interval: Union[int, object] = values.unset, + ) -> BucketInstance: + """ + Asynchronous coroutine to update the BucketInstance + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: The updated BucketInstance + """ + + data = values.of( + { + "Max": max, + "Interval": interval, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.BucketContext {}>".format(context) + + +class BucketPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> BucketInstance: + """ + Build an instance of BucketInstance + + :param payload: Payload response from the API + """ + return BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.BucketPage>" + + +class BucketList(ListResource): + + def __init__(self, version: Version, service_sid: str, rate_limit_sid: str): + """ + Initialize the BucketList + + :param version: Version that contains the resource + :param service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + :param rate_limit_sid: The Twilio-provided string that uniquely identifies the Rate Limit resource. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "rate_limit_sid": rate_limit_sid, + } + self._uri = ( + "/Services/{service_sid}/RateLimits/{rate_limit_sid}/Buckets".format( + **self._solution + ) + ) + + def create(self, max: int, interval: int) -> BucketInstance: + """ + Create the BucketInstance + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: The created BucketInstance + """ + + data = values.of( + { + "Max": max, + "Interval": interval, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + ) + + async def create_async(self, max: int, interval: int) -> BucketInstance: + """ + Asynchronously create the BucketInstance + + :param max: Maximum number of requests permitted in during the interval. + :param interval: Number of seconds that the rate limit will be enforced over. + + :returns: The created BucketInstance + """ + + data = values.of( + { + "Max": max, + "Interval": interval, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[BucketInstance]: + """ + Streams BucketInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[BucketInstance]: + """ + Asynchronously streams BucketInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BucketInstance]: + """ + Lists BucketInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[BucketInstance]: + """ + Asynchronously lists BucketInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BucketPage: + """ + Retrieve a single page of BucketInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BucketInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BucketPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> BucketPage: + """ + Asynchronously retrieve a single page of BucketInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of BucketInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return BucketPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> BucketPage: + """ + Retrieve a specific page of BucketInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BucketInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return BucketPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> BucketPage: + """ + Asynchronously retrieve a specific page of BucketInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of BucketInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return BucketPage(self._version, response, self._solution) + + def get(self, sid: str) -> BucketContext: + """ + Constructs a BucketContext + + :param sid: A 34 character string that uniquely identifies this Bucket. + """ + return BucketContext( + self._version, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> BucketContext: + """ + Constructs a BucketContext + + :param sid: A 34 character string that uniquely identifies this Bucket. + """ + return BucketContext( + self._version, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.BucketList>" diff --git a/twilio/rest/verify/v2/service/verification.py b/twilio/rest/verify/v2/service/verification.py new file mode 100644 index 0000000000..64988a5983 --- /dev/null +++ b/twilio/rest/verify/v2/service/verification.py @@ -0,0 +1,517 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class VerificationInstance(InstanceResource): + + class Channel(object): + SMS = "sms" + CALL = "call" + EMAIL = "email" + WHATSAPP = "whatsapp" + SNA = "sna" + + class RiskCheck(object): + ENABLE = "enable" + DISABLE = "disable" + + class Status(object): + CANCELED = "canceled" + APPROVED = "approved" + + """ + :ivar sid: The unique string that we created to identify the Verification resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Verification resource. + :ivar to: The phone number or [email](https://www.twilio.com/docs/verify/email) being verified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :ivar channel: + :ivar status: The status of the verification. Can be: `pending`, `approved`, `canceled`, `max_attempts_reached`, `deleted`, `failed` or `expired`. + :ivar valid: Use \"status\" instead. Legacy property indicating whether the verification was successful. + :ivar lookup: Information about the phone number being verified. + :ivar amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :ivar payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :ivar send_code_attempts: An array of verification attempt objects containing the channel attempted and the channel-specific transaction SID. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar sna: The set of fields used for a silent network auth (`sna`) verification. Contains a single field with the URL to be invoked to verify the phone number. + :ivar url: The absolute URL of the Verification resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.to: Optional[str] = payload.get("to") + self.channel: Optional["VerificationInstance.Channel"] = payload.get("channel") + self.status: Optional[str] = payload.get("status") + self.valid: Optional[bool] = payload.get("valid") + self.lookup: Optional[Dict[str, object]] = payload.get("lookup") + self.amount: Optional[str] = payload.get("amount") + self.payee: Optional[str] = payload.get("payee") + self.send_code_attempts: Optional[List[Dict[str, object]]] = payload.get( + "send_code_attempts" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sna: Optional[Dict[str, object]] = payload.get("sna") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[VerificationContext] = None + + @property + def _proxy(self) -> "VerificationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: VerificationContext for this VerificationInstance + """ + if self._context is None: + self._context = VerificationContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "VerificationInstance": + """ + Fetch the VerificationInstance + + + :returns: The fetched VerificationInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "VerificationInstance": + """ + Asynchronous coroutine to fetch the VerificationInstance + + + :returns: The fetched VerificationInstance + """ + return await self._proxy.fetch_async() + + def update(self, status: "VerificationInstance.Status") -> "VerificationInstance": + """ + Update the VerificationInstance + + :param status: + + :returns: The updated VerificationInstance + """ + return self._proxy.update( + status=status, + ) + + async def update_async( + self, status: "VerificationInstance.Status" + ) -> "VerificationInstance": + """ + Asynchronous coroutine to update the VerificationInstance + + :param status: + + :returns: The updated VerificationInstance + """ + return await self._proxy.update_async( + status=status, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.VerificationInstance {}>".format(context) + + +class VerificationContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the VerificationContext + + :param version: Version that contains the resource + :param service_sid: The SID of the verification [Service](https://www.twilio.com/docs/verify/api/service) to update the resource from. + :param sid: The Twilio-provided string that uniquely identifies the Verification resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Verifications/{sid}".format( + **self._solution + ) + + def fetch(self) -> VerificationInstance: + """ + Fetch the VerificationInstance + + + :returns: The fetched VerificationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return VerificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> VerificationInstance: + """ + Asynchronous coroutine to fetch the VerificationInstance + + + :returns: The fetched VerificationInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return VerificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update(self, status: "VerificationInstance.Status") -> VerificationInstance: + """ + Update the VerificationInstance + + :param status: + + :returns: The updated VerificationInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return VerificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, status: "VerificationInstance.Status" + ) -> VerificationInstance: + """ + Asynchronous coroutine to update the VerificationInstance + + :param status: + + :returns: The updated VerificationInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return VerificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.VerificationContext {}>".format(context) + + +class VerificationList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the VerificationList + + :param version: Version that contains the resource + :param service_sid: The SID of the verification [Service](https://www.twilio.com/docs/verify/api/service) to create the resource under. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Verifications".format(**self._solution) + + def create( + self, + to: str, + channel: str, + custom_friendly_name: Union[str, object] = values.unset, + custom_message: Union[str, object] = values.unset, + send_digits: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + custom_code: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + rate_limits: Union[object, object] = values.unset, + channel_configuration: Union[object, object] = values.unset, + app_hash: Union[str, object] = values.unset, + template_sid: Union[str, object] = values.unset, + template_custom_substitutions: Union[str, object] = values.unset, + device_ip: Union[str, object] = values.unset, + enable_sna_client_token: Union[bool, object] = values.unset, + risk_check: Union["VerificationInstance.RiskCheck", object] = values.unset, + tags: Union[str, object] = values.unset, + ) -> VerificationInstance: + """ + Create the VerificationInstance + + :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param channel: The verification method to use. One of: [`email`](https://www.twilio.com/docs/verify/email), `sms`, `whatsapp`, `call`, `sna` or `auto`. + :param custom_friendly_name: A custom user defined friendly name that overwrites the existing one in the verification message + :param custom_message: The text of a custom message to use for the verification. + :param send_digits: The digits to send after a phone call is answered, for example, to dial an extension. For more information, see the Programmable Voice documentation of [sendDigits](https://www.twilio.com/docs/voice/twiml/number#attributes-sendDigits). + :param locale: Locale will automatically resolve based on phone number country code for SMS, WhatsApp, and call channel verifications. It will fallback to English or the template’s default translation if the selected translation is not available. This parameter will override the automatic locale resolution. [See supported languages and more information here](https://www.twilio.com/docs/verify/supported-languages). + :param custom_code: A pre-generated code to use for verification. The code can be between 4 and 10 characters, inclusive. + :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param rate_limits: The custom key-value pairs of Programmable Rate Limits. Keys correspond to `unique_name` fields defined when [creating your Rate Limit](https://www.twilio.com/docs/verify/api/service-rate-limits). Associated value pairs represent values in the request that you are rate limiting on. You may include multiple Rate Limit values in each request. + :param channel_configuration: [`email`](https://www.twilio.com/docs/verify/email) channel configuration in json format. The fields 'from' and 'from_name' are optional but if included the 'from' field must have a valid email address. + :param app_hash: Your [App Hash](https://developers.google.com/identity/sms-retriever/verify#computing_your_apps_hash_string) to be appended at the end of your verification SMS body. Applies only to SMS. Example SMS body: `<#> Your AppName verification code is: 1234 He42w354ol9`. + :param template_sid: The message [template](https://www.twilio.com/docs/verify/api/templates). If provided, will override the default template for the Service. SMS and Voice channels only. + :param template_custom_substitutions: A stringified JSON object in which the keys are the template's special variables and the values are the variables substitutions. + :param device_ip: Strongly encouraged if using the auto channel. The IP address of the client's device. If provided, it has to be a valid IPv4 or IPv6 address. + :param enable_sna_client_token: An optional Boolean value to indicate the requirement of sna client token in the SNA URL invocation response for added security. This token must match in the Verification Check request to confirm phone number verification. + :param risk_check: + :param tags: A string containing a JSON map of key value pairs of tags to be recorded as metadata for the message. The object may contain up to 10 tags. Keys and values can each be up to 128 characters in length. + + :returns: The created VerificationInstance + """ + + data = values.of( + { + "To": to, + "Channel": channel, + "CustomFriendlyName": custom_friendly_name, + "CustomMessage": custom_message, + "SendDigits": send_digits, + "Locale": locale, + "CustomCode": custom_code, + "Amount": amount, + "Payee": payee, + "RateLimits": serialize.object(rate_limits), + "ChannelConfiguration": serialize.object(channel_configuration), + "AppHash": app_hash, + "TemplateSid": template_sid, + "TemplateCustomSubstitutions": template_custom_substitutions, + "DeviceIp": device_ip, + "EnableSnaClientToken": serialize.boolean_to_string( + enable_sna_client_token + ), + "RiskCheck": risk_check, + "Tags": tags, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return VerificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + to: str, + channel: str, + custom_friendly_name: Union[str, object] = values.unset, + custom_message: Union[str, object] = values.unset, + send_digits: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + custom_code: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + rate_limits: Union[object, object] = values.unset, + channel_configuration: Union[object, object] = values.unset, + app_hash: Union[str, object] = values.unset, + template_sid: Union[str, object] = values.unset, + template_custom_substitutions: Union[str, object] = values.unset, + device_ip: Union[str, object] = values.unset, + enable_sna_client_token: Union[bool, object] = values.unset, + risk_check: Union["VerificationInstance.RiskCheck", object] = values.unset, + tags: Union[str, object] = values.unset, + ) -> VerificationInstance: + """ + Asynchronously create the VerificationInstance + + :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param channel: The verification method to use. One of: [`email`](https://www.twilio.com/docs/verify/email), `sms`, `whatsapp`, `call`, `sna` or `auto`. + :param custom_friendly_name: A custom user defined friendly name that overwrites the existing one in the verification message + :param custom_message: The text of a custom message to use for the verification. + :param send_digits: The digits to send after a phone call is answered, for example, to dial an extension. For more information, see the Programmable Voice documentation of [sendDigits](https://www.twilio.com/docs/voice/twiml/number#attributes-sendDigits). + :param locale: Locale will automatically resolve based on phone number country code for SMS, WhatsApp, and call channel verifications. It will fallback to English or the template’s default translation if the selected translation is not available. This parameter will override the automatic locale resolution. [See supported languages and more information here](https://www.twilio.com/docs/verify/supported-languages). + :param custom_code: A pre-generated code to use for verification. The code can be between 4 and 10 characters, inclusive. + :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param rate_limits: The custom key-value pairs of Programmable Rate Limits. Keys correspond to `unique_name` fields defined when [creating your Rate Limit](https://www.twilio.com/docs/verify/api/service-rate-limits). Associated value pairs represent values in the request that you are rate limiting on. You may include multiple Rate Limit values in each request. + :param channel_configuration: [`email`](https://www.twilio.com/docs/verify/email) channel configuration in json format. The fields 'from' and 'from_name' are optional but if included the 'from' field must have a valid email address. + :param app_hash: Your [App Hash](https://developers.google.com/identity/sms-retriever/verify#computing_your_apps_hash_string) to be appended at the end of your verification SMS body. Applies only to SMS. Example SMS body: `<#> Your AppName verification code is: 1234 He42w354ol9`. + :param template_sid: The message [template](https://www.twilio.com/docs/verify/api/templates). If provided, will override the default template for the Service. SMS and Voice channels only. + :param template_custom_substitutions: A stringified JSON object in which the keys are the template's special variables and the values are the variables substitutions. + :param device_ip: Strongly encouraged if using the auto channel. The IP address of the client's device. If provided, it has to be a valid IPv4 or IPv6 address. + :param enable_sna_client_token: An optional Boolean value to indicate the requirement of sna client token in the SNA URL invocation response for added security. This token must match in the Verification Check request to confirm phone number verification. + :param risk_check: + :param tags: A string containing a JSON map of key value pairs of tags to be recorded as metadata for the message. The object may contain up to 10 tags. Keys and values can each be up to 128 characters in length. + + :returns: The created VerificationInstance + """ + + data = values.of( + { + "To": to, + "Channel": channel, + "CustomFriendlyName": custom_friendly_name, + "CustomMessage": custom_message, + "SendDigits": send_digits, + "Locale": locale, + "CustomCode": custom_code, + "Amount": amount, + "Payee": payee, + "RateLimits": serialize.object(rate_limits), + "ChannelConfiguration": serialize.object(channel_configuration), + "AppHash": app_hash, + "TemplateSid": template_sid, + "TemplateCustomSubstitutions": template_custom_substitutions, + "DeviceIp": device_ip, + "EnableSnaClientToken": serialize.boolean_to_string( + enable_sna_client_token + ), + "RiskCheck": risk_check, + "Tags": tags, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return VerificationInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def get(self, sid: str) -> VerificationContext: + """ + Constructs a VerificationContext + + :param sid: The Twilio-provided string that uniquely identifies the Verification resource to update. + """ + return VerificationContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> VerificationContext: + """ + Constructs a VerificationContext + + :param sid: The Twilio-provided string that uniquely identifies the Verification resource to update. + """ + return VerificationContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.VerificationList>" diff --git a/twilio/rest/verify/v2/service/verification_check.py b/twilio/rest/verify/v2/service/verification_check.py new file mode 100644 index 0000000000..c09057ebe1 --- /dev/null +++ b/twilio/rest/verify/v2/service/verification_check.py @@ -0,0 +1,202 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class VerificationCheckInstance(InstanceResource): + + class Channel(object): + SMS = "sms" + CALL = "call" + EMAIL = "email" + WHATSAPP = "whatsapp" + SNA = "sna" + + """ + :ivar sid: The unique string that we created to identify the VerificationCheck resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the VerificationCheck resource. + :ivar to: The phone number or [email](https://www.twilio.com/docs/verify/email) being verified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :ivar channel: + :ivar status: The status of the verification. Can be: `pending`, `approved`, `canceled`, `max_attempts_reached`, `deleted`, `failed` or `expired`. + :ivar valid: Use \"status\" instead. Legacy property indicating whether the verification was successful. + :ivar amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :ivar payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :ivar date_created: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the Verification Check resource was created. + :ivar date_updated: The [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date and time in GMT when the Verification Check resource was last updated. + :ivar sna_attempts_error_codes: List of error codes as a result of attempting a verification using the `sna` channel. The error codes are chronologically ordered, from the first attempt to the latest attempt. This will be an empty list if no errors occured or `null` if the last channel used wasn't `sna`. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], service_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.to: Optional[str] = payload.get("to") + self.channel: Optional["VerificationCheckInstance.Channel"] = payload.get( + "channel" + ) + self.status: Optional[str] = payload.get("status") + self.valid: Optional[bool] = payload.get("valid") + self.amount: Optional[str] = payload.get("amount") + self.payee: Optional[str] = payload.get("payee") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sna_attempts_error_codes: Optional[List[Dict[str, object]]] = payload.get( + "sna_attempts_error_codes" + ) + + self._solution = { + "service_sid": service_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.VerificationCheckInstance {}>".format(context) + + +class VerificationCheckList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the VerificationCheckList + + :param version: Version that contains the resource + :param service_sid: The SID of the verification [Service](https://www.twilio.com/docs/verify/api/service) to create the resource under. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/VerificationCheck".format(**self._solution) + + def create( + self, + code: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + sna_client_token: Union[str, object] = values.unset, + ) -> VerificationCheckInstance: + """ + Create the VerificationCheckInstance + + :param code: The 4-10 character string being verified. + :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Either this parameter or the `verification_sid` must be specified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param verification_sid: A SID that uniquely identifies the Verification Check. Either this parameter or the `to` phone number/[email](https://www.twilio.com/docs/verify/email) must be specified. + :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param sna_client_token: A sna client token received in sna url invocation response needs to be passed in Verification Check request and should match to get successful response. + + :returns: The created VerificationCheckInstance + """ + + data = values.of( + { + "Code": code, + "To": to, + "VerificationSid": verification_sid, + "Amount": amount, + "Payee": payee, + "SnaClientToken": sna_client_token, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return VerificationCheckInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + code: Union[str, object] = values.unset, + to: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + amount: Union[str, object] = values.unset, + payee: Union[str, object] = values.unset, + sna_client_token: Union[str, object] = values.unset, + ) -> VerificationCheckInstance: + """ + Asynchronously create the VerificationCheckInstance + + :param code: The 4-10 character string being verified. + :param to: The phone number or [email](https://www.twilio.com/docs/verify/email) to verify. Either this parameter or the `verification_sid` must be specified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). + :param verification_sid: A SID that uniquely identifies the Verification Check. Either this parameter or the `to` phone number/[email](https://www.twilio.com/docs/verify/email) must be specified. + :param amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. + :param sna_client_token: A sna client token received in sna url invocation response needs to be passed in Verification Check request and should match to get successful response. + + :returns: The created VerificationCheckInstance + """ + + data = values.of( + { + "Code": code, + "To": to, + "VerificationSid": verification_sid, + "Amount": amount, + "Payee": payee, + "SnaClientToken": sna_client_token, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return VerificationCheckInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.VerificationCheckList>" diff --git a/twilio/rest/verify/v2/service/webhook.py b/twilio/rest/verify/v2/service/webhook.py new file mode 100644 index 0000000000..dd68cf301b --- /dev/null +++ b/twilio/rest/verify/v2/service/webhook.py @@ -0,0 +1,739 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class WebhookInstance(InstanceResource): + + class Methods(object): + GET = "GET" + POST = "POST" + + class Status(object): + ENABLED = "enabled" + DISABLED = "disabled" + + class Version(object): + V1 = "v1" + V2 = "v2" + + """ + :ivar sid: The unique string that we created to identify the Webhook resource. + :ivar service_sid: The unique SID identifier of the Service. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. + :ivar friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :ivar event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :ivar status: + :ivar version: + :ivar webhook_url: The URL associated with this Webhook. + :ivar webhook_method: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Webhook resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.event_types: Optional[List[str]] = payload.get("event_types") + self.status: Optional["WebhookInstance.Status"] = payload.get("status") + self.version: Optional["WebhookInstance.Version"] = payload.get("version") + self.webhook_url: Optional[str] = payload.get("webhook_url") + self.webhook_method: Optional["WebhookInstance.Methods"] = payload.get( + "webhook_method" + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid, + "sid": sid or self.sid, + } + self._context: Optional[WebhookContext] = None + + @property + def _proxy(self) -> "WebhookContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: WebhookContext for this WebhookInstance + """ + if self._context is None: + self._context = WebhookContext( + self._version, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "WebhookInstance": + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "WebhookInstance": + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + event_types: Union[List[str], object] = values.unset, + webhook_url: Union[str, object] = values.unset, + status: Union["WebhookInstance.Status", object] = values.unset, + version: Union["WebhookInstance.Version", object] = values.unset, + ) -> "WebhookInstance": + """ + Update the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param version: + + :returns: The updated WebhookInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + version=version, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + event_types: Union[List[str], object] = values.unset, + webhook_url: Union[str, object] = values.unset, + status: Union["WebhookInstance.Status", object] = values.unset, + version: Union["WebhookInstance.Version", object] = values.unset, + ) -> "WebhookInstance": + """ + Asynchronous coroutine to update the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param version: + + :returns: The updated WebhookInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + version=version, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.WebhookInstance {}>".format(context) + + +class WebhookContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, sid: str): + """ + Initialize the WebhookContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param sid: The Twilio-provided string that uniquely identifies the Webhook resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "sid": sid, + } + self._uri = "/Services/{service_sid}/Webhooks/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the WebhookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> WebhookInstance: + """ + Asynchronous coroutine to fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + event_types: Union[List[str], object] = values.unset, + webhook_url: Union[str, object] = values.unset, + status: Union["WebhookInstance.Status", object] = values.unset, + version: Union["WebhookInstance.Version", object] = values.unset, + ) -> WebhookInstance: + """ + Update the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param version: + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "EventTypes": serialize.map(event_types, lambda e: e), + "WebhookUrl": webhook_url, + "Status": status, + "Version": version, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + event_types: Union[List[str], object] = values.unset, + webhook_url: Union[str, object] = values.unset, + status: Union["WebhookInstance.Status", object] = values.unset, + version: Union["WebhookInstance.Version", object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronous coroutine to update the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param version: + + :returns: The updated WebhookInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "EventTypes": serialize.map(event_types, lambda e: e), + "WebhookUrl": webhook_url, + "Status": status, + "Version": version, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.WebhookContext {}>".format(context) + + +class WebhookPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: + """ + Build an instance of WebhookInstance + + :param payload: Payload response from the API + """ + return WebhookInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.WebhookPage>" + + +class WebhookList(ListResource): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the WebhookList + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + } + self._uri = "/Services/{service_sid}/Webhooks".format(**self._solution) + + def create( + self, + friendly_name: str, + event_types: List[str], + webhook_url: str, + status: Union["WebhookInstance.Status", object] = values.unset, + version: Union["WebhookInstance.Version", object] = values.unset, + ) -> WebhookInstance: + """ + Create the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param version: + + :returns: The created WebhookInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "EventTypes": serialize.map(event_types, lambda e: e), + "WebhookUrl": webhook_url, + "Status": status, + "Version": version, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + async def create_async( + self, + friendly_name: str, + event_types: List[str], + webhook_url: str, + status: Union["WebhookInstance.Status", object] = values.unset, + version: Union["WebhookInstance.Version", object] = values.unset, + ) -> WebhookInstance: + """ + Asynchronously create the WebhookInstance + + :param friendly_name: The string that you assigned to describe the webhook. **This value should not contain PII.** + :param event_types: The array of events that this Webhook is subscribed to. Possible event types: `*, factor.deleted, factor.created, factor.verified, challenge.approved, challenge.denied` + :param webhook_url: The URL associated with this Webhook. + :param status: + :param version: + + :returns: The created WebhookInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "EventTypes": serialize.map(event_types, lambda e: e), + "WebhookUrl": webhook_url, + "Status": status, + "Version": version, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return WebhookInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[WebhookInstance]: + """ + Streams WebhookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[WebhookInstance]: + """ + Asynchronously streams WebhookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: + """ + Lists WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[WebhookInstance]: + """ + Asynchronously lists WebhookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebhookPage: + """ + Retrieve a single page of WebhookInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebhookInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> WebhookPage: + """ + Asynchronously retrieve a single page of WebhookInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of WebhookInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return WebhookPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> WebhookPage: + """ + Retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return WebhookPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> WebhookPage: + """ + Asynchronously retrieve a specific page of WebhookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of WebhookInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return WebhookPage(self._version, response, self._solution) + + def get(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: The Twilio-provided string that uniquely identifies the Webhook resource to update. + """ + return WebhookContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __call__(self, sid: str) -> WebhookContext: + """ + Constructs a WebhookContext + + :param sid: The Twilio-provided string that uniquely identifies the Webhook resource to update. + """ + return WebhookContext( + self._version, service_sid=self._solution["service_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.WebhookList>" diff --git a/twilio/rest/verify/v2/template.py b/twilio/rest/verify/v2/template.py new file mode 100644 index 0000000000..5a242c153e --- /dev/null +++ b/twilio/rest/verify/v2/template.py @@ -0,0 +1,301 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class TemplateInstance(InstanceResource): + """ + :ivar sid: A 34 character string that uniquely identifies a Verification Template. + :ivar account_sid: The unique SID identifier of the Account. + :ivar friendly_name: A descriptive string that you create to describe a Template. It can be up to 32 characters long. + :ivar channels: A list of channels that support the Template. Can include: sms, voice. + :ivar translations: An object that contains the different translations of the template. Every translation is identified by the language short name and contains its respective information as the approval status, text and created/modified date. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.channels: Optional[List[str]] = payload.get("channels") + self.translations: Optional[Dict[str, object]] = payload.get("translations") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Verify.V2.TemplateInstance>" + + +class TemplatePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TemplateInstance: + """ + Build an instance of TemplateInstance + + :param payload: Payload response from the API + """ + return TemplateInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.TemplatePage>" + + +class TemplateList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TemplateList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Templates" + + def stream( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[TemplateInstance]: + """ + Streams TemplateInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: String filter used to query templates with a given friendly name. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(friendly_name=friendly_name, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[TemplateInstance]: + """ + Asynchronously streams TemplateInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str friendly_name: String filter used to query templates with a given friendly name. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + friendly_name=friendly_name, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TemplateInstance]: + """ + Lists TemplateInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: String filter used to query templates with a given friendly name. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[TemplateInstance]: + """ + Asynchronously lists TemplateInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str friendly_name: String filter used to query templates with a given friendly name. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TemplatePage: + """ + Retrieve a single page of TemplateInstance records from the API. + Request is executed immediately + + :param friendly_name: String filter used to query templates with a given friendly name. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TemplateInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TemplatePage(self._version, response) + + async def page_async( + self, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> TemplatePage: + """ + Asynchronously retrieve a single page of TemplateInstance records from the API. + Request is executed immediately + + :param friendly_name: String filter used to query templates with a given friendly name. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of TemplateInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TemplatePage(self._version, response) + + def get_page(self, target_url: str) -> TemplatePage: + """ + Retrieve a specific page of TemplateInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TemplateInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TemplatePage(self._version, response) + + async def get_page_async(self, target_url: str) -> TemplatePage: + """ + Asynchronously retrieve a specific page of TemplateInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TemplateInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TemplatePage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.TemplateList>" diff --git a/twilio/rest/verify/v2/verification_attempt.py b/twilio/rest/verify/v2/verification_attempt.py new file mode 100644 index 0000000000..129a65a5fb --- /dev/null +++ b/twilio/rest/verify/v2/verification_attempt.py @@ -0,0 +1,602 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class VerificationAttemptInstance(InstanceResource): + + class Channels(object): + SMS = "sms" + CALL = "call" + EMAIL = "email" + WHATSAPP = "whatsapp" + RBM = "rbm" + SNA = "sna" + + class ConversionStatus(object): + CONVERTED = "converted" + UNCONVERTED = "unconverted" + + """ + :ivar sid: The SID that uniquely identifies the verification attempt resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Verification resource. + :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) used to generate the attempt. + :ivar verification_sid: The SID of the [Verification](https://www.twilio.com/docs/verify/api/verification) that generated the attempt. + :ivar date_created: The date that this Attempt was created, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date that this Attempt was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar conversion_status: + :ivar channel: + :ivar price: An object containing the charge for this verification attempt related to the channel costs and the currency used. The costs related to the succeeded verifications are not included. May not be immediately available. More information on pricing is available [here](https://www.twilio.com/en-us/verify/pricing). + :ivar channel_data: An object containing the channel specific information for an attempt. + :ivar url: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.service_sid: Optional[str] = payload.get("service_sid") + self.verification_sid: Optional[str] = payload.get("verification_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.conversion_status: Optional[ + "VerificationAttemptInstance.ConversionStatus" + ] = payload.get("conversion_status") + self.channel: Optional["VerificationAttemptInstance.Channels"] = payload.get( + "channel" + ) + self.price: Optional[Dict[str, object]] = payload.get("price") + self.channel_data: Optional[Dict[str, object]] = payload.get("channel_data") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[VerificationAttemptContext] = None + + @property + def _proxy(self) -> "VerificationAttemptContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: VerificationAttemptContext for this VerificationAttemptInstance + """ + if self._context is None: + self._context = VerificationAttemptContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "VerificationAttemptInstance": + """ + Fetch the VerificationAttemptInstance + + + :returns: The fetched VerificationAttemptInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "VerificationAttemptInstance": + """ + Asynchronous coroutine to fetch the VerificationAttemptInstance + + + :returns: The fetched VerificationAttemptInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.VerificationAttemptInstance {}>".format(context) + + +class VerificationAttemptContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the VerificationAttemptContext + + :param version: Version that contains the resource + :param sid: The unique SID identifier of a Verification Attempt + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Attempts/{sid}".format(**self._solution) + + def fetch(self) -> VerificationAttemptInstance: + """ + Fetch the VerificationAttemptInstance + + + :returns: The fetched VerificationAttemptInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return VerificationAttemptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> VerificationAttemptInstance: + """ + Asynchronous coroutine to fetch the VerificationAttemptInstance + + + :returns: The fetched VerificationAttemptInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return VerificationAttemptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Verify.V2.VerificationAttemptContext {}>".format(context) + + +class VerificationAttemptPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> VerificationAttemptInstance: + """ + Build an instance of VerificationAttemptInstance + + :param payload: Payload response from the API + """ + return VerificationAttemptInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.VerificationAttemptPage>" + + +class VerificationAttemptList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the VerificationAttemptList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Attempts" + + def stream( + self, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + channel_data_to: Union[str, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union["VerificationAttemptInstance.Channels", object] = values.unset, + verify_service_sid: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + status: Union[ + "VerificationAttemptInstance.ConversionStatus", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[VerificationAttemptInstance]: + """ + Streams VerificationAttemptInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param datetime date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param str channel_data_to: Destination of a verification. It is phone number in E.164 format. + :param str country: Filter used to query Verification Attempts sent to the specified destination country. + :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param str verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. + :param str verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. + :param "VerificationAttemptInstance.ConversionStatus" status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + date_created_after=date_created_after, + date_created_before=date_created_before, + channel_data_to=channel_data_to, + country=country, + channel=channel, + verify_service_sid=verify_service_sid, + verification_sid=verification_sid, + status=status, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + channel_data_to: Union[str, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union["VerificationAttemptInstance.Channels", object] = values.unset, + verify_service_sid: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + status: Union[ + "VerificationAttemptInstance.ConversionStatus", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[VerificationAttemptInstance]: + """ + Asynchronously streams VerificationAttemptInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param datetime date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param str channel_data_to: Destination of a verification. It is phone number in E.164 format. + :param str country: Filter used to query Verification Attempts sent to the specified destination country. + :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param str verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. + :param str verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. + :param "VerificationAttemptInstance.ConversionStatus" status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + date_created_after=date_created_after, + date_created_before=date_created_before, + channel_data_to=channel_data_to, + country=country, + channel=channel, + verify_service_sid=verify_service_sid, + verification_sid=verification_sid, + status=status, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + channel_data_to: Union[str, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union["VerificationAttemptInstance.Channels", object] = values.unset, + verify_service_sid: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + status: Union[ + "VerificationAttemptInstance.ConversionStatus", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[VerificationAttemptInstance]: + """ + Lists VerificationAttemptInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param datetime date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param str channel_data_to: Destination of a verification. It is phone number in E.164 format. + :param str country: Filter used to query Verification Attempts sent to the specified destination country. + :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param str verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. + :param str verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. + :param "VerificationAttemptInstance.ConversionStatus" status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + date_created_after=date_created_after, + date_created_before=date_created_before, + channel_data_to=channel_data_to, + country=country, + channel=channel, + verify_service_sid=verify_service_sid, + verification_sid=verification_sid, + status=status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + channel_data_to: Union[str, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union["VerificationAttemptInstance.Channels", object] = values.unset, + verify_service_sid: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + status: Union[ + "VerificationAttemptInstance.ConversionStatus", object + ] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[VerificationAttemptInstance]: + """ + Asynchronously lists VerificationAttemptInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param datetime date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param str channel_data_to: Destination of a verification. It is phone number in E.164 format. + :param str country: Filter used to query Verification Attempts sent to the specified destination country. + :param "VerificationAttemptInstance.Channels" channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param str verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. + :param str verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. + :param "VerificationAttemptInstance.ConversionStatus" status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + date_created_after=date_created_after, + date_created_before=date_created_before, + channel_data_to=channel_data_to, + country=country, + channel=channel, + verify_service_sid=verify_service_sid, + verification_sid=verification_sid, + status=status, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + channel_data_to: Union[str, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union["VerificationAttemptInstance.Channels", object] = values.unset, + verify_service_sid: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + status: Union[ + "VerificationAttemptInstance.ConversionStatus", object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> VerificationAttemptPage: + """ + Retrieve a single page of VerificationAttemptInstance records from the API. + Request is executed immediately + + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param channel_data_to: Destination of a verification. It is phone number in E.164 format. + :param country: Filter used to query Verification Attempts sent to the specified destination country. + :param channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. + :param verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. + :param status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of VerificationAttemptInstance + """ + data = values.of( + { + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ChannelData.To": channel_data_to, + "Country": country, + "Channel": channel, + "VerifyServiceSid": verify_service_sid, + "VerificationSid": verification_sid, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return VerificationAttemptPage(self._version, response) + + async def page_async( + self, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + channel_data_to: Union[str, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union["VerificationAttemptInstance.Channels", object] = values.unset, + verify_service_sid: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + status: Union[ + "VerificationAttemptInstance.ConversionStatus", object + ] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> VerificationAttemptPage: + """ + Asynchronously retrieve a single page of VerificationAttemptInstance records from the API. + Request is executed immediately + + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param channel_data_to: Destination of a verification. It is phone number in E.164 format. + :param country: Filter used to query Verification Attempts sent to the specified destination country. + :param channel: Filter used to query Verification Attempts by communication channel. Valid values are `SMS` and `CALL` + :param verify_service_sid: Filter used to query Verification Attempts by verify service. Only attempts of the provided SID will be returned. + :param verification_sid: Filter used to return all the Verification Attempts of a single verification. Only attempts of the provided verification SID will be returned. + :param status: Filter used to query Verification Attempts by conversion status. Valid values are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for attempts that were confirmed. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of VerificationAttemptInstance + """ + data = values.of( + { + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "ChannelData.To": channel_data_to, + "Country": country, + "Channel": channel, + "VerifyServiceSid": verify_service_sid, + "VerificationSid": verification_sid, + "Status": status, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return VerificationAttemptPage(self._version, response) + + def get_page(self, target_url: str) -> VerificationAttemptPage: + """ + Retrieve a specific page of VerificationAttemptInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of VerificationAttemptInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return VerificationAttemptPage(self._version, response) + + async def get_page_async(self, target_url: str) -> VerificationAttemptPage: + """ + Asynchronously retrieve a specific page of VerificationAttemptInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of VerificationAttemptInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return VerificationAttemptPage(self._version, response) + + def get(self, sid: str) -> VerificationAttemptContext: + """ + Constructs a VerificationAttemptContext + + :param sid: The unique SID identifier of a Verification Attempt + """ + return VerificationAttemptContext(self._version, sid=sid) + + def __call__(self, sid: str) -> VerificationAttemptContext: + """ + Constructs a VerificationAttemptContext + + :param sid: The unique SID identifier of a Verification Attempt + """ + return VerificationAttemptContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.VerificationAttemptList>" diff --git a/twilio/rest/verify/v2/verification_attempts_summary.py b/twilio/rest/verify/v2/verification_attempts_summary.py new file mode 100644 index 0000000000..d662cf8f55 --- /dev/null +++ b/twilio/rest/verify/v2/verification_attempts_summary.py @@ -0,0 +1,296 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Verify + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional, Union +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class VerificationAttemptsSummaryInstance(InstanceResource): + + class Channels(object): + SMS = "sms" + CALL = "call" + EMAIL = "email" + WHATSAPP = "whatsapp" + + """ + :ivar total_attempts: Total of attempts made according to the provided filters + :ivar total_converted: Total of attempts made that were confirmed by the end user, according to the provided filters. + :ivar total_unconverted: Total of attempts made that were not confirmed by the end user, according to the provided filters. + :ivar conversion_rate_percentage: Percentage of the confirmed messages over the total, defined by (total_converted/total_attempts)*100. + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.total_attempts: Optional[int] = deserialize.integer( + payload.get("total_attempts") + ) + self.total_converted: Optional[int] = deserialize.integer( + payload.get("total_converted") + ) + self.total_unconverted: Optional[int] = deserialize.integer( + payload.get("total_unconverted") + ) + self.conversion_rate_percentage: Optional[str] = payload.get( + "conversion_rate_percentage" + ) + self.url: Optional[str] = payload.get("url") + + self._context: Optional[VerificationAttemptsSummaryContext] = None + + @property + def _proxy(self) -> "VerificationAttemptsSummaryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: VerificationAttemptsSummaryContext for this VerificationAttemptsSummaryInstance + """ + if self._context is None: + self._context = VerificationAttemptsSummaryContext( + self._version, + ) + return self._context + + def fetch( + self, + verify_service_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union[ + "VerificationAttemptsSummaryInstance.Channels", object + ] = values.unset, + destination_prefix: Union[str, object] = values.unset, + ) -> "VerificationAttemptsSummaryInstance": + """ + Fetch the VerificationAttemptsSummaryInstance + + :param verify_service_sid: Filter used to consider only Verification Attempts of the given verify service on the summary aggregation. + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. Valid values are `SMS`, `CALL` and `WHATSAPP` + :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. + + :returns: The fetched VerificationAttemptsSummaryInstance + """ + return self._proxy.fetch( + verify_service_sid=verify_service_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + country=country, + channel=channel, + destination_prefix=destination_prefix, + ) + + async def fetch_async( + self, + verify_service_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union[ + "VerificationAttemptsSummaryInstance.Channels", object + ] = values.unset, + destination_prefix: Union[str, object] = values.unset, + ) -> "VerificationAttemptsSummaryInstance": + """ + Asynchronous coroutine to fetch the VerificationAttemptsSummaryInstance + + :param verify_service_sid: Filter used to consider only Verification Attempts of the given verify service on the summary aggregation. + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. Valid values are `SMS`, `CALL` and `WHATSAPP` + :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. + + :returns: The fetched VerificationAttemptsSummaryInstance + """ + return await self._proxy.fetch_async( + verify_service_sid=verify_service_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + country=country, + channel=channel, + destination_prefix=destination_prefix, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Verify.V2.VerificationAttemptsSummaryInstance>" + + +class VerificationAttemptsSummaryContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the VerificationAttemptsSummaryContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/Attempts/Summary" + + def fetch( + self, + verify_service_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union[ + "VerificationAttemptsSummaryInstance.Channels", object + ] = values.unset, + destination_prefix: Union[str, object] = values.unset, + ) -> VerificationAttemptsSummaryInstance: + """ + Fetch the VerificationAttemptsSummaryInstance + + :param verify_service_sid: Filter used to consider only Verification Attempts of the given verify service on the summary aggregation. + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. Valid values are `SMS`, `CALL` and `WHATSAPP` + :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. + + :returns: The fetched VerificationAttemptsSummaryInstance + """ + + data = values.of( + { + "VerifyServiceSid": verify_service_sid, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "Country": country, + "Channel": channel, + "DestinationPrefix": destination_prefix, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return VerificationAttemptsSummaryInstance( + self._version, + payload, + ) + + async def fetch_async( + self, + verify_service_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + country: Union[str, object] = values.unset, + channel: Union[ + "VerificationAttemptsSummaryInstance.Channels", object + ] = values.unset, + destination_prefix: Union[str, object] = values.unset, + ) -> VerificationAttemptsSummaryInstance: + """ + Asynchronous coroutine to fetch the VerificationAttemptsSummaryInstance + + :param verify_service_sid: Filter used to consider only Verification Attempts of the given verify service on the summary aggregation. + :param date_created_after: Datetime filter used to consider only Verification Attempts created after this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in ISO 8601 formatted datetime string: yyyy-MM-dd'T'HH:mm:ss'Z. + :param country: Filter used to consider only Verification Attempts sent to the specified destination country on the summary aggregation. + :param channel: Filter Verification Attempts considered on the summary aggregation by communication channel. Valid values are `SMS`, `CALL` and `WHATSAPP` + :param destination_prefix: Filter the Verification Attempts considered on the summary aggregation by Destination prefix. It is the prefix of a phone number in E.164 format. + + :returns: The fetched VerificationAttemptsSummaryInstance + """ + + data = values.of( + { + "VerifyServiceSid": verify_service_sid, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "Country": country, + "Channel": channel, + "DestinationPrefix": destination_prefix, + } + ) + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + + return VerificationAttemptsSummaryInstance( + self._version, + payload, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Verify.V2.VerificationAttemptsSummaryContext>" + + +class VerificationAttemptsSummaryList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the VerificationAttemptsSummaryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> VerificationAttemptsSummaryContext: + """ + Constructs a VerificationAttemptsSummaryContext + + """ + return VerificationAttemptsSummaryContext(self._version) + + def __call__(self) -> VerificationAttemptsSummaryContext: + """ + Constructs a VerificationAttemptsSummaryContext + + """ + return VerificationAttemptsSummaryContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Verify.V2.VerificationAttemptsSummaryList>" diff --git a/twilio/rest/video/VideoBase.py b/twilio/rest/video/VideoBase.py new file mode 100644 index 0000000000..0d2cf7e364 --- /dev/null +++ b/twilio/rest/video/VideoBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.video.v1 import V1 + + +class VideoBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Video Domain + + :returns: Domain for Video + """ + super().__init__(twilio, "https://video.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Video + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Video>" diff --git a/twilio/rest/video/__init__.py b/twilio/rest/video/__init__.py new file mode 100644 index 0000000000..d57e4f1ecc --- /dev/null +++ b/twilio/rest/video/__init__.py @@ -0,0 +1,65 @@ +from warnings import warn + +from twilio.rest.video.VideoBase import VideoBase +from twilio.rest.video.v1.composition import CompositionList +from twilio.rest.video.v1.composition_hook import CompositionHookList +from twilio.rest.video.v1.composition_settings import CompositionSettingsList +from twilio.rest.video.v1.recording import RecordingList +from twilio.rest.video.v1.recording_settings import RecordingSettingsList +from twilio.rest.video.v1.room import RoomList + + +class Video(VideoBase): + @property + def compositions(self) -> CompositionList: + warn( + "compositions is deprecated. Use v1.compositions instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.compositions + + @property + def composition_hooks(self) -> CompositionHookList: + warn( + "composition_hooks is deprecated. Use v1.composition_hooks instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.composition_hooks + + @property + def composition_settings(self) -> CompositionSettingsList: + warn( + "composition_settings is deprecated. Use v1.composition_settings instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.composition_settings + + @property + def recordings(self) -> RecordingList: + warn( + "recordings is deprecated. Use v1.recordings instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.recordings + + @property + def recording_settings(self) -> RecordingSettingsList: + warn( + "recording_settings is deprecated. Use v1.recording_settings instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.recording_settings + + @property + def rooms(self) -> RoomList: + warn( + "rooms is deprecated. Use v1.rooms instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.rooms diff --git a/twilio/rest/video/v1/__init__.py b/twilio/rest/video/v1/__init__.py new file mode 100644 index 0000000000..0667596a3f --- /dev/null +++ b/twilio/rest/video/v1/__init__.py @@ -0,0 +1,83 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.video.v1.composition import CompositionList +from twilio.rest.video.v1.composition_hook import CompositionHookList +from twilio.rest.video.v1.composition_settings import CompositionSettingsList +from twilio.rest.video.v1.recording import RecordingList +from twilio.rest.video.v1.recording_settings import RecordingSettingsList +from twilio.rest.video.v1.room import RoomList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Video + + :param domain: The Twilio.video domain + """ + super().__init__(domain, "v1") + self._compositions: Optional[CompositionList] = None + self._composition_hooks: Optional[CompositionHookList] = None + self._composition_settings: Optional[CompositionSettingsList] = None + self._recordings: Optional[RecordingList] = None + self._recording_settings: Optional[RecordingSettingsList] = None + self._rooms: Optional[RoomList] = None + + @property + def compositions(self) -> CompositionList: + if self._compositions is None: + self._compositions = CompositionList(self) + return self._compositions + + @property + def composition_hooks(self) -> CompositionHookList: + if self._composition_hooks is None: + self._composition_hooks = CompositionHookList(self) + return self._composition_hooks + + @property + def composition_settings(self) -> CompositionSettingsList: + if self._composition_settings is None: + self._composition_settings = CompositionSettingsList(self) + return self._composition_settings + + @property + def recordings(self) -> RecordingList: + if self._recordings is None: + self._recordings = RecordingList(self) + return self._recordings + + @property + def recording_settings(self) -> RecordingSettingsList: + if self._recording_settings is None: + self._recording_settings = RecordingSettingsList(self) + return self._recording_settings + + @property + def rooms(self) -> RoomList: + if self._rooms is None: + self._rooms = RoomList(self) + return self._rooms + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1>" diff --git a/twilio/rest/video/v1/composition.py b/twilio/rest/video/v1/composition.py new file mode 100644 index 0000000000..06f4d05f5f --- /dev/null +++ b/twilio/rest/video/v1/composition.py @@ -0,0 +1,695 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CompositionInstance(InstanceResource): + + class Format(object): + MP4 = "mp4" + WEBM = "webm" + + class Status(object): + ENQUEUED = "enqueued" + PROCESSING = "processing" + COMPLETED = "completed" + DELETED = "deleted" + FAILED = "failed" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Composition resource. + :ivar status: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_completed: The date and time in GMT when the composition's media processing task finished, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_deleted: The date and time in GMT when the composition generated media was deleted, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar sid: The unique string that we created to identify the Composition resource. + :ivar room_sid: The SID of the Group Room that generated the audio and video tracks used in the composition. All media sources included in a composition must belong to the same Group Room. + :ivar audio_sources: The array of track names to include in the composition. The composition includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this property can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :ivar audio_sources_excluded: The array of track names to exclude from the composition. The composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this property can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :ivar video_layout: An object that describes the video layout of the composition in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :ivar resolution: The dimensions of the video image in pixels expressed as columns (width) and rows (height). The string's format is `{width}x{height}`, such as `640x480`. + :ivar trim: Whether to remove intervals with no media, as specified in the POST request that created the composition. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :ivar format: + :ivar bitrate: The average bit rate of the composition's media. + :ivar size: The size of the composed media file in bytes. + :ivar duration: The duration of the composition's media file in seconds. + :ivar media_external_location: The URL of the media file associated with the composition when stored externally. See [External S3 Compositions](/docs/video/api/external-s3-compositions) for more details. + :ivar status_callback: The URL called using the `status_callback_method` to send status information on every composition event. + :ivar status_callback_method: The HTTP method used to call `status_callback`. Can be: `POST` or `GET`, defaults to `POST`. + :ivar url: The absolute URL of the resource. + :ivar links: The URL of the media file associated with the composition. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.status: Optional["CompositionInstance.Status"] = payload.get("status") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_completed: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_completed") + ) + self.date_deleted: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_deleted") + ) + self.sid: Optional[str] = payload.get("sid") + self.room_sid: Optional[str] = payload.get("room_sid") + self.audio_sources: Optional[List[str]] = payload.get("audio_sources") + self.audio_sources_excluded: Optional[List[str]] = payload.get( + "audio_sources_excluded" + ) + self.video_layout: Optional[Dict[str, object]] = payload.get("video_layout") + self.resolution: Optional[str] = payload.get("resolution") + self.trim: Optional[bool] = payload.get("trim") + self.format: Optional["CompositionInstance.Format"] = payload.get("format") + self.bitrate: Optional[int] = deserialize.integer(payload.get("bitrate")) + self.size: Optional[int] = payload.get("size") + self.duration: Optional[int] = deserialize.integer(payload.get("duration")) + self.media_external_location: Optional[str] = payload.get( + "media_external_location" + ) + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CompositionContext] = None + + @property + def _proxy(self) -> "CompositionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CompositionContext for this CompositionInstance + """ + if self._context is None: + self._context = CompositionContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CompositionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CompositionInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CompositionInstance": + """ + Fetch the CompositionInstance + + + :returns: The fetched CompositionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CompositionInstance": + """ + Asynchronous coroutine to fetch the CompositionInstance + + + :returns: The fetched CompositionInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.CompositionInstance {}>".format(context) + + +class CompositionContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CompositionContext + + :param version: Version that contains the resource + :param sid: The SID of the Composition resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Compositions/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CompositionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CompositionInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CompositionInstance: + """ + Fetch the CompositionInstance + + + :returns: The fetched CompositionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CompositionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CompositionInstance: + """ + Asynchronous coroutine to fetch the CompositionInstance + + + :returns: The fetched CompositionInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CompositionInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.CompositionContext {}>".format(context) + + +class CompositionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CompositionInstance: + """ + Build an instance of CompositionInstance + + :param payload: Payload response from the API + """ + return CompositionInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.CompositionPage>" + + +class CompositionList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CompositionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Compositions" + + def create( + self, + room_sid: str, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> CompositionInstance: + """ + Create the CompositionInstance + + :param room_sid: The SID of the Group Room with the media tracks to be used as composition sources. + :param video_layout: An object that describes the video layout of the composition in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :param audio_sources: An array of track names from the same group room to merge into the new composition. Can include zero or more track names. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` includes `student` as well as `studentTeam`. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :param audio_sources_excluded: An array of track names to exclude. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param trim: Whether to clip the intervals where there is no active media in the composition. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + + :returns: The created CompositionInstance + """ + + data = values.of( + { + "RoomSid": room_sid, + "VideoLayout": serialize.object(video_layout), + "AudioSources": serialize.map(audio_sources, lambda e: e), + "AudioSourcesExcluded": serialize.map( + audio_sources_excluded, lambda e: e + ), + "Resolution": resolution, + "Format": format, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Trim": serialize.boolean_to_string(trim), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CompositionInstance(self._version, payload) + + async def create_async( + self, + room_sid: str, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> CompositionInstance: + """ + Asynchronously create the CompositionInstance + + :param room_sid: The SID of the Group Room with the media tracks to be used as composition sources. + :param video_layout: An object that describes the video layout of the composition in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :param audio_sources: An array of track names from the same group room to merge into the new composition. Can include zero or more track names. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` includes `student` as well as `studentTeam`. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :param audio_sources_excluded: An array of track names to exclude. The new composition includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which will match zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param trim: Whether to clip the intervals where there is no active media in the composition. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + + :returns: The created CompositionInstance + """ + + data = values.of( + { + "RoomSid": room_sid, + "VideoLayout": serialize.object(video_layout), + "AudioSources": serialize.map(audio_sources, lambda e: e), + "AudioSourcesExcluded": serialize.map( + audio_sources_excluded, lambda e: e + ), + "Resolution": resolution, + "Format": format, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Trim": serialize.boolean_to_string(trim), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CompositionInstance(self._version, payload) + + def stream( + self, + status: Union["CompositionInstance.Status", object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + room_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CompositionInstance]: + """ + Streams CompositionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "CompositionInstance.Status" status: Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. + :param datetime date_created_after: Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only Composition resources created before this ISO 8601 date-time with time zone. + :param str room_sid: Read only Composition resources with this Room SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + date_created_after=date_created_after, + date_created_before=date_created_before, + room_sid=room_sid, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["CompositionInstance.Status", object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + room_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CompositionInstance]: + """ + Asynchronously streams CompositionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "CompositionInstance.Status" status: Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. + :param datetime date_created_after: Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only Composition resources created before this ISO 8601 date-time with time zone. + :param str room_sid: Read only Composition resources with this Room SID. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + date_created_after=date_created_after, + date_created_before=date_created_before, + room_sid=room_sid, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["CompositionInstance.Status", object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + room_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CompositionInstance]: + """ + Lists CompositionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "CompositionInstance.Status" status: Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. + :param datetime date_created_after: Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only Composition resources created before this ISO 8601 date-time with time zone. + :param str room_sid: Read only Composition resources with this Room SID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + date_created_after=date_created_after, + date_created_before=date_created_before, + room_sid=room_sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["CompositionInstance.Status", object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + room_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CompositionInstance]: + """ + Asynchronously lists CompositionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "CompositionInstance.Status" status: Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. + :param datetime date_created_after: Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only Composition resources created before this ISO 8601 date-time with time zone. + :param str room_sid: Read only Composition resources with this Room SID. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + date_created_after=date_created_after, + date_created_before=date_created_before, + room_sid=room_sid, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["CompositionInstance.Status", object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + room_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CompositionPage: + """ + Retrieve a single page of CompositionInstance records from the API. + Request is executed immediately + + :param status: Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. + :param date_created_after: Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param date_created_before: Read only Composition resources created before this ISO 8601 date-time with time zone. + :param room_sid: Read only Composition resources with this Room SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CompositionInstance + """ + data = values.of( + { + "Status": status, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "RoomSid": room_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CompositionPage(self._version, response) + + async def page_async( + self, + status: Union["CompositionInstance.Status", object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + room_sid: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CompositionPage: + """ + Asynchronously retrieve a single page of CompositionInstance records from the API. + Request is executed immediately + + :param status: Read only Composition resources with this status. Can be: `enqueued`, `processing`, `completed`, `deleted`, or `failed`. + :param date_created_after: Read only Composition resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param date_created_before: Read only Composition resources created before this ISO 8601 date-time with time zone. + :param room_sid: Read only Composition resources with this Room SID. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CompositionInstance + """ + data = values.of( + { + "Status": status, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "RoomSid": room_sid, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CompositionPage(self._version, response) + + def get_page(self, target_url: str) -> CompositionPage: + """ + Retrieve a specific page of CompositionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CompositionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CompositionPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CompositionPage: + """ + Asynchronously retrieve a specific page of CompositionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CompositionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CompositionPage(self._version, response) + + def get(self, sid: str) -> CompositionContext: + """ + Constructs a CompositionContext + + :param sid: The SID of the Composition resource to fetch. + """ + return CompositionContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CompositionContext: + """ + Constructs a CompositionContext + + :param sid: The SID of the Composition resource to fetch. + """ + return CompositionContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.CompositionList>" diff --git a/twilio/rest/video/v1/composition_hook.py b/twilio/rest/video/v1/composition_hook.py new file mode 100644 index 0000000000..30fead17b0 --- /dev/null +++ b/twilio/rest/video/v1/composition_hook.py @@ -0,0 +1,882 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CompositionHookInstance(InstanceResource): + + class Format(object): + MP4 = "mp4" + WEBM = "webm" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CompositionHook resource. + :ivar friendly_name: The string that you assigned to describe the resource. Can be up to 100 characters long and must be unique within the account. + :ivar enabled: Whether the CompositionHook is active. When `true`, the CompositionHook is triggered for every completed Group Room on the account. When `false`, the CompositionHook is never triggered. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar sid: The unique string that we created to identify the CompositionHook resource. + :ivar audio_sources: The array of track names to include in the compositions created by the composition hook. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this property can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :ivar audio_sources_excluded: The array of track names to exclude from the compositions created by the composition hook. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this property can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :ivar video_layout: A JSON object that describes the video layout of the composition in terms of regions as specified in the HTTP POST request that created the CompositionHook resource. See [POST Parameters](https://www.twilio.com/docs/video/api/compositions-resource#http-post-parameters) for more information. Please, be aware that either video_layout or audio_sources have to be provided to get a valid creation request + :ivar resolution: The dimensions of the video image in pixels expressed as columns (width) and rows (height). The string's format is `{width}x{height}`, such as `640x480`. + :ivar trim: Whether intervals with no media are clipped, as specified in the POST request that created the CompositionHook resource. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :ivar format: + :ivar status_callback: The URL we call using the `status_callback_method` to send status information to your application. + :ivar status_callback_method: The HTTP method we should use to call `status_callback`. Can be `POST` or `GET` and defaults to `POST`. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.enabled: Optional[bool] = payload.get("enabled") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.sid: Optional[str] = payload.get("sid") + self.audio_sources: Optional[List[str]] = payload.get("audio_sources") + self.audio_sources_excluded: Optional[List[str]] = payload.get( + "audio_sources_excluded" + ) + self.video_layout: Optional[Dict[str, object]] = payload.get("video_layout") + self.resolution: Optional[str] = payload.get("resolution") + self.trim: Optional[bool] = payload.get("trim") + self.format: Optional["CompositionHookInstance.Format"] = payload.get("format") + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CompositionHookContext] = None + + @property + def _proxy(self) -> "CompositionHookContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CompositionHookContext for this CompositionHookInstance + """ + if self._context is None: + self._context = CompositionHookContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CompositionHookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CompositionHookInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CompositionHookInstance": + """ + Fetch the CompositionHookInstance + + + :returns: The fetched CompositionHookInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CompositionHookInstance": + """ + Asynchronous coroutine to fetch the CompositionHookInstance + + + :returns: The fetched CompositionHookInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + trim: Union[bool, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + resolution: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> "CompositionHookInstance": + """ + Update the CompositionHookInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook never triggers. + :param video_layout: A JSON object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param trim: Whether to clip the intervals where there is no active media in the compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + + :returns: The updated CompositionHookInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + trim=trim, + format=format, + resolution=resolution, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) + + async def update_async( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + trim: Union[bool, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + resolution: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> "CompositionHookInstance": + """ + Asynchronous coroutine to update the CompositionHookInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook never triggers. + :param video_layout: A JSON object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param trim: Whether to clip the intervals where there is no active media in the compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + + :returns: The updated CompositionHookInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + enabled=enabled, + video_layout=video_layout, + audio_sources=audio_sources, + audio_sources_excluded=audio_sources_excluded, + trim=trim, + format=format, + resolution=resolution, + status_callback=status_callback, + status_callback_method=status_callback_method, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.CompositionHookInstance {}>".format(context) + + +class CompositionHookContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CompositionHookContext + + :param version: Version that contains the resource + :param sid: The SID of the CompositionHook resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/CompositionHooks/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CompositionHookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CompositionHookInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CompositionHookInstance: + """ + Fetch the CompositionHookInstance + + + :returns: The fetched CompositionHookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CompositionHookInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CompositionHookInstance: + """ + Asynchronous coroutine to fetch the CompositionHookInstance + + + :returns: The fetched CompositionHookInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CompositionHookInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + trim: Union[bool, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + resolution: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> CompositionHookInstance: + """ + Update the CompositionHookInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook never triggers. + :param video_layout: A JSON object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param trim: Whether to clip the intervals where there is no active media in the compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + + :returns: The updated CompositionHookInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Enabled": serialize.boolean_to_string(enabled), + "VideoLayout": serialize.object(video_layout), + "AudioSources": serialize.map(audio_sources, lambda e: e), + "AudioSourcesExcluded": serialize.map( + audio_sources_excluded, lambda e: e + ), + "Trim": serialize.boolean_to_string(trim), + "Format": format, + "Resolution": resolution, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CompositionHookInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + trim: Union[bool, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + resolution: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + ) -> CompositionHookInstance: + """ + Asynchronous coroutine to update the CompositionHookInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook never triggers. + :param video_layout: A JSON object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param trim: Whether to clip the intervals where there is no active media in the compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + + :returns: The updated CompositionHookInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Enabled": serialize.boolean_to_string(enabled), + "VideoLayout": serialize.object(video_layout), + "AudioSources": serialize.map(audio_sources, lambda e: e), + "AudioSourcesExcluded": serialize.map( + audio_sources_excluded, lambda e: e + ), + "Trim": serialize.boolean_to_string(trim), + "Format": format, + "Resolution": resolution, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CompositionHookInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.CompositionHookContext {}>".format(context) + + +class CompositionHookPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CompositionHookInstance: + """ + Build an instance of CompositionHookInstance + + :param payload: Payload response from the API + """ + return CompositionHookInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.CompositionHookPage>" + + +class CompositionHookList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CompositionHookList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/CompositionHooks" + + def create( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> CompositionHookInstance: + """ + Create the CompositionHookInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook will never be triggered. + :param video_layout: An object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param trim: Whether to clip the intervals where there is no active media in the Compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + + :returns: The created CompositionHookInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Enabled": serialize.boolean_to_string(enabled), + "VideoLayout": serialize.object(video_layout), + "AudioSources": serialize.map(audio_sources, lambda e: e), + "AudioSourcesExcluded": serialize.map( + audio_sources_excluded, lambda e: e + ), + "Resolution": resolution, + "Format": format, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Trim": serialize.boolean_to_string(trim), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CompositionHookInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + enabled: Union[bool, object] = values.unset, + video_layout: Union[object, object] = values.unset, + audio_sources: Union[List[str], object] = values.unset, + audio_sources_excluded: Union[List[str], object] = values.unset, + resolution: Union[str, object] = values.unset, + format: Union["CompositionHookInstance.Format", object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + trim: Union[bool, object] = values.unset, + ) -> CompositionHookInstance: + """ + Asynchronously create the CompositionHookInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It can be up to 100 characters long and it must be unique within the account. + :param enabled: Whether the composition hook is active. When `true`, the composition hook will be triggered for every completed Group Room in the account. When `false`, the composition hook will never be triggered. + :param video_layout: An object that describes the video layout of the composition hook in terms of regions. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param audio_sources: An array of track names from the same group room to merge into the compositions created by the composition hook. Can include zero or more track names. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` includes tracks named `student` as well as `studentTeam`. + :param audio_sources_excluded: An array of track names to exclude. A composition triggered by the composition hook includes all audio sources specified in `audio_sources` except for those specified in `audio_sources_excluded`. The track names in this parameter can include an asterisk as a wild card character, which matches zero or more characters in a track name. For example, `student*` excludes `student` as well as `studentTeam`. This parameter can also be empty. + :param resolution: A string that describes the columns (width) and rows (height) of the generated composed video in pixels. Defaults to `640x480`. The string's format is `{width}x{height}` where: * 16 <= `{width}` <= 1280 * 16 <= `{height}` <= 1280 * `{width}` * `{height}` <= 921,600 Typical values are: * HD = `1280x720` * PAL = `1024x576` * VGA = `640x480` * CIF = `320x240` Note that the `resolution` imposes an aspect ratio to the resulting composition. When the original video tracks are constrained by the aspect ratio, they are scaled to fit. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + :param format: + :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application on every composition event. If not provided, status callback events will not be dispatched. + :param status_callback_method: The HTTP method we should use to call `status_callback`. Can be: `POST` or `GET` and the default is `POST`. + :param trim: Whether to clip the intervals where there is no active media in the Compositions triggered by the composition hook. The default is `true`. Compositions with `trim` enabled are shorter when the Room is created and no Participant joins for a while as well as if all the Participants leave the room and join later, because those gaps will be removed. See [Specifying Video Layouts](https://www.twilio.com/docs/video/api/compositions-resource#specifying-video-layouts) for more info. + + :returns: The created CompositionHookInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Enabled": serialize.boolean_to_string(enabled), + "VideoLayout": serialize.object(video_layout), + "AudioSources": serialize.map(audio_sources, lambda e: e), + "AudioSourcesExcluded": serialize.map( + audio_sources_excluded, lambda e: e + ), + "Resolution": resolution, + "Format": format, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Trim": serialize.boolean_to_string(trim), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CompositionHookInstance(self._version, payload) + + def stream( + self, + enabled: Union[bool, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CompositionHookInstance]: + """ + Streams CompositionHookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool enabled: Read only CompositionHook resources with an `enabled` value that matches this parameter. + :param datetime date_created_after: Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param str friendly_name: Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + enabled=enabled, + date_created_after=date_created_after, + date_created_before=date_created_before, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + enabled: Union[bool, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CompositionHookInstance]: + """ + Asynchronously streams CompositionHookInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param bool enabled: Read only CompositionHook resources with an `enabled` value that matches this parameter. + :param datetime date_created_after: Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param str friendly_name: Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + enabled=enabled, + date_created_after=date_created_after, + date_created_before=date_created_before, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + enabled: Union[bool, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CompositionHookInstance]: + """ + Lists CompositionHookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool enabled: Read only CompositionHook resources with an `enabled` value that matches this parameter. + :param datetime date_created_after: Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param str friendly_name: Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + enabled=enabled, + date_created_after=date_created_after, + date_created_before=date_created_before, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + enabled: Union[bool, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CompositionHookInstance]: + """ + Asynchronously lists CompositionHookInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param bool enabled: Read only CompositionHook resources with an `enabled` value that matches this parameter. + :param datetime date_created_after: Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param str friendly_name: Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + enabled=enabled, + date_created_after=date_created_after, + date_created_before=date_created_before, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + enabled: Union[bool, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CompositionHookPage: + """ + Retrieve a single page of CompositionHookInstance records from the API. + Request is executed immediately + + :param enabled: Read only CompositionHook resources with an `enabled` value that matches this parameter. + :param date_created_after: Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param date_created_before: Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param friendly_name: Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CompositionHookInstance + """ + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CompositionHookPage(self._version, response) + + async def page_async( + self, + enabled: Union[bool, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CompositionHookPage: + """ + Asynchronously retrieve a single page of CompositionHookInstance records from the API. + Request is executed immediately + + :param enabled: Read only CompositionHook resources with an `enabled` value that matches this parameter. + :param date_created_after: Read only CompositionHook resources created on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param date_created_before: Read only CompositionHook resources created before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param friendly_name: Read only CompositionHook resources with friendly names that match this string. The match is not case sensitive and can include asterisk `*` characters as wildcard match. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CompositionHookInstance + """ + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "FriendlyName": friendly_name, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CompositionHookPage(self._version, response) + + def get_page(self, target_url: str) -> CompositionHookPage: + """ + Retrieve a specific page of CompositionHookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CompositionHookInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CompositionHookPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CompositionHookPage: + """ + Asynchronously retrieve a specific page of CompositionHookInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CompositionHookInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CompositionHookPage(self._version, response) + + def get(self, sid: str) -> CompositionHookContext: + """ + Constructs a CompositionHookContext + + :param sid: The SID of the CompositionHook resource to update. + """ + return CompositionHookContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CompositionHookContext: + """ + Constructs a CompositionHookContext + + :param sid: The SID of the CompositionHook resource to update. + """ + return CompositionHookContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.CompositionHookList>" diff --git a/twilio/rest/video/v1/composition_settings.py b/twilio/rest/video/v1/composition_settings.py new file mode 100644 index 0000000000..384ae692e8 --- /dev/null +++ b/twilio/rest/video/v1/composition_settings.py @@ -0,0 +1,318 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class CompositionSettingsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CompositionSettings resource. + :ivar friendly_name: The string that you assigned to describe the resource and that will be shown in the console + :ivar aws_credentials_sid: The SID of the stored Credential resource. + :ivar aws_s3_url: The URL of the AWS S3 bucket where the compositions are stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/compositions`, where `compositions` is the path in which you want the compositions to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :ivar aws_storage_enabled: Whether all compositions are written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. + :ivar encryption_key_sid: The SID of the Public Key resource used for encryption. + :ivar encryption_enabled: Whether all compositions are stored in an encrypted form. The default is `false`. + :ivar url: The absolute URL of the resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.aws_credentials_sid: Optional[str] = payload.get("aws_credentials_sid") + self.aws_s3_url: Optional[str] = payload.get("aws_s3_url") + self.aws_storage_enabled: Optional[bool] = payload.get("aws_storage_enabled") + self.encryption_key_sid: Optional[str] = payload.get("encryption_key_sid") + self.encryption_enabled: Optional[bool] = payload.get("encryption_enabled") + self.url: Optional[str] = payload.get("url") + + self._context: Optional[CompositionSettingsContext] = None + + @property + def _proxy(self) -> "CompositionSettingsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CompositionSettingsContext for this CompositionSettingsInstance + """ + if self._context is None: + self._context = CompositionSettingsContext( + self._version, + ) + return self._context + + def create( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> "CompositionSettingsInstance": + """ + Create the CompositionSettingsInstance + + :param friendly_name: A descriptive string that you create to describe the resource and show to the user in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the compositions should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/compositions`, where `compositions` is the path in which you want the compositions to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all compositions should be written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. + :param encryption_enabled: Whether all compositions should be stored in an encrypted form. The default is `false`. + + :returns: The created CompositionSettingsInstance + """ + return self._proxy.create( + friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + + async def create_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> "CompositionSettingsInstance": + """ + Asynchronous coroutine to create the CompositionSettingsInstance + + :param friendly_name: A descriptive string that you create to describe the resource and show to the user in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the compositions should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/compositions`, where `compositions` is the path in which you want the compositions to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all compositions should be written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. + :param encryption_enabled: Whether all compositions should be stored in an encrypted form. The default is `false`. + + :returns: The created CompositionSettingsInstance + """ + return await self._proxy.create_async( + friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + + def fetch(self) -> "CompositionSettingsInstance": + """ + Fetch the CompositionSettingsInstance + + + :returns: The fetched CompositionSettingsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CompositionSettingsInstance": + """ + Asynchronous coroutine to fetch the CompositionSettingsInstance + + + :returns: The fetched CompositionSettingsInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Video.V1.CompositionSettingsInstance>" + + +class CompositionSettingsContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the CompositionSettingsContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/CompositionSettings/Default" + + def create( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> CompositionSettingsInstance: + """ + Create the CompositionSettingsInstance + + :param friendly_name: A descriptive string that you create to describe the resource and show to the user in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the compositions should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/compositions`, where `compositions` is the path in which you want the compositions to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all compositions should be written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. + :param encryption_enabled: Whether all compositions should be stored in an encrypted form. The default is `false`. + + :returns: The created CompositionSettingsInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "AwsCredentialsSid": aws_credentials_sid, + "EncryptionKeySid": encryption_key_sid, + "AwsS3Url": aws_s3_url, + "AwsStorageEnabled": serialize.boolean_to_string(aws_storage_enabled), + "EncryptionEnabled": serialize.boolean_to_string(encryption_enabled), + } + ) + + payload = self._version.create(method="POST", uri=self._uri, data=data) + + return CompositionSettingsInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> CompositionSettingsInstance: + """ + Asynchronous coroutine to create the CompositionSettingsInstance + + :param friendly_name: A descriptive string that you create to describe the resource and show to the user in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the compositions should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/compositions`, where `compositions` is the path in which you want the compositions to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all compositions should be written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. + :param encryption_enabled: Whether all compositions should be stored in an encrypted form. The default is `false`. + + :returns: The created CompositionSettingsInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "AwsCredentialsSid": aws_credentials_sid, + "EncryptionKeySid": encryption_key_sid, + "AwsS3Url": aws_s3_url, + "AwsStorageEnabled": serialize.boolean_to_string(aws_storage_enabled), + "EncryptionEnabled": serialize.boolean_to_string(encryption_enabled), + } + ) + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data + ) + + return CompositionSettingsInstance(self._version, payload) + + def fetch(self) -> CompositionSettingsInstance: + """ + Fetch the CompositionSettingsInstance + + + :returns: The fetched CompositionSettingsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CompositionSettingsInstance( + self._version, + payload, + ) + + async def fetch_async(self) -> CompositionSettingsInstance: + """ + Asynchronous coroutine to fetch the CompositionSettingsInstance + + + :returns: The fetched CompositionSettingsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CompositionSettingsInstance( + self._version, + payload, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Video.V1.CompositionSettingsContext>" + + +class CompositionSettingsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CompositionSettingsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> CompositionSettingsContext: + """ + Constructs a CompositionSettingsContext + + """ + return CompositionSettingsContext(self._version) + + def __call__(self) -> CompositionSettingsContext: + """ + Constructs a CompositionSettingsContext + + """ + return CompositionSettingsContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.CompositionSettingsList>" diff --git a/twilio/rest/video/v1/recording.py b/twilio/rest/video/v1/recording.py new file mode 100644 index 0000000000..f474345fe0 --- /dev/null +++ b/twilio/rest/video/v1/recording.py @@ -0,0 +1,621 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RecordingInstance(InstanceResource): + + class Codec(object): + VP8 = "VP8" + H264 = "H264" + OPUS = "OPUS" + PCMU = "PCMU" + + class Format(object): + MKA = "mka" + MKV = "mkv" + + class Status(object): + PROCESSING = "processing" + COMPLETED = "completed" + DELETED = "deleted" + FAILED = "failed" + + class Type(object): + AUDIO = "audio" + VIDEO = "video" + DATA = "data" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Recording resource. + :ivar status: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar sid: The unique string that we created to identify the Recording resource. + :ivar source_sid: The SID of the recording source. For a Room Recording, this value is a `track_sid`. + :ivar size: The size of the recorded track, in bytes. + :ivar url: The absolute URL of the resource. + :ivar type: + :ivar duration: The duration of the recording in seconds rounded to the nearest second. Sub-second tracks have a `Duration` property of 1 second + :ivar container_format: + :ivar codec: + :ivar grouping_sids: A list of SIDs related to the recording. Includes the `room_sid` and `participant_sid`. + :ivar track_name: The name that was given to the source track of the recording. If no name is given, the `source_sid` is used. + :ivar offset: The time in milliseconds elapsed between an arbitrary point in time, common to all group rooms, and the moment when the source room of this track started. This information provides a synchronization mechanism for recordings belonging to the same room. + :ivar media_external_location: The URL of the media file associated with the recording when stored externally. See [External S3 Recordings](/docs/video/api/external-s3-recordings) for more details. + :ivar status_callback: The URL called using the `status_callback_method` to send status information on every recording event. + :ivar status_callback_method: The HTTP method used to call `status_callback`. Can be: `POST` or `GET`, defaults to `POST`. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.status: Optional["RecordingInstance.Status"] = payload.get("status") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.sid: Optional[str] = payload.get("sid") + self.source_sid: Optional[str] = payload.get("source_sid") + self.size: Optional[int] = payload.get("size") + self.url: Optional[str] = payload.get("url") + self.type: Optional["RecordingInstance.Type"] = payload.get("type") + self.duration: Optional[int] = deserialize.integer(payload.get("duration")) + self.container_format: Optional["RecordingInstance.Format"] = payload.get( + "container_format" + ) + self.codec: Optional["RecordingInstance.Codec"] = payload.get("codec") + self.grouping_sids: Optional[Dict[str, object]] = payload.get("grouping_sids") + self.track_name: Optional[str] = payload.get("track_name") + self.offset: Optional[int] = payload.get("offset") + self.media_external_location: Optional[str] = payload.get( + "media_external_location" + ) + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[RecordingContext] = None + + @property + def _proxy(self) -> "RecordingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RecordingContext for this RecordingInstance + """ + if self._context is None: + self._context = RecordingContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RecordingInstance": + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RecordingInstance": + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.RecordingInstance {}>".format(context) + + +class RecordingContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the RecordingContext + + :param version: Version that contains the resource + :param sid: The SID of the Recording resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Recordings/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RecordingInstance: + """ + Fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RecordingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RecordingInstance: + """ + Asynchronous coroutine to fetch the RecordingInstance + + + :returns: The fetched RecordingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RecordingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.RecordingContext {}>".format(context) + + +class RecordingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: + """ + Build an instance of RecordingInstance + + :param payload: Payload response from the API + """ + return RecordingInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.RecordingPage>" + + +class RecordingList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RecordingList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Recordings" + + def stream( + self, + status: Union["RecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + grouping_sid: Union[List[str], object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + media_type: Union["RecordingInstance.Type", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RecordingInstance]: + """ + Streams RecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "RecordingInstance.Status" status: Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param List[str] grouping_sid: Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. + :param "RecordingInstance.Type" media_type: Read only recordings that have this media type. Can be either `audio` or `video`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + source_sid=source_sid, + grouping_sid=grouping_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + media_type=media_type, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["RecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + grouping_sid: Union[List[str], object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + media_type: Union["RecordingInstance.Type", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RecordingInstance]: + """ + Asynchronously streams RecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "RecordingInstance.Status" status: Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param List[str] grouping_sid: Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. + :param "RecordingInstance.Type" media_type: Read only recordings that have this media type. Can be either `audio` or `video`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + source_sid=source_sid, + grouping_sid=grouping_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + media_type=media_type, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["RecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + grouping_sid: Union[List[str], object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + media_type: Union["RecordingInstance.Type", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordingInstance]: + """ + Lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RecordingInstance.Status" status: Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param List[str] grouping_sid: Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. + :param "RecordingInstance.Type" media_type: Read only recordings that have this media type. Can be either `audio` or `video`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + source_sid=source_sid, + grouping_sid=grouping_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + media_type=media_type, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["RecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + grouping_sid: Union[List[str], object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + media_type: Union["RecordingInstance.Type", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RecordingInstance]: + """ + Asynchronously lists RecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RecordingInstance.Status" status: Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param List[str] grouping_sid: Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param datetime date_created_before: Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. + :param "RecordingInstance.Type" media_type: Read only recordings that have this media type. Can be either `audio` or `video`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + source_sid=source_sid, + grouping_sid=grouping_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + media_type=media_type, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["RecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + grouping_sid: Union[List[str], object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + media_type: Union["RecordingInstance.Type", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordingPage: + """ + Retrieve a single page of RecordingInstance records from the API. + Request is executed immediately + + :param status: Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. + :param source_sid: Read only the recordings that have this `source_sid`. + :param grouping_sid: Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. + :param date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param date_created_before: Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. + :param media_type: Read only recordings that have this media type. Can be either `audio` or `video`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordingInstance + """ + data = values.of( + { + "Status": status, + "SourceSid": source_sid, + "GroupingSid": serialize.map(grouping_sid, lambda e: e), + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "MediaType": media_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response) + + async def page_async( + self, + status: Union["RecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + grouping_sid: Union[List[str], object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + media_type: Union["RecordingInstance.Type", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RecordingPage: + """ + Asynchronously retrieve a single page of RecordingInstance records from the API. + Request is executed immediately + + :param status: Read only the recordings that have this status. Can be: `processing`, `completed`, or `deleted`. + :param source_sid: Read only the recordings that have this `source_sid`. + :param grouping_sid: Read only recordings with this `grouping_sid`, which may include a `participant_sid` and/or a `room_sid`. + :param date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone. + :param date_created_before: Read only recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone, given as `YYYY-MM-DDThh:mm:ss+|-hh:mm` or `YYYY-MM-DDThh:mm:ssZ`. + :param media_type: Read only recordings that have this media type. Can be either `audio` or `video`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RecordingInstance + """ + data = values.of( + { + "Status": status, + "SourceSid": source_sid, + "GroupingSid": serialize.map(grouping_sid, lambda e: e), + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "MediaType": media_type, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RecordingPage(self._version, response) + + def get_page(self, target_url: str) -> RecordingPage: + """ + Retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RecordingPage(self._version, response) + + async def get_page_async(self, target_url: str) -> RecordingPage: + """ + Asynchronously retrieve a specific page of RecordingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RecordingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RecordingPage(self._version, response) + + def get(self, sid: str) -> RecordingContext: + """ + Constructs a RecordingContext + + :param sid: The SID of the Recording resource to fetch. + """ + return RecordingContext(self._version, sid=sid) + + def __call__(self, sid: str) -> RecordingContext: + """ + Constructs a RecordingContext + + :param sid: The SID of the Recording resource to fetch. + """ + return RecordingContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.RecordingList>" diff --git a/twilio/rest/video/v1/recording_settings.py b/twilio/rest/video/v1/recording_settings.py new file mode 100644 index 0000000000..46259b6cf8 --- /dev/null +++ b/twilio/rest/video/v1/recording_settings.py @@ -0,0 +1,318 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class RecordingSettingsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the RecordingSettings resource. + :ivar friendly_name: The string that you assigned to describe the resource and show the user in the console + :ivar aws_credentials_sid: The SID of the stored Credential resource. + :ivar aws_s3_url: The URL of the AWS S3 bucket where the recordings are stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/recordings`, where `recordings` is the path in which you want the recordings to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :ivar aws_storage_enabled: Whether all recordings are written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. + :ivar encryption_key_sid: The SID of the Public Key resource used for encryption. + :ivar encryption_enabled: Whether all recordings are stored in an encrypted form. The default is `false`. + :ivar url: The absolute URL of the resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.aws_credentials_sid: Optional[str] = payload.get("aws_credentials_sid") + self.aws_s3_url: Optional[str] = payload.get("aws_s3_url") + self.aws_storage_enabled: Optional[bool] = payload.get("aws_storage_enabled") + self.encryption_key_sid: Optional[str] = payload.get("encryption_key_sid") + self.encryption_enabled: Optional[bool] = payload.get("encryption_enabled") + self.url: Optional[str] = payload.get("url") + + self._context: Optional[RecordingSettingsContext] = None + + @property + def _proxy(self) -> "RecordingSettingsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RecordingSettingsContext for this RecordingSettingsInstance + """ + if self._context is None: + self._context = RecordingSettingsContext( + self._version, + ) + return self._context + + def create( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> "RecordingSettingsInstance": + """ + Create the RecordingSettingsInstance + + :param friendly_name: A descriptive string that you create to describe the resource and be shown to users in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the recordings should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/recordings`, where `recordings` is the path in which you want the recordings to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all recordings should be written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. + :param encryption_enabled: Whether all recordings should be stored in an encrypted form. The default is `false`. + + :returns: The created RecordingSettingsInstance + """ + return self._proxy.create( + friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + + async def create_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> "RecordingSettingsInstance": + """ + Asynchronous coroutine to create the RecordingSettingsInstance + + :param friendly_name: A descriptive string that you create to describe the resource and be shown to users in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the recordings should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/recordings`, where `recordings` is the path in which you want the recordings to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all recordings should be written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. + :param encryption_enabled: Whether all recordings should be stored in an encrypted form. The default is `false`. + + :returns: The created RecordingSettingsInstance + """ + return await self._proxy.create_async( + friendly_name, + aws_credentials_sid=aws_credentials_sid, + encryption_key_sid=encryption_key_sid, + aws_s3_url=aws_s3_url, + aws_storage_enabled=aws_storage_enabled, + encryption_enabled=encryption_enabled, + ) + + def fetch(self) -> "RecordingSettingsInstance": + """ + Fetch the RecordingSettingsInstance + + + :returns: The fetched RecordingSettingsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RecordingSettingsInstance": + """ + Asynchronous coroutine to fetch the RecordingSettingsInstance + + + :returns: The fetched RecordingSettingsInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Video.V1.RecordingSettingsInstance>" + + +class RecordingSettingsContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the RecordingSettingsContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/RecordingSettings/Default" + + def create( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> RecordingSettingsInstance: + """ + Create the RecordingSettingsInstance + + :param friendly_name: A descriptive string that you create to describe the resource and be shown to users in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the recordings should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/recordings`, where `recordings` is the path in which you want the recordings to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all recordings should be written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. + :param encryption_enabled: Whether all recordings should be stored in an encrypted form. The default is `false`. + + :returns: The created RecordingSettingsInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "AwsCredentialsSid": aws_credentials_sid, + "EncryptionKeySid": encryption_key_sid, + "AwsS3Url": aws_s3_url, + "AwsStorageEnabled": serialize.boolean_to_string(aws_storage_enabled), + "EncryptionEnabled": serialize.boolean_to_string(encryption_enabled), + } + ) + + payload = self._version.create(method="POST", uri=self._uri, data=data) + + return RecordingSettingsInstance(self._version, payload) + + async def create_async( + self, + friendly_name: str, + aws_credentials_sid: Union[str, object] = values.unset, + encryption_key_sid: Union[str, object] = values.unset, + aws_s3_url: Union[str, object] = values.unset, + aws_storage_enabled: Union[bool, object] = values.unset, + encryption_enabled: Union[bool, object] = values.unset, + ) -> RecordingSettingsInstance: + """ + Asynchronous coroutine to create the RecordingSettingsInstance + + :param friendly_name: A descriptive string that you create to describe the resource and be shown to users in the console + :param aws_credentials_sid: The SID of the stored Credential resource. + :param encryption_key_sid: The SID of the Public Key resource to use for encryption. + :param aws_s3_url: The URL of the AWS S3 bucket where the recordings should be stored. We only support DNS-compliant URLs like `https://documentation-example-twilio-bucket/recordings`, where `recordings` is the path in which you want the recordings to be stored. This URL accepts only URI-valid characters, as described in the [RFC 3986](https://tools.ietf.org/html/rfc3986#section-2). + :param aws_storage_enabled: Whether all recordings should be written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. + :param encryption_enabled: Whether all recordings should be stored in an encrypted form. The default is `false`. + + :returns: The created RecordingSettingsInstance + """ + data = values.of( + { + "FriendlyName": friendly_name, + "AwsCredentialsSid": aws_credentials_sid, + "EncryptionKeySid": encryption_key_sid, + "AwsS3Url": aws_s3_url, + "AwsStorageEnabled": serialize.boolean_to_string(aws_storage_enabled), + "EncryptionEnabled": serialize.boolean_to_string(encryption_enabled), + } + ) + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data + ) + + return RecordingSettingsInstance(self._version, payload) + + def fetch(self) -> RecordingSettingsInstance: + """ + Fetch the RecordingSettingsInstance + + + :returns: The fetched RecordingSettingsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RecordingSettingsInstance( + self._version, + payload, + ) + + async def fetch_async(self) -> RecordingSettingsInstance: + """ + Asynchronous coroutine to fetch the RecordingSettingsInstance + + + :returns: The fetched RecordingSettingsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RecordingSettingsInstance( + self._version, + payload, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Video.V1.RecordingSettingsContext>" + + +class RecordingSettingsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RecordingSettingsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> RecordingSettingsContext: + """ + Constructs a RecordingSettingsContext + + """ + return RecordingSettingsContext(self._version) + + def __call__(self) -> RecordingSettingsContext: + """ + Constructs a RecordingSettingsContext + + """ + return RecordingSettingsContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.RecordingSettingsList>" diff --git a/twilio/rest/video/v1/room/__init__.py b/twilio/rest/video/v1/room/__init__.py new file mode 100644 index 0000000000..d51b8b8711 --- /dev/null +++ b/twilio/rest/video/v1/room/__init__.py @@ -0,0 +1,867 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.video.v1.room.participant import ParticipantList +from twilio.rest.video.v1.room.recording_rules import RecordingRulesList +from twilio.rest.video.v1.room.room_recording import RoomRecordingList + + +class RoomInstance(InstanceResource): + + class RoomStatus(object): + IN_PROGRESS = "in-progress" + COMPLETED = "completed" + FAILED = "failed" + + class RoomType(object): + GO = "go" + PEER_TO_PEER = "peer-to-peer" + GROUP = "group" + GROUP_SMALL = "group-small" + + class VideoCodec(object): + VP8 = "VP8" + H264 = "H264" + + """ + :ivar sid: The unique string that Twilio created to identify the Room resource. + :ivar status: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Room resource. + :ivar enable_turn: Deprecated, now always considered to be true. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used as a `room_sid` in place of the resource's `sid` in the URL to address the resource, assuming it does not contain any [reserved characters](https://tools.ietf.org/html/rfc3986#section-2.2) that would need to be URL encoded. This value is unique for `in-progress` rooms. SDK clients can use this name to connect to the room. REST API clients can use this name in place of the Room SID to interact with the room as long as the room is `in-progress`. + :ivar status_callback: The URL Twilio calls using the `status_callback_method` to send status information to your application on every room event. See [Status Callbacks](https://www.twilio.com/docs/video/api/status-callbacks) for more info. + :ivar status_callback_method: The HTTP method Twilio uses to call `status_callback`. Can be `POST` or `GET` and defaults to `POST`. + :ivar end_time: The UTC end time of the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :ivar duration: The duration of the room in seconds. + :ivar type: + :ivar max_participants: The maximum number of concurrent Participants allowed in the room. + :ivar max_participant_duration: The maximum number of seconds a Participant can be connected to the room. The maximum possible value is 86400 seconds (24 hours). The default is 14400 seconds (4 hours). + :ivar max_concurrent_published_tracks: The maximum number of published audio, video, and data tracks all participants combined are allowed to publish in the room at the same time. Check [Programmable Video Limits](https://www.twilio.com/docs/video/programmable-video-limits) for more details. If it is set to 0 it means unconstrained. + :ivar record_participants_on_connect: Whether to start recording when Participants connect. + :ivar video_codecs: An array of the video codecs that are supported when publishing a track in the room. Can be: `VP8` and `H264`. + :ivar media_region: The region for the Room's media server. Can be one of the [available Media Regions](https://www.twilio.com/docs/video/ip-addresses#media-servers). + :ivar audio_only: When set to true, indicates that the participants in the room will only publish audio. No video tracks will be allowed. + :ivar empty_room_timeout: Specifies how long (in minutes) a room will remain active after last participant leaves. Can be configured when creating a room via REST API. For Ad-Hoc rooms this value cannot be changed. + :ivar unused_room_timeout: Specifies how long (in minutes) a room will remain active if no one joins. Can be configured when creating a room via REST API. For Ad-Hoc rooms this value cannot be changed. + :ivar large_room: Indicates if this is a large room. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.status: Optional["RoomInstance.RoomStatus"] = payload.get("status") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.account_sid: Optional[str] = payload.get("account_sid") + self.enable_turn: Optional[bool] = payload.get("enable_turn") + self.unique_name: Optional[str] = payload.get("unique_name") + self.status_callback: Optional[str] = payload.get("status_callback") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.duration: Optional[int] = deserialize.integer(payload.get("duration")) + self.type: Optional["RoomInstance.RoomType"] = payload.get("type") + self.max_participants: Optional[int] = deserialize.integer( + payload.get("max_participants") + ) + self.max_participant_duration: Optional[int] = deserialize.integer( + payload.get("max_participant_duration") + ) + self.max_concurrent_published_tracks: Optional[int] = deserialize.integer( + payload.get("max_concurrent_published_tracks") + ) + self.record_participants_on_connect: Optional[bool] = payload.get( + "record_participants_on_connect" + ) + self.video_codecs: Optional[List["RoomInstance.VideoCodec"]] = payload.get( + "video_codecs" + ) + self.media_region: Optional[str] = payload.get("media_region") + self.audio_only: Optional[bool] = payload.get("audio_only") + self.empty_room_timeout: Optional[int] = deserialize.integer( + payload.get("empty_room_timeout") + ) + self.unused_room_timeout: Optional[int] = deserialize.integer( + payload.get("unused_room_timeout") + ) + self.large_room: Optional[bool] = payload.get("large_room") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[RoomContext] = None + + @property + def _proxy(self) -> "RoomContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoomContext for this RoomInstance + """ + if self._context is None: + self._context = RoomContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "RoomInstance": + """ + Fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RoomInstance": + """ + Asynchronous coroutine to fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + return await self._proxy.fetch_async() + + def update(self, status: "RoomInstance.RoomStatus") -> "RoomInstance": + """ + Update the RoomInstance + + :param status: + + :returns: The updated RoomInstance + """ + return self._proxy.update( + status=status, + ) + + async def update_async(self, status: "RoomInstance.RoomStatus") -> "RoomInstance": + """ + Asynchronous coroutine to update the RoomInstance + + :param status: + + :returns: The updated RoomInstance + """ + return await self._proxy.update_async( + status=status, + ) + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + return self._proxy.participants + + @property + def recording_rules(self) -> RecordingRulesList: + """ + Access the recording_rules + """ + return self._proxy.recording_rules + + @property + def recordings(self) -> RoomRecordingList: + """ + Access the recordings + """ + return self._proxy.recordings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.RoomInstance {}>".format(context) + + +class RoomContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the RoomContext + + :param version: Version that contains the resource + :param sid: The SID of the Room resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Rooms/{sid}".format(**self._solution) + + self._participants: Optional[ParticipantList] = None + self._recording_rules: Optional[RecordingRulesList] = None + self._recordings: Optional[RoomRecordingList] = None + + def fetch(self) -> RoomInstance: + """ + Fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RoomInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RoomInstance: + """ + Asynchronous coroutine to fetch the RoomInstance + + + :returns: The fetched RoomInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RoomInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update(self, status: "RoomInstance.RoomStatus") -> RoomInstance: + """ + Update the RoomInstance + + :param status: + + :returns: The updated RoomInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoomInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async(self, status: "RoomInstance.RoomStatus") -> RoomInstance: + """ + Asynchronous coroutine to update the RoomInstance + + :param status: + + :returns: The updated RoomInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoomInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def participants(self) -> ParticipantList: + """ + Access the participants + """ + if self._participants is None: + self._participants = ParticipantList( + self._version, + self._solution["sid"], + ) + return self._participants + + @property + def recording_rules(self) -> RecordingRulesList: + """ + Access the recording_rules + """ + if self._recording_rules is None: + self._recording_rules = RecordingRulesList( + self._version, + self._solution["sid"], + ) + return self._recording_rules + + @property + def recordings(self) -> RoomRecordingList: + """ + Access the recordings + """ + if self._recordings is None: + self._recordings = RoomRecordingList( + self._version, + self._solution["sid"], + ) + return self._recordings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.RoomContext {}>".format(context) + + +class RoomPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoomInstance: + """ + Build an instance of RoomInstance + + :param payload: Payload response from the API + """ + return RoomInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.RoomPage>" + + +class RoomList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RoomList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Rooms" + + def create( + self, + enable_turn: Union[bool, object] = values.unset, + type: Union["RoomInstance.RoomType", object] = values.unset, + unique_name: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + max_participants: Union[int, object] = values.unset, + record_participants_on_connect: Union[bool, object] = values.unset, + transcribe_participants_on_connect: Union[bool, object] = values.unset, + video_codecs: Union[List["RoomInstance.VideoCodec"], object] = values.unset, + media_region: Union[str, object] = values.unset, + recording_rules: Union[object, object] = values.unset, + transcriptions_configuration: Union[object, object] = values.unset, + audio_only: Union[bool, object] = values.unset, + max_participant_duration: Union[int, object] = values.unset, + empty_room_timeout: Union[int, object] = values.unset, + unused_room_timeout: Union[int, object] = values.unset, + large_room: Union[bool, object] = values.unset, + ) -> RoomInstance: + """ + Create the RoomInstance + + :param enable_turn: Deprecated, now always considered to be true. + :param type: + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as a `room_sid` in place of the resource's `sid` in the URL to address the resource, assuming it does not contain any [reserved characters](https://tools.ietf.org/html/rfc3986#section-2.2) that would need to be URL encoded. This value is unique for `in-progress` rooms. SDK clients can use this name to connect to the room. REST API clients can use this name in place of the Room SID to interact with the room as long as the room is `in-progress`. + :param status_callback: The URL Twilio should call using the `status_callback_method` to send status information to your application on every room event. See [Status Callbacks](https://www.twilio.com/docs/video/api/status-callbacks) for more info. + :param status_callback_method: The HTTP method Twilio should use to call `status_callback`. Can be `POST` or `GET`. + :param max_participants: The maximum number of concurrent Participants allowed in the room. The maximum allowed value is 50. + :param record_participants_on_connect: Whether to start recording when Participants connect. + :param transcribe_participants_on_connect: Whether to start transcriptions when Participants connect. If TranscriptionsConfiguration is not provided, default settings will be used. + :param video_codecs: An array of the video codecs that are supported when publishing a track in the room. Can be: `VP8` and `H264`. + :param media_region: The region for the Room's media server. Can be one of the [available Media Regions](https://www.twilio.com/docs/video/ip-addresses#group-rooms-media-servers). + :param recording_rules: A collection of Recording Rules that describe how to include or exclude matching tracks for recording + :param transcriptions_configuration: A collection of properties that describe transcription behaviour. If TranscribeParticipantsOnConnect is set to true and TranscriptionsConfiguration is not provided, default settings will be used. + :param audio_only: When set to true, indicates that the participants in the room will only publish audio. No video tracks will be allowed. + :param max_participant_duration: The maximum number of seconds a Participant can be connected to the room. The maximum possible value is 86400 seconds (24 hours). The default is 14400 seconds (4 hours). + :param empty_room_timeout: Configures how long (in minutes) a room will remain active after last participant leaves. Valid values range from 1 to 60 minutes (no fractions). + :param unused_room_timeout: Configures how long (in minutes) a room will remain active if no one joins. Valid values range from 1 to 60 minutes (no fractions). + :param large_room: When set to true, indicated that this is the large room. + + :returns: The created RoomInstance + """ + + data = values.of( + { + "EnableTurn": serialize.boolean_to_string(enable_turn), + "Type": type, + "UniqueName": unique_name, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "MaxParticipants": max_participants, + "RecordParticipantsOnConnect": serialize.boolean_to_string( + record_participants_on_connect + ), + "TranscribeParticipantsOnConnect": serialize.boolean_to_string( + transcribe_participants_on_connect + ), + "VideoCodecs": serialize.map(video_codecs, lambda e: e), + "MediaRegion": media_region, + "RecordingRules": serialize.object(recording_rules), + "TranscriptionsConfiguration": serialize.object( + transcriptions_configuration + ), + "AudioOnly": serialize.boolean_to_string(audio_only), + "MaxParticipantDuration": max_participant_duration, + "EmptyRoomTimeout": empty_room_timeout, + "UnusedRoomTimeout": unused_room_timeout, + "LargeRoom": serialize.boolean_to_string(large_room), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoomInstance(self._version, payload) + + async def create_async( + self, + enable_turn: Union[bool, object] = values.unset, + type: Union["RoomInstance.RoomType", object] = values.unset, + unique_name: Union[str, object] = values.unset, + status_callback: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + max_participants: Union[int, object] = values.unset, + record_participants_on_connect: Union[bool, object] = values.unset, + transcribe_participants_on_connect: Union[bool, object] = values.unset, + video_codecs: Union[List["RoomInstance.VideoCodec"], object] = values.unset, + media_region: Union[str, object] = values.unset, + recording_rules: Union[object, object] = values.unset, + transcriptions_configuration: Union[object, object] = values.unset, + audio_only: Union[bool, object] = values.unset, + max_participant_duration: Union[int, object] = values.unset, + empty_room_timeout: Union[int, object] = values.unset, + unused_room_timeout: Union[int, object] = values.unset, + large_room: Union[bool, object] = values.unset, + ) -> RoomInstance: + """ + Asynchronously create the RoomInstance + + :param enable_turn: Deprecated, now always considered to be true. + :param type: + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used as a `room_sid` in place of the resource's `sid` in the URL to address the resource, assuming it does not contain any [reserved characters](https://tools.ietf.org/html/rfc3986#section-2.2) that would need to be URL encoded. This value is unique for `in-progress` rooms. SDK clients can use this name to connect to the room. REST API clients can use this name in place of the Room SID to interact with the room as long as the room is `in-progress`. + :param status_callback: The URL Twilio should call using the `status_callback_method` to send status information to your application on every room event. See [Status Callbacks](https://www.twilio.com/docs/video/api/status-callbacks) for more info. + :param status_callback_method: The HTTP method Twilio should use to call `status_callback`. Can be `POST` or `GET`. + :param max_participants: The maximum number of concurrent Participants allowed in the room. The maximum allowed value is 50. + :param record_participants_on_connect: Whether to start recording when Participants connect. + :param transcribe_participants_on_connect: Whether to start transcriptions when Participants connect. If TranscriptionsConfiguration is not provided, default settings will be used. + :param video_codecs: An array of the video codecs that are supported when publishing a track in the room. Can be: `VP8` and `H264`. + :param media_region: The region for the Room's media server. Can be one of the [available Media Regions](https://www.twilio.com/docs/video/ip-addresses#group-rooms-media-servers). + :param recording_rules: A collection of Recording Rules that describe how to include or exclude matching tracks for recording + :param transcriptions_configuration: A collection of properties that describe transcription behaviour. If TranscribeParticipantsOnConnect is set to true and TranscriptionsConfiguration is not provided, default settings will be used. + :param audio_only: When set to true, indicates that the participants in the room will only publish audio. No video tracks will be allowed. + :param max_participant_duration: The maximum number of seconds a Participant can be connected to the room. The maximum possible value is 86400 seconds (24 hours). The default is 14400 seconds (4 hours). + :param empty_room_timeout: Configures how long (in minutes) a room will remain active after last participant leaves. Valid values range from 1 to 60 minutes (no fractions). + :param unused_room_timeout: Configures how long (in minutes) a room will remain active if no one joins. Valid values range from 1 to 60 minutes (no fractions). + :param large_room: When set to true, indicated that this is the large room. + + :returns: The created RoomInstance + """ + + data = values.of( + { + "EnableTurn": serialize.boolean_to_string(enable_turn), + "Type": type, + "UniqueName": unique_name, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "MaxParticipants": max_participants, + "RecordParticipantsOnConnect": serialize.boolean_to_string( + record_participants_on_connect + ), + "TranscribeParticipantsOnConnect": serialize.boolean_to_string( + transcribe_participants_on_connect + ), + "VideoCodecs": serialize.map(video_codecs, lambda e: e), + "MediaRegion": media_region, + "RecordingRules": serialize.object(recording_rules), + "TranscriptionsConfiguration": serialize.object( + transcriptions_configuration + ), + "AudioOnly": serialize.boolean_to_string(audio_only), + "MaxParticipantDuration": max_participant_duration, + "EmptyRoomTimeout": empty_room_timeout, + "UnusedRoomTimeout": unused_room_timeout, + "LargeRoom": serialize.boolean_to_string(large_room), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RoomInstance(self._version, payload) + + def stream( + self, + status: Union["RoomInstance.RoomStatus", object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoomInstance]: + """ + Streams RoomInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "RoomInstance.RoomStatus" status: Read only the rooms with this status. Can be: `in-progress` (default) or `completed` + :param str unique_name: Read only rooms with the this `unique_name`. + :param datetime date_created_after: Read only rooms that started on or after this date, given as `YYYY-MM-DD`. + :param datetime date_created_before: Read only rooms that started before this date, given as `YYYY-MM-DD`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + unique_name=unique_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["RoomInstance.RoomStatus", object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoomInstance]: + """ + Asynchronously streams RoomInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "RoomInstance.RoomStatus" status: Read only the rooms with this status. Can be: `in-progress` (default) or `completed` + :param str unique_name: Read only rooms with the this `unique_name`. + :param datetime date_created_after: Read only rooms that started on or after this date, given as `YYYY-MM-DD`. + :param datetime date_created_before: Read only rooms that started before this date, given as `YYYY-MM-DD`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + unique_name=unique_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["RoomInstance.RoomStatus", object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoomInstance]: + """ + Lists RoomInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RoomInstance.RoomStatus" status: Read only the rooms with this status. Can be: `in-progress` (default) or `completed` + :param str unique_name: Read only rooms with the this `unique_name`. + :param datetime date_created_after: Read only rooms that started on or after this date, given as `YYYY-MM-DD`. + :param datetime date_created_before: Read only rooms that started before this date, given as `YYYY-MM-DD`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + unique_name=unique_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["RoomInstance.RoomStatus", object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoomInstance]: + """ + Asynchronously lists RoomInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RoomInstance.RoomStatus" status: Read only the rooms with this status. Can be: `in-progress` (default) or `completed` + :param str unique_name: Read only rooms with the this `unique_name`. + :param datetime date_created_after: Read only rooms that started on or after this date, given as `YYYY-MM-DD`. + :param datetime date_created_before: Read only rooms that started before this date, given as `YYYY-MM-DD`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + unique_name=unique_name, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["RoomInstance.RoomStatus", object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RoomPage: + """ + Retrieve a single page of RoomInstance records from the API. + Request is executed immediately + + :param status: Read only the rooms with this status. Can be: `in-progress` (default) or `completed` + :param unique_name: Read only rooms with the this `unique_name`. + :param date_created_after: Read only rooms that started on or after this date, given as `YYYY-MM-DD`. + :param date_created_before: Read only rooms that started before this date, given as `YYYY-MM-DD`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoomInstance + """ + data = values.of( + { + "Status": status, + "UniqueName": unique_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RoomPage(self._version, response) + + async def page_async( + self, + status: Union["RoomInstance.RoomStatus", object] = values.unset, + unique_name: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RoomPage: + """ + Asynchronously retrieve a single page of RoomInstance records from the API. + Request is executed immediately + + :param status: Read only the rooms with this status. Can be: `in-progress` (default) or `completed` + :param unique_name: Read only rooms with the this `unique_name`. + :param date_created_after: Read only rooms that started on or after this date, given as `YYYY-MM-DD`. + :param date_created_before: Read only rooms that started before this date, given as `YYYY-MM-DD`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoomInstance + """ + data = values.of( + { + "Status": status, + "UniqueName": unique_name, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RoomPage(self._version, response) + + def get_page(self, target_url: str) -> RoomPage: + """ + Retrieve a specific page of RoomInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoomInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RoomPage(self._version, response) + + async def get_page_async(self, target_url: str) -> RoomPage: + """ + Asynchronously retrieve a specific page of RoomInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoomInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RoomPage(self._version, response) + + def get(self, sid: str) -> RoomContext: + """ + Constructs a RoomContext + + :param sid: The SID of the Room resource to update. + """ + return RoomContext(self._version, sid=sid) + + def __call__(self, sid: str) -> RoomContext: + """ + Constructs a RoomContext + + :param sid: The SID of the Room resource to update. + """ + return RoomContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.RoomList>" diff --git a/twilio/rest/video/v1/room/participant/__init__.py b/twilio/rest/video/v1/room/participant/__init__.py new file mode 100644 index 0000000000..7e012e8d37 --- /dev/null +++ b/twilio/rest/video/v1/room/participant/__init__.py @@ -0,0 +1,717 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.video.v1.room.participant.anonymize import AnonymizeList +from twilio.rest.video.v1.room.participant.published_track import PublishedTrackList +from twilio.rest.video.v1.room.participant.subscribe_rules import SubscribeRulesList +from twilio.rest.video.v1.room.participant.subscribed_track import SubscribedTrackList + + +class ParticipantInstance(InstanceResource): + + class Status(object): + CONNECTED = "connected" + DISCONNECTED = "disconnected" + RECONNECTING = "reconnecting" + + """ + :ivar sid: The unique string that we created to identify the RoomParticipant resource. + :ivar room_sid: The SID of the participant's room. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the RoomParticipant resource. + :ivar status: + :ivar identity: The application-defined string that uniquely identifies the resource's User within a Room. If a client joins with an existing Identity, the existing client is disconnected. See [access tokens](https://www.twilio.com/docs/video/tutorials/user-identity-access-tokens) and [limits](https://www.twilio.com/docs/video/programmable-video-limits) for more info. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar start_time: The time of participant connected to the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :ivar end_time: The time when the participant disconnected from the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :ivar duration: The duration in seconds that the participant was `connected`. Populated only after the participant is `disconnected`. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + room_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.room_sid: Optional[str] = payload.get("room_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.status: Optional["ParticipantInstance.Status"] = payload.get("status") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.duration: Optional[int] = deserialize.integer(payload.get("duration")) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "room_sid": room_sid, + "sid": sid or self.sid, + } + self._context: Optional[ParticipantContext] = None + + @property + def _proxy(self) -> "ParticipantContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ParticipantContext for this ParticipantInstance + """ + if self._context is None: + self._context = ParticipantContext( + self._version, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ParticipantInstance": + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ParticipantInstance": + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + return await self._proxy.fetch_async() + + def update( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> "ParticipantInstance": + """ + Update the ParticipantInstance + + :param status: + + :returns: The updated ParticipantInstance + """ + return self._proxy.update( + status=status, + ) + + async def update_async( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> "ParticipantInstance": + """ + Asynchronous coroutine to update the ParticipantInstance + + :param status: + + :returns: The updated ParticipantInstance + """ + return await self._proxy.update_async( + status=status, + ) + + @property + def anonymize(self) -> AnonymizeList: + """ + Access the anonymize + """ + return self._proxy.anonymize + + @property + def published_tracks(self) -> PublishedTrackList: + """ + Access the published_tracks + """ + return self._proxy.published_tracks + + @property + def subscribe_rules(self) -> SubscribeRulesList: + """ + Access the subscribe_rules + """ + return self._proxy.subscribe_rules + + @property + def subscribed_tracks(self) -> SubscribedTrackList: + """ + Access the subscribed_tracks + """ + return self._proxy.subscribed_tracks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.ParticipantInstance {}>".format(context) + + +class ParticipantContext(InstanceContext): + + def __init__(self, version: Version, room_sid: str, sid: str): + """ + Initialize the ParticipantContext + + :param version: Version that contains the resource + :param room_sid: The SID of the room with the participant to update. + :param sid: The SID of the RoomParticipant resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "sid": sid, + } + self._uri = "/Rooms/{room_sid}/Participants/{sid}".format(**self._solution) + + self._anonymize: Optional[AnonymizeList] = None + self._published_tracks: Optional[PublishedTrackList] = None + self._subscribe_rules: Optional[SubscribeRulesList] = None + self._subscribed_tracks: Optional[SubscribedTrackList] = None + + def fetch(self) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ParticipantInstance: + """ + Asynchronous coroutine to fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + def update( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> ParticipantInstance: + """ + Update the ParticipantInstance + + :param status: + + :returns: The updated ParticipantInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, status: Union["ParticipantInstance.Status", object] = values.unset + ) -> ParticipantInstance: + """ + Asynchronous coroutine to update the ParticipantInstance + + :param status: + + :returns: The updated ParticipantInstance + """ + + data = values.of( + { + "Status": status, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + @property + def anonymize(self) -> AnonymizeList: + """ + Access the anonymize + """ + if self._anonymize is None: + self._anonymize = AnonymizeList( + self._version, + self._solution["room_sid"], + self._solution["sid"], + ) + return self._anonymize + + @property + def published_tracks(self) -> PublishedTrackList: + """ + Access the published_tracks + """ + if self._published_tracks is None: + self._published_tracks = PublishedTrackList( + self._version, + self._solution["room_sid"], + self._solution["sid"], + ) + return self._published_tracks + + @property + def subscribe_rules(self) -> SubscribeRulesList: + """ + Access the subscribe_rules + """ + if self._subscribe_rules is None: + self._subscribe_rules = SubscribeRulesList( + self._version, + self._solution["room_sid"], + self._solution["sid"], + ) + return self._subscribe_rules + + @property + def subscribed_tracks(self) -> SubscribedTrackList: + """ + Access the subscribed_tracks + """ + if self._subscribed_tracks is None: + self._subscribed_tracks = SubscribedTrackList( + self._version, + self._solution["room_sid"], + self._solution["sid"], + ) + return self._subscribed_tracks + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.ParticipantContext {}>".format(context) + + +class ParticipantPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: + """ + Build an instance of ParticipantInstance + + :param payload: Payload response from the API + """ + return ParticipantInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.ParticipantPage>" + + +class ParticipantList(ListResource): + + def __init__(self, version: Version, room_sid: str): + """ + Initialize the ParticipantList + + :param version: Version that contains the resource + :param room_sid: The SID of the room with the Participant resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + } + self._uri = "/Rooms/{room_sid}/Participants".format(**self._solution) + + def stream( + self, + status: Union["ParticipantInstance.Status", object] = values.unset, + identity: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ParticipantInstance]: + """ + Streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "ParticipantInstance.Status" status: Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. + :param str identity: Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. + :param datetime date_created_after: Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param datetime date_created_before: Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + identity=identity, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["ParticipantInstance.Status", object] = values.unset, + identity: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ParticipantInstance]: + """ + Asynchronously streams ParticipantInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "ParticipantInstance.Status" status: Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. + :param str identity: Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. + :param datetime date_created_after: Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param datetime date_created_before: Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + identity=identity, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["ParticipantInstance.Status", object] = values.unset, + identity: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "ParticipantInstance.Status" status: Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. + :param str identity: Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. + :param datetime date_created_after: Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param datetime date_created_before: Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + identity=identity, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["ParticipantInstance.Status", object] = values.unset, + identity: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ParticipantInstance]: + """ + Asynchronously lists ParticipantInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "ParticipantInstance.Status" status: Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. + :param str identity: Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. + :param datetime date_created_after: Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param datetime date_created_before: Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + identity=identity, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["ParticipantInstance.Status", object] = values.unset, + identity: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param status: Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. + :param identity: Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. + :param date_created_after: Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param date_created_before: Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "Status": status, + "Identity": identity, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + async def page_async( + self, + status: Union["ParticipantInstance.Status", object] = values.unset, + identity: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ParticipantPage: + """ + Asynchronously retrieve a single page of ParticipantInstance records from the API. + Request is executed immediately + + :param status: Read only the participants with this status. Can be: `connected` or `disconnected`. For `in-progress` Rooms the default Status is `connected`, for `completed` Rooms only `disconnected` Participants are returned. + :param identity: Read only the Participants with this [User](https://www.twilio.com/docs/chat/rest/user-resource) `identity` value. + :param date_created_after: Read only Participants that started after this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param date_created_before: Read only Participants that started before this date in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ParticipantInstance + """ + data = values.of( + { + "Status": status, + "Identity": identity, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ParticipantPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ParticipantPage: + """ + Retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ParticipantPage: + """ + Asynchronously retrieve a specific page of ParticipantInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ParticipantInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ParticipantPage(self._version, response, self._solution) + + def get(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: The SID of the RoomParticipant resource to update. + """ + return ParticipantContext( + self._version, room_sid=self._solution["room_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: The SID of the RoomParticipant resource to update. + """ + return ParticipantContext( + self._version, room_sid=self._solution["room_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.ParticipantList>" diff --git a/twilio/rest/video/v1/room/participant/anonymize.py b/twilio/rest/video/v1/room/participant/anonymize.py new file mode 100644 index 0000000000..0560d3eff4 --- /dev/null +++ b/twilio/rest/video/v1/room/participant/anonymize.py @@ -0,0 +1,245 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, Optional +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class AnonymizeInstance(InstanceResource): + + class Status(object): + CONNECTED = "connected" + DISCONNECTED = "disconnected" + + """ + :ivar sid: The unique string that we created to identify the RoomParticipant resource. + :ivar room_sid: The SID of the participant's room. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the RoomParticipant resource. + :ivar status: + :ivar identity: The SID of the participant. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar start_time: The time of participant connected to the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :ivar end_time: The time when the participant disconnected from the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. + :ivar duration: The duration in seconds that the participant was `connected`. Populated only after the participant is `disconnected`. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], room_sid: str, sid: str + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.room_sid: Optional[str] = payload.get("room_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.status: Optional["AnonymizeInstance.Status"] = payload.get("status") + self.identity: Optional[str] = payload.get("identity") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start_time") + ) + self.end_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("end_time") + ) + self.duration: Optional[int] = deserialize.integer(payload.get("duration")) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "room_sid": room_sid, + "sid": sid, + } + self._context: Optional[AnonymizeContext] = None + + @property + def _proxy(self) -> "AnonymizeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AnonymizeContext for this AnonymizeInstance + """ + if self._context is None: + self._context = AnonymizeContext( + self._version, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return self._context + + def update(self) -> "AnonymizeInstance": + """ + Update the AnonymizeInstance + + + :returns: The updated AnonymizeInstance + """ + return self._proxy.update() + + async def update_async(self) -> "AnonymizeInstance": + """ + Asynchronous coroutine to update the AnonymizeInstance + + + :returns: The updated AnonymizeInstance + """ + return await self._proxy.update_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.AnonymizeInstance {}>".format(context) + + +class AnonymizeContext(InstanceContext): + + def __init__(self, version: Version, room_sid: str, sid: str): + """ + Initialize the AnonymizeContext + + :param version: Version that contains the resource + :param room_sid: The SID of the room with the participant to update. + :param sid: The SID of the RoomParticipant resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "sid": sid, + } + self._uri = "/Rooms/{room_sid}/Participants/{sid}/Anonymize".format( + **self._solution + ) + + def update(self) -> AnonymizeInstance: + """ + Update the AnonymizeInstance + + + :returns: The updated AnonymizeInstance + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AnonymizeInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + async def update_async(self) -> AnonymizeInstance: + """ + Asynchronous coroutine to update the AnonymizeInstance + + + :returns: The updated AnonymizeInstance + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return AnonymizeInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.AnonymizeContext {}>".format(context) + + +class AnonymizeList(ListResource): + + def __init__(self, version: Version, room_sid: str, sid: str): + """ + Initialize the AnonymizeList + + :param version: Version that contains the resource + :param room_sid: The SID of the room with the participant to update. + :param sid: The SID of the RoomParticipant resource to update. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "sid": sid, + } + + def get(self) -> AnonymizeContext: + """ + Constructs a AnonymizeContext + + """ + return AnonymizeContext( + self._version, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + def __call__(self) -> AnonymizeContext: + """ + Constructs a AnonymizeContext + + """ + return AnonymizeContext( + self._version, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.AnonymizeList>" diff --git a/twilio/rest/video/v1/room/participant/published_track.py b/twilio/rest/video/v1/room/participant/published_track.py new file mode 100644 index 0000000000..a766b276ab --- /dev/null +++ b/twilio/rest/video/v1/room/participant/published_track.py @@ -0,0 +1,472 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class PublishedTrackInstance(InstanceResource): + + class Kind(object): + AUDIO = "audio" + VIDEO = "video" + DATA = "data" + + """ + :ivar sid: The unique string that we created to identify the RoomParticipantPublishedTrack resource. + :ivar participant_sid: The SID of the Participant resource with the published track. + :ivar room_sid: The SID of the Room resource where the track is published. + :ivar name: The track name. Must be no more than 128 characters, and be unique among the participant's published tracks. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar enabled: Whether the track is enabled. + :ivar kind: + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + room_sid: str, + participant_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.room_sid: Optional[str] = payload.get("room_sid") + self.name: Optional[str] = payload.get("name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.enabled: Optional[bool] = payload.get("enabled") + self.kind: Optional["PublishedTrackInstance.Kind"] = payload.get("kind") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "room_sid": room_sid, + "participant_sid": participant_sid, + "sid": sid or self.sid, + } + self._context: Optional[PublishedTrackContext] = None + + @property + def _proxy(self) -> "PublishedTrackContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PublishedTrackContext for this PublishedTrackInstance + """ + if self._context is None: + self._context = PublishedTrackContext( + self._version, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "PublishedTrackInstance": + """ + Fetch the PublishedTrackInstance + + + :returns: The fetched PublishedTrackInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PublishedTrackInstance": + """ + Asynchronous coroutine to fetch the PublishedTrackInstance + + + :returns: The fetched PublishedTrackInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.PublishedTrackInstance {}>".format(context) + + +class PublishedTrackContext(InstanceContext): + + def __init__(self, version: Version, room_sid: str, participant_sid: str, sid: str): + """ + Initialize the PublishedTrackContext + + :param version: Version that contains the resource + :param room_sid: The SID of the Room resource where the Track resource to fetch is published. + :param participant_sid: The SID of the Participant resource with the published track to fetch. + :param sid: The SID of the RoomParticipantPublishedTrack resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "participant_sid": participant_sid, + "sid": sid, + } + self._uri = "/Rooms/{room_sid}/Participants/{participant_sid}/PublishedTracks/{sid}".format( + **self._solution + ) + + def fetch(self) -> PublishedTrackInstance: + """ + Fetch the PublishedTrackInstance + + + :returns: The fetched PublishedTrackInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return PublishedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> PublishedTrackInstance: + """ + Asynchronous coroutine to fetch the PublishedTrackInstance + + + :returns: The fetched PublishedTrackInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return PublishedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.PublishedTrackContext {}>".format(context) + + +class PublishedTrackPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PublishedTrackInstance: + """ + Build an instance of PublishedTrackInstance + + :param payload: Payload response from the API + """ + return PublishedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.PublishedTrackPage>" + + +class PublishedTrackList(ListResource): + + def __init__(self, version: Version, room_sid: str, participant_sid: str): + """ + Initialize the PublishedTrackList + + :param version: Version that contains the resource + :param room_sid: The SID of the Room resource where the Track resources to read are published. + :param participant_sid: The SID of the Participant resource with the published tracks to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "participant_sid": participant_sid, + } + self._uri = ( + "/Rooms/{room_sid}/Participants/{participant_sid}/PublishedTracks".format( + **self._solution + ) + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PublishedTrackInstance]: + """ + Streams PublishedTrackInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PublishedTrackInstance]: + """ + Asynchronously streams PublishedTrackInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PublishedTrackInstance]: + """ + Lists PublishedTrackInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PublishedTrackInstance]: + """ + Asynchronously lists PublishedTrackInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PublishedTrackPage: + """ + Retrieve a single page of PublishedTrackInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PublishedTrackInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PublishedTrackPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PublishedTrackPage: + """ + Asynchronously retrieve a single page of PublishedTrackInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of PublishedTrackInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PublishedTrackPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> PublishedTrackPage: + """ + Retrieve a specific page of PublishedTrackInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PublishedTrackInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PublishedTrackPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> PublishedTrackPage: + """ + Asynchronously retrieve a specific page of PublishedTrackInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PublishedTrackInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PublishedTrackPage(self._version, response, self._solution) + + def get(self, sid: str) -> PublishedTrackContext: + """ + Constructs a PublishedTrackContext + + :param sid: The SID of the RoomParticipantPublishedTrack resource to fetch. + """ + return PublishedTrackContext( + self._version, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> PublishedTrackContext: + """ + Constructs a PublishedTrackContext + + :param sid: The SID of the RoomParticipantPublishedTrack resource to fetch. + """ + return PublishedTrackContext( + self._version, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.PublishedTrackList>" diff --git a/twilio/rest/video/v1/room/participant/subscribe_rules.py b/twilio/rest/video/v1/room/participant/subscribe_rules.py new file mode 100644 index 0000000000..992f8a374b --- /dev/null +++ b/twilio/rest/video/v1/room/participant/subscribe_rules.py @@ -0,0 +1,205 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SubscribeRulesInstance(InstanceResource): + """ + :ivar participant_sid: The SID of the Participant resource for the Subscribe Rules. + :ivar room_sid: The SID of the Room resource for the Subscribe Rules + :ivar rules: A collection of Subscribe Rules that describe how to include or exclude matching tracks. See the [Specifying Subscribe Rules](https://www.twilio.com/docs/video/api/track-subscriptions#specifying-sr) section for further information. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + room_sid: str, + participant_sid: str, + ): + super().__init__(version) + + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.room_sid: Optional[str] = payload.get("room_sid") + self.rules: Optional[List[str]] = payload.get("rules") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "room_sid": room_sid, + "participant_sid": participant_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.SubscribeRulesInstance {}>".format(context) + + +class SubscribeRulesList(ListResource): + + def __init__(self, version: Version, room_sid: str, participant_sid: str): + """ + Initialize the SubscribeRulesList + + :param version: Version that contains the resource + :param room_sid: The SID of the Room resource where the subscribe rules to update apply. + :param participant_sid: The SID of the Participant resource to update the Subscribe Rules. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "participant_sid": participant_sid, + } + self._uri = ( + "/Rooms/{room_sid}/Participants/{participant_sid}/SubscribeRules".format( + **self._solution + ) + ) + + def fetch(self) -> SubscribeRulesInstance: + """ + Asynchronously fetch the SubscribeRulesInstance + + + :returns: The fetched SubscribeRulesInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + async def fetch_async(self) -> SubscribeRulesInstance: + """ + Asynchronously fetch the SubscribeRulesInstance + + + :returns: The fetched SubscribeRulesInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + def update( + self, rules: Union[object, object] = values.unset + ) -> SubscribeRulesInstance: + """ + Update the SubscribeRulesInstance + + :param rules: A JSON-encoded array of subscribe rules. See the [Specifying Subscribe Rules](https://www.twilio.com/docs/video/api/track-subscriptions#specifying-sr) section for further information. + + :returns: The created SubscribeRulesInstance + """ + + data = values.of( + { + "Rules": serialize.object(rules), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + async def update_async( + self, rules: Union[object, object] = values.unset + ) -> SubscribeRulesInstance: + """ + Asynchronously update the SubscribeRulesInstance + + :param rules: A JSON-encoded array of subscribe rules. See the [Specifying Subscribe Rules](https://www.twilio.com/docs/video/api/track-subscriptions#specifying-sr) section for further information. + + :returns: The created SubscribeRulesInstance + """ + + data = values.of( + { + "Rules": serialize.object(rules), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SubscribeRulesInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.SubscribeRulesList>" diff --git a/twilio/rest/video/v1/room/participant/subscribed_track.py b/twilio/rest/video/v1/room/participant/subscribed_track.py new file mode 100644 index 0000000000..8baea148dc --- /dev/null +++ b/twilio/rest/video/v1/room/participant/subscribed_track.py @@ -0,0 +1,474 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SubscribedTrackInstance(InstanceResource): + + class Kind(object): + AUDIO = "audio" + VIDEO = "video" + DATA = "data" + + """ + :ivar sid: The unique string that we created to identify the RoomParticipantSubscribedTrack resource. + :ivar participant_sid: The SID of the participant that subscribes to the track. + :ivar publisher_sid: The SID of the participant that publishes the track. + :ivar room_sid: The SID of the room where the track is published. + :ivar name: The track name. Must have no more than 128 characters and be unique among the participant's published tracks. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar enabled: Whether the track is enabled. + :ivar kind: + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + room_sid: str, + participant_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.participant_sid: Optional[str] = payload.get("participant_sid") + self.publisher_sid: Optional[str] = payload.get("publisher_sid") + self.room_sid: Optional[str] = payload.get("room_sid") + self.name: Optional[str] = payload.get("name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.enabled: Optional[bool] = payload.get("enabled") + self.kind: Optional["SubscribedTrackInstance.Kind"] = payload.get("kind") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "room_sid": room_sid, + "participant_sid": participant_sid, + "sid": sid or self.sid, + } + self._context: Optional[SubscribedTrackContext] = None + + @property + def _proxy(self) -> "SubscribedTrackContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SubscribedTrackContext for this SubscribedTrackInstance + """ + if self._context is None: + self._context = SubscribedTrackContext( + self._version, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "SubscribedTrackInstance": + """ + Fetch the SubscribedTrackInstance + + + :returns: The fetched SubscribedTrackInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SubscribedTrackInstance": + """ + Asynchronous coroutine to fetch the SubscribedTrackInstance + + + :returns: The fetched SubscribedTrackInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.SubscribedTrackInstance {}>".format(context) + + +class SubscribedTrackContext(InstanceContext): + + def __init__(self, version: Version, room_sid: str, participant_sid: str, sid: str): + """ + Initialize the SubscribedTrackContext + + :param version: Version that contains the resource + :param room_sid: The SID of the Room where the Track resource to fetch is subscribed. + :param participant_sid: The SID of the participant that subscribes to the Track resource to fetch. + :param sid: The SID of the RoomParticipantSubscribedTrack resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "participant_sid": participant_sid, + "sid": sid, + } + self._uri = "/Rooms/{room_sid}/Participants/{participant_sid}/SubscribedTracks/{sid}".format( + **self._solution + ) + + def fetch(self) -> SubscribedTrackInstance: + """ + Fetch the SubscribedTrackInstance + + + :returns: The fetched SubscribedTrackInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SubscribedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SubscribedTrackInstance: + """ + Asynchronous coroutine to fetch the SubscribedTrackInstance + + + :returns: The fetched SubscribedTrackInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SubscribedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.SubscribedTrackContext {}>".format(context) + + +class SubscribedTrackPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SubscribedTrackInstance: + """ + Build an instance of SubscribedTrackInstance + + :param payload: Payload response from the API + """ + return SubscribedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.SubscribedTrackPage>" + + +class SubscribedTrackList(ListResource): + + def __init__(self, version: Version, room_sid: str, participant_sid: str): + """ + Initialize the SubscribedTrackList + + :param version: Version that contains the resource + :param room_sid: The SID of the Room resource with the Track resources to read. + :param participant_sid: The SID of the participant that subscribes to the Track resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "participant_sid": participant_sid, + } + self._uri = ( + "/Rooms/{room_sid}/Participants/{participant_sid}/SubscribedTracks".format( + **self._solution + ) + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SubscribedTrackInstance]: + """ + Streams SubscribedTrackInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SubscribedTrackInstance]: + """ + Asynchronously streams SubscribedTrackInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SubscribedTrackInstance]: + """ + Lists SubscribedTrackInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SubscribedTrackInstance]: + """ + Asynchronously lists SubscribedTrackInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SubscribedTrackPage: + """ + Retrieve a single page of SubscribedTrackInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SubscribedTrackInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SubscribedTrackPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SubscribedTrackPage: + """ + Asynchronously retrieve a single page of SubscribedTrackInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SubscribedTrackInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SubscribedTrackPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> SubscribedTrackPage: + """ + Retrieve a specific page of SubscribedTrackInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SubscribedTrackInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SubscribedTrackPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> SubscribedTrackPage: + """ + Asynchronously retrieve a specific page of SubscribedTrackInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SubscribedTrackInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SubscribedTrackPage(self._version, response, self._solution) + + def get(self, sid: str) -> SubscribedTrackContext: + """ + Constructs a SubscribedTrackContext + + :param sid: The SID of the RoomParticipantSubscribedTrack resource to fetch. + """ + return SubscribedTrackContext( + self._version, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> SubscribedTrackContext: + """ + Constructs a SubscribedTrackContext + + :param sid: The SID of the RoomParticipantSubscribedTrack resource to fetch. + """ + return SubscribedTrackContext( + self._version, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.SubscribedTrackList>" diff --git a/twilio/rest/video/v1/room/recording_rules.py b/twilio/rest/video/v1/room/recording_rules.py new file mode 100644 index 0000000000..d79d465c28 --- /dev/null +++ b/twilio/rest/video/v1/room/recording_rules.py @@ -0,0 +1,178 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union +from twilio.base import deserialize, serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class RecordingRulesInstance(InstanceResource): + """ + :ivar room_sid: The SID of the Room resource for the Recording Rules + :ivar rules: A collection of Recording Rules that describe how to include or exclude matching tracks for recording + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], room_sid: str): + super().__init__(version) + + self.room_sid: Optional[str] = payload.get("room_sid") + self.rules: Optional[List[str]] = payload.get("rules") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "room_sid": room_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.RecordingRulesInstance {}>".format(context) + + +class RecordingRulesList(ListResource): + + def __init__(self, version: Version, room_sid: str): + """ + Initialize the RecordingRulesList + + :param version: Version that contains the resource + :param room_sid: The SID of the Room resource where the recording rules to update apply. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + } + self._uri = "/Rooms/{room_sid}/RecordingRules".format(**self._solution) + + def fetch(self) -> RecordingRulesInstance: + """ + Asynchronously fetch the RecordingRulesInstance + + + :returns: The fetched RecordingRulesInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + async def fetch_async(self) -> RecordingRulesInstance: + """ + Asynchronously fetch the RecordingRulesInstance + + + :returns: The fetched RecordingRulesInstance + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + def update( + self, rules: Union[object, object] = values.unset + ) -> RecordingRulesInstance: + """ + Update the RecordingRulesInstance + + :param rules: A JSON-encoded array of recording rules. + + :returns: The created RecordingRulesInstance + """ + + data = values.of( + { + "Rules": serialize.object(rules), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + async def update_async( + self, rules: Union[object, object] = values.unset + ) -> RecordingRulesInstance: + """ + Asynchronously update the RecordingRulesInstance + + :param rules: A JSON-encoded array of recording rules. + + :returns: The created RecordingRulesInstance + """ + + data = values.of( + { + "Rules": serialize.object(rules), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RecordingRulesInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.RecordingRulesList>" diff --git a/twilio/rest/video/v1/room/room_recording.py b/twilio/rest/video/v1/room/room_recording.py new file mode 100644 index 0000000000..21d433ce38 --- /dev/null +++ b/twilio/rest/video/v1/room/room_recording.py @@ -0,0 +1,602 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Video + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RoomRecordingInstance(InstanceResource): + + class Codec(object): + VP8 = "VP8" + H264 = "H264" + OPUS = "OPUS" + PCMU = "PCMU" + + class Format(object): + MKA = "mka" + MKV = "mkv" + + class Status(object): + PROCESSING = "processing" + COMPLETED = "completed" + DELETED = "deleted" + FAILED = "failed" + + class Type(object): + AUDIO = "audio" + VIDEO = "video" + DATA = "data" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the RoomRecording resource. + :ivar status: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar sid: The unique string that we created to identify the RoomRecording resource. + :ivar source_sid: The SID of the recording source. For a Room Recording, this value is a `track_sid`. + :ivar size: The size of the recorded track in bytes. + :ivar url: The absolute URL of the resource. + :ivar type: + :ivar duration: The duration of the recording rounded to the nearest second. Sub-second duration tracks have a `duration` of 1 second + :ivar container_format: + :ivar codec: + :ivar grouping_sids: A list of SIDs related to the Recording. Includes the `room_sid` and `participant_sid`. + :ivar track_name: The name that was given to the source track of the recording. If no name is given, the `source_sid` is used. + :ivar offset: The time in milliseconds elapsed between an arbitrary point in time, common to all group rooms, and the moment when the source room of this track started. This information provides a synchronization mechanism for recordings belonging to the same room. + :ivar media_external_location: The URL of the media file associated with the recording when stored externally. See [External S3 Recordings](/docs/video/api/external-s3-recordings) for more details. + :ivar room_sid: The SID of the Room resource the recording is associated with. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + room_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.status: Optional["RoomRecordingInstance.Status"] = payload.get("status") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.sid: Optional[str] = payload.get("sid") + self.source_sid: Optional[str] = payload.get("source_sid") + self.size: Optional[int] = payload.get("size") + self.url: Optional[str] = payload.get("url") + self.type: Optional["RoomRecordingInstance.Type"] = payload.get("type") + self.duration: Optional[int] = deserialize.integer(payload.get("duration")) + self.container_format: Optional["RoomRecordingInstance.Format"] = payload.get( + "container_format" + ) + self.codec: Optional["RoomRecordingInstance.Codec"] = payload.get("codec") + self.grouping_sids: Optional[Dict[str, object]] = payload.get("grouping_sids") + self.track_name: Optional[str] = payload.get("track_name") + self.offset: Optional[int] = payload.get("offset") + self.media_external_location: Optional[str] = payload.get( + "media_external_location" + ) + self.room_sid: Optional[str] = payload.get("room_sid") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "room_sid": room_sid, + "sid": sid or self.sid, + } + self._context: Optional[RoomRecordingContext] = None + + @property + def _proxy(self) -> "RoomRecordingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoomRecordingContext for this RoomRecordingInstance + """ + if self._context is None: + self._context = RoomRecordingContext( + self._version, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RoomRecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoomRecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RoomRecordingInstance": + """ + Fetch the RoomRecordingInstance + + + :returns: The fetched RoomRecordingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RoomRecordingInstance": + """ + Asynchronous coroutine to fetch the RoomRecordingInstance + + + :returns: The fetched RoomRecordingInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.RoomRecordingInstance {}>".format(context) + + +class RoomRecordingContext(InstanceContext): + + def __init__(self, version: Version, room_sid: str, sid: str): + """ + Initialize the RoomRecordingContext + + :param version: Version that contains the resource + :param room_sid: The SID of the Room resource with the recording to fetch. + :param sid: The SID of the RoomRecording resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + "sid": sid, + } + self._uri = "/Rooms/{room_sid}/Recordings/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RoomRecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoomRecordingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RoomRecordingInstance: + """ + Fetch the RoomRecordingInstance + + + :returns: The fetched RoomRecordingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RoomRecordingInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RoomRecordingInstance: + """ + Asynchronous coroutine to fetch the RoomRecordingInstance + + + :returns: The fetched RoomRecordingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RoomRecordingInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Video.V1.RoomRecordingContext {}>".format(context) + + +class RoomRecordingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoomRecordingInstance: + """ + Build an instance of RoomRecordingInstance + + :param payload: Payload response from the API + """ + return RoomRecordingInstance( + self._version, payload, room_sid=self._solution["room_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.RoomRecordingPage>" + + +class RoomRecordingList(ListResource): + + def __init__(self, version: Version, room_sid: str): + """ + Initialize the RoomRecordingList + + :param version: Version that contains the resource + :param room_sid: The SID of the room with the RoomRecording resources to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "room_sid": room_sid, + } + self._uri = "/Rooms/{room_sid}/Recordings".format(**self._solution) + + def stream( + self, + status: Union["RoomRecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RoomRecordingInstance]: + """ + Streams RoomRecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "RoomRecordingInstance.Status" status: Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + source_sid=source_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["RoomRecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RoomRecordingInstance]: + """ + Asynchronously streams RoomRecordingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "RoomRecordingInstance.Status" status: Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + source_sid=source_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["RoomRecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoomRecordingInstance]: + """ + Lists RoomRecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RoomRecordingInstance.Status" status: Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + source_sid=source_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["RoomRecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RoomRecordingInstance]: + """ + Asynchronously lists RoomRecordingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "RoomRecordingInstance.Status" status: Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. + :param str source_sid: Read only the recordings that have this `source_sid`. + :param datetime date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param datetime date_created_before: Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + source_sid=source_sid, + date_created_after=date_created_after, + date_created_before=date_created_before, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["RoomRecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RoomRecordingPage: + """ + Retrieve a single page of RoomRecordingInstance records from the API. + Request is executed immediately + + :param status: Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. + :param source_sid: Read only the recordings that have this `source_sid`. + :param date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param date_created_before: Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoomRecordingInstance + """ + data = values.of( + { + "Status": status, + "SourceSid": source_sid, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RoomRecordingPage(self._version, response, self._solution) + + async def page_async( + self, + status: Union["RoomRecordingInstance.Status", object] = values.unset, + source_sid: Union[str, object] = values.unset, + date_created_after: Union[datetime, object] = values.unset, + date_created_before: Union[datetime, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RoomRecordingPage: + """ + Asynchronously retrieve a single page of RoomRecordingInstance records from the API. + Request is executed immediately + + :param status: Read only the recordings with this status. Can be: `processing`, `completed`, or `deleted`. + :param source_sid: Read only the recordings that have this `source_sid`. + :param date_created_after: Read only recordings that started on or after this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param date_created_before: Read only Recordings that started before this [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) datetime with time zone. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RoomRecordingInstance + """ + data = values.of( + { + "Status": status, + "SourceSid": source_sid, + "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), + "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RoomRecordingPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> RoomRecordingPage: + """ + Retrieve a specific page of RoomRecordingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoomRecordingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RoomRecordingPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> RoomRecordingPage: + """ + Asynchronously retrieve a specific page of RoomRecordingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoomRecordingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RoomRecordingPage(self._version, response, self._solution) + + def get(self, sid: str) -> RoomRecordingContext: + """ + Constructs a RoomRecordingContext + + :param sid: The SID of the RoomRecording resource to fetch. + """ + return RoomRecordingContext( + self._version, room_sid=self._solution["room_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RoomRecordingContext: + """ + Constructs a RoomRecordingContext + + :param sid: The SID of the RoomRecording resource to fetch. + """ + return RoomRecordingContext( + self._version, room_sid=self._solution["room_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Video.V1.RoomRecordingList>" diff --git a/twilio/rest/voice/VoiceBase.py b/twilio/rest/voice/VoiceBase.py new file mode 100644 index 0000000000..4394ab1a2d --- /dev/null +++ b/twilio/rest/voice/VoiceBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.voice.v1 import V1 + + +class VoiceBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Voice Domain + + :returns: Domain for Voice + """ + super().__init__(twilio, "https://voice.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Voice + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Voice>" diff --git a/twilio/rest/voice/__init__.py b/twilio/rest/voice/__init__.py new file mode 100644 index 0000000000..019a3a2058 --- /dev/null +++ b/twilio/rest/voice/__init__.py @@ -0,0 +1,65 @@ +from warnings import warn + +from twilio.rest.voice.VoiceBase import VoiceBase +from twilio.rest.voice.v1.archived_call import ArchivedCallList +from twilio.rest.voice.v1.byoc_trunk import ByocTrunkList +from twilio.rest.voice.v1.connection_policy import ConnectionPolicyList +from twilio.rest.voice.v1.dialing_permissions import DialingPermissionsList +from twilio.rest.voice.v1.ip_record import IpRecordList +from twilio.rest.voice.v1.source_ip_mapping import SourceIpMappingList + + +class Voice(VoiceBase): + @property + def archived_calls(self) -> ArchivedCallList: + warn( + "archived_calls is deprecated. Use v1.archived_calls instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.archived_calls + + @property + def byoc_trunks(self) -> ByocTrunkList: + warn( + "byoc_trunks is deprecated. Use v1.byoc_trunks instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.byoc_trunks + + @property + def connection_policies(self) -> ConnectionPolicyList: + warn( + "connection_policies is deprecated. Use v1.connection_policies instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.connection_policies + + @property + def dialing_permissions(self) -> DialingPermissionsList: + warn( + "dialing_permissions is deprecated. Use v1.dialing_permissions instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.dialing_permissions + + @property + def ip_records(self) -> IpRecordList: + warn( + "ip_records is deprecated. Use v1.ip_records instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.ip_records + + @property + def source_ip_mappings(self) -> SourceIpMappingList: + warn( + "source_ip_mappings is deprecated. Use v1.source_ip_mappings instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.source_ip_mappings diff --git a/twilio/rest/voice/v1/__init__.py b/twilio/rest/voice/v1/__init__.py new file mode 100644 index 0000000000..75c0c7fc74 --- /dev/null +++ b/twilio/rest/voice/v1/__init__.py @@ -0,0 +1,83 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.voice.v1.archived_call import ArchivedCallList +from twilio.rest.voice.v1.byoc_trunk import ByocTrunkList +from twilio.rest.voice.v1.connection_policy import ConnectionPolicyList +from twilio.rest.voice.v1.dialing_permissions import DialingPermissionsList +from twilio.rest.voice.v1.ip_record import IpRecordList +from twilio.rest.voice.v1.source_ip_mapping import SourceIpMappingList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Voice + + :param domain: The Twilio.voice domain + """ + super().__init__(domain, "v1") + self._archived_calls: Optional[ArchivedCallList] = None + self._byoc_trunks: Optional[ByocTrunkList] = None + self._connection_policies: Optional[ConnectionPolicyList] = None + self._dialing_permissions: Optional[DialingPermissionsList] = None + self._ip_records: Optional[IpRecordList] = None + self._source_ip_mappings: Optional[SourceIpMappingList] = None + + @property + def archived_calls(self) -> ArchivedCallList: + if self._archived_calls is None: + self._archived_calls = ArchivedCallList(self) + return self._archived_calls + + @property + def byoc_trunks(self) -> ByocTrunkList: + if self._byoc_trunks is None: + self._byoc_trunks = ByocTrunkList(self) + return self._byoc_trunks + + @property + def connection_policies(self) -> ConnectionPolicyList: + if self._connection_policies is None: + self._connection_policies = ConnectionPolicyList(self) + return self._connection_policies + + @property + def dialing_permissions(self) -> DialingPermissionsList: + if self._dialing_permissions is None: + self._dialing_permissions = DialingPermissionsList(self) + return self._dialing_permissions + + @property + def ip_records(self) -> IpRecordList: + if self._ip_records is None: + self._ip_records = IpRecordList(self) + return self._ip_records + + @property + def source_ip_mappings(self) -> SourceIpMappingList: + if self._source_ip_mappings is None: + self._source_ip_mappings = SourceIpMappingList(self) + return self._source_ip_mappings + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V1>" diff --git a/twilio/rest/voice/v1/archived_call.py b/twilio/rest/voice/v1/archived_call.py new file mode 100644 index 0000000000..939f1a03e2 --- /dev/null +++ b/twilio/rest/voice/v1/archived_call.py @@ -0,0 +1,113 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import date +from twilio.base import values +from twilio.base.instance_context import InstanceContext + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ArchivedCallContext(InstanceContext): + + def __init__(self, version: Version, date: date, sid: str): + """ + Initialize the ArchivedCallContext + + :param version: Version that contains the resource + :param date: The date of the Call in UTC. + :param sid: The Twilio-provided Call SID that uniquely identifies the Call resource to delete + """ + super().__init__(version) + + # Path Solution + self._solution = { + "date": date, + "sid": sid, + } + self._uri = "/Archives/{date}/Calls/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the ArchivedCallInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ArchivedCallInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V1.ArchivedCallContext {}>".format(context) + + +class ArchivedCallList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ArchivedCallList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, date: date, sid: str) -> ArchivedCallContext: + """ + Constructs a ArchivedCallContext + + :param date: The date of the Call in UTC. + :param sid: The Twilio-provided Call SID that uniquely identifies the Call resource to delete + """ + return ArchivedCallContext(self._version, date=date, sid=sid) + + def __call__(self, date: date, sid: str) -> ArchivedCallContext: + """ + Constructs a ArchivedCallContext + + :param date: The date of the Call in UTC. + :param sid: The Twilio-provided Call SID that uniquely identifies the Call resource to delete + """ + return ArchivedCallContext(self._version, date=date, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V1.ArchivedCallList>" diff --git a/twilio/rest/voice/v1/byoc_trunk.py b/twilio/rest/voice/v1/byoc_trunk.py new file mode 100644 index 0000000000..304bdd78a5 --- /dev/null +++ b/twilio/rest/voice/v1/byoc_trunk.py @@ -0,0 +1,787 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ByocTrunkInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the BYOC Trunk resource. + :ivar sid: The unique string that that we created to identify the BYOC Trunk resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar voice_url: The URL we call using the `voice_method` when the BYOC Trunk receives a call. + :ivar voice_method: The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. + :ivar voice_fallback_url: The URL that we call when an error occurs while retrieving or executing the TwiML requested from `voice_url`. + :ivar voice_fallback_method: The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :ivar status_callback_url: The URL that we call to pass status parameters (such as call ended) to your application. + :ivar status_callback_method: The HTTP method we use to call `status_callback_url`. Either `GET` or `POST`. + :ivar cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :ivar connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :ivar from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \"call back\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \"sip.twilio.com\". + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.voice_url: Optional[str] = payload.get("voice_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.status_callback_url: Optional[str] = payload.get("status_callback_url") + self.status_callback_method: Optional[str] = payload.get( + "status_callback_method" + ) + self.cnam_lookup_enabled: Optional[bool] = payload.get("cnam_lookup_enabled") + self.connection_policy_sid: Optional[str] = payload.get("connection_policy_sid") + self.from_domain_sid: Optional[str] = payload.get("from_domain_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ByocTrunkContext] = None + + @property + def _proxy(self) -> "ByocTrunkContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ByocTrunkContext for this ByocTrunkInstance + """ + if self._context is None: + self._context = ByocTrunkContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ByocTrunkInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ByocTrunkInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ByocTrunkInstance": + """ + Fetch the ByocTrunkInstance + + + :returns: The fetched ByocTrunkInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ByocTrunkInstance": + """ + Asynchronous coroutine to fetch the ByocTrunkInstance + + + :returns: The fetched ByocTrunkInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> "ByocTrunkInstance": + """ + Update the ByocTrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: The updated ByocTrunkInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> "ByocTrunkInstance": + """ + Asynchronous coroutine to update the ByocTrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: The updated ByocTrunkInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + voice_url=voice_url, + voice_method=voice_method, + voice_fallback_url=voice_fallback_url, + voice_fallback_method=voice_fallback_method, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + cnam_lookup_enabled=cnam_lookup_enabled, + connection_policy_sid=connection_policy_sid, + from_domain_sid=from_domain_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V1.ByocTrunkInstance {}>".format(context) + + +class ByocTrunkContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ByocTrunkContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the BYOC Trunk resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/ByocTrunks/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the ByocTrunkInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ByocTrunkInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ByocTrunkInstance: + """ + Fetch the ByocTrunkInstance + + + :returns: The fetched ByocTrunkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ByocTrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ByocTrunkInstance: + """ + Asynchronous coroutine to fetch the ByocTrunkInstance + + + :returns: The fetched ByocTrunkInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ByocTrunkInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ByocTrunkInstance: + """ + Update the ByocTrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: The updated ByocTrunkInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "ConnectionPolicySid": connection_policy_sid, + "FromDomainSid": from_domain_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ByocTrunkInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ByocTrunkInstance: + """ + Asynchronous coroutine to update the ByocTrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url` + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML requested by `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: The updated ByocTrunkInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "ConnectionPolicySid": connection_policy_sid, + "FromDomainSid": from_domain_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ByocTrunkInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V1.ByocTrunkContext {}>".format(context) + + +class ByocTrunkPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ByocTrunkInstance: + """ + Build an instance of ByocTrunkInstance + + :param payload: Payload response from the API + """ + return ByocTrunkInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V1.ByocTrunkPage>" + + +class ByocTrunkList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ByocTrunkList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ByocTrunks" + + def create( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ByocTrunkInstance: + """ + Create the ByocTrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: The created ByocTrunkInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "ConnectionPolicySid": connection_policy_sid, + "FromDomainSid": from_domain_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ByocTrunkInstance(self._version, payload) + + async def create_async( + self, + friendly_name: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + status_callback_url: Union[str, object] = values.unset, + status_callback_method: Union[str, object] = values.unset, + cnam_lookup_enabled: Union[bool, object] = values.unset, + connection_policy_sid: Union[str, object] = values.unset, + from_domain_sid: Union[str, object] = values.unset, + ) -> ByocTrunkInstance: + """ + Asynchronously create the ByocTrunkInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param voice_url: The URL we should call when the BYOC Trunk receives a call. + :param voice_method: The HTTP method we should use to call `voice_url`. Can be: `GET` or `POST`. + :param voice_fallback_url: The URL that we should call when an error occurs while retrieving or executing the TwiML from `voice_url`. + :param voice_fallback_method: The HTTP method we should use to call `voice_fallback_url`. Can be: `GET` or `POST`. + :param status_callback_url: The URL that we should call to pass status parameters (such as call ended) to your application. + :param status_callback_method: The HTTP method we should use to call `status_callback_url`. Can be: `GET` or `POST`. + :param cnam_lookup_enabled: Whether Caller ID Name (CNAM) lookup is enabled for the trunk. If enabled, all inbound calls to the BYOC Trunk from the United States and Canada automatically perform a CNAM Lookup and display Caller ID data on your phone. See [CNAM Lookups](https://www.twilio.com/docs/sip-trunking#CNAM) for more information. + :param connection_policy_sid: The SID of the Connection Policy that Twilio will use when routing traffic to your communications infrastructure. + :param from_domain_sid: The SID of the SIP Domain that should be used in the `From` header of originating calls sent to your SIP infrastructure. If your SIP infrastructure allows users to \\\"call back\\\" an incoming call, configure this with a [SIP Domain](https://www.twilio.com/docs/voice/api/sending-sip) to ensure proper routing. If not configured, the from domain will default to \\\"sip.twilio.com\\\". + + :returns: The created ByocTrunkInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "ConnectionPolicySid": connection_policy_sid, + "FromDomainSid": from_domain_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ByocTrunkInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ByocTrunkInstance]: + """ + Streams ByocTrunkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ByocTrunkInstance]: + """ + Asynchronously streams ByocTrunkInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ByocTrunkInstance]: + """ + Lists ByocTrunkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ByocTrunkInstance]: + """ + Asynchronously lists ByocTrunkInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ByocTrunkPage: + """ + Retrieve a single page of ByocTrunkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ByocTrunkInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ByocTrunkPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ByocTrunkPage: + """ + Asynchronously retrieve a single page of ByocTrunkInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ByocTrunkInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ByocTrunkPage(self._version, response) + + def get_page(self, target_url: str) -> ByocTrunkPage: + """ + Retrieve a specific page of ByocTrunkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ByocTrunkInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ByocTrunkPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ByocTrunkPage: + """ + Asynchronously retrieve a specific page of ByocTrunkInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ByocTrunkInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ByocTrunkPage(self._version, response) + + def get(self, sid: str) -> ByocTrunkContext: + """ + Constructs a ByocTrunkContext + + :param sid: The Twilio-provided string that uniquely identifies the BYOC Trunk resource to update. + """ + return ByocTrunkContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ByocTrunkContext: + """ + Constructs a ByocTrunkContext + + :param sid: The Twilio-provided string that uniquely identifies the BYOC Trunk resource to update. + """ + return ByocTrunkContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V1.ByocTrunkList>" diff --git a/twilio/rest/voice/v1/connection_policy/__init__.py b/twilio/rest/voice/v1/connection_policy/__init__.py new file mode 100644 index 0000000000..e2a56929c7 --- /dev/null +++ b/twilio/rest/voice/v1/connection_policy/__init__.py @@ -0,0 +1,629 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.voice.v1.connection_policy.connection_policy_target import ( + ConnectionPolicyTargetList, +) + + +class ConnectionPolicyInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Connection Policy resource. + :ivar sid: The unique string that we created to identify the Connection Policy resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related resources. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[ConnectionPolicyContext] = None + + @property + def _proxy(self) -> "ConnectionPolicyContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConnectionPolicyContext for this ConnectionPolicyInstance + """ + if self._context is None: + self._context = ConnectionPolicyContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ConnectionPolicyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConnectionPolicyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ConnectionPolicyInstance": + """ + Fetch the ConnectionPolicyInstance + + + :returns: The fetched ConnectionPolicyInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConnectionPolicyInstance": + """ + Asynchronous coroutine to fetch the ConnectionPolicyInstance + + + :returns: The fetched ConnectionPolicyInstance + """ + return await self._proxy.fetch_async() + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "ConnectionPolicyInstance": + """ + Update the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated ConnectionPolicyInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "ConnectionPolicyInstance": + """ + Asynchronous coroutine to update the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated ConnectionPolicyInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + @property + def targets(self) -> ConnectionPolicyTargetList: + """ + Access the targets + """ + return self._proxy.targets + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V1.ConnectionPolicyInstance {}>".format(context) + + +class ConnectionPolicyContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ConnectionPolicyContext + + :param version: Version that contains the resource + :param sid: The unique string that we created to identify the Connection Policy resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/ConnectionPolicies/{sid}".format(**self._solution) + + self._targets: Optional[ConnectionPolicyTargetList] = None + + def delete(self) -> bool: + """ + Deletes the ConnectionPolicyInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConnectionPolicyInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConnectionPolicyInstance: + """ + Fetch the ConnectionPolicyInstance + + + :returns: The fetched ConnectionPolicyInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ConnectionPolicyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ConnectionPolicyInstance: + """ + Asynchronous coroutine to fetch the ConnectionPolicyInstance + + + :returns: The fetched ConnectionPolicyInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ConnectionPolicyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> ConnectionPolicyInstance: + """ + Update the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated ConnectionPolicyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConnectionPolicyInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ConnectionPolicyInstance: + """ + Asynchronous coroutine to update the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated ConnectionPolicyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConnectionPolicyInstance( + self._version, payload, sid=self._solution["sid"] + ) + + @property + def targets(self) -> ConnectionPolicyTargetList: + """ + Access the targets + """ + if self._targets is None: + self._targets = ConnectionPolicyTargetList( + self._version, + self._solution["sid"], + ) + return self._targets + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V1.ConnectionPolicyContext {}>".format(context) + + +class ConnectionPolicyPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConnectionPolicyInstance: + """ + Build an instance of ConnectionPolicyInstance + + :param payload: Payload response from the API + """ + return ConnectionPolicyInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V1.ConnectionPolicyPage>" + + +class ConnectionPolicyList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ConnectionPolicyList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ConnectionPolicies" + + def create( + self, friendly_name: Union[str, object] = values.unset + ) -> ConnectionPolicyInstance: + """ + Create the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The created ConnectionPolicyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConnectionPolicyInstance(self._version, payload) + + async def create_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ConnectionPolicyInstance: + """ + Asynchronously create the ConnectionPolicyInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The created ConnectionPolicyInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConnectionPolicyInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConnectionPolicyInstance]: + """ + Streams ConnectionPolicyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConnectionPolicyInstance]: + """ + Asynchronously streams ConnectionPolicyInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConnectionPolicyInstance]: + """ + Lists ConnectionPolicyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConnectionPolicyInstance]: + """ + Asynchronously lists ConnectionPolicyInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConnectionPolicyPage: + """ + Retrieve a single page of ConnectionPolicyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConnectionPolicyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConnectionPolicyPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConnectionPolicyPage: + """ + Asynchronously retrieve a single page of ConnectionPolicyInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConnectionPolicyInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConnectionPolicyPage(self._version, response) + + def get_page(self, target_url: str) -> ConnectionPolicyPage: + """ + Retrieve a specific page of ConnectionPolicyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConnectionPolicyInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConnectionPolicyPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ConnectionPolicyPage: + """ + Asynchronously retrieve a specific page of ConnectionPolicyInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConnectionPolicyInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConnectionPolicyPage(self._version, response) + + def get(self, sid: str) -> ConnectionPolicyContext: + """ + Constructs a ConnectionPolicyContext + + :param sid: The unique string that we created to identify the Connection Policy resource to update. + """ + return ConnectionPolicyContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ConnectionPolicyContext: + """ + Constructs a ConnectionPolicyContext + + :param sid: The unique string that we created to identify the Connection Policy resource to update. + """ + return ConnectionPolicyContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V1.ConnectionPolicyList>" diff --git a/twilio/rest/voice/v1/connection_policy/connection_policy_target.py b/twilio/rest/voice/v1/connection_policy/connection_policy_target.py new file mode 100644 index 0000000000..03f4fd607d --- /dev/null +++ b/twilio/rest/voice/v1/connection_policy/connection_policy_target.py @@ -0,0 +1,736 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ConnectionPolicyTargetInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Target resource. + :ivar connection_policy_sid: The SID of the Connection Policy that owns the Target. + :ivar sid: The unique string that we created to identify the Target resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :ivar priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important target. + :ivar weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. Targets with higher values receive more load than those with lower ones with the same priority. + :ivar enabled: Whether the target is enabled. The default is `true`. + :ivar date_created: The date and time in GMT when the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + connection_policy_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.connection_policy_sid: Optional[str] = payload.get("connection_policy_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.target: Optional[str] = payload.get("target") + self.priority: Optional[int] = deserialize.integer(payload.get("priority")) + self.weight: Optional[int] = deserialize.integer(payload.get("weight")) + self.enabled: Optional[bool] = payload.get("enabled") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "connection_policy_sid": connection_policy_sid, + "sid": sid or self.sid, + } + self._context: Optional[ConnectionPolicyTargetContext] = None + + @property + def _proxy(self) -> "ConnectionPolicyTargetContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConnectionPolicyTargetContext for this ConnectionPolicyTargetInstance + """ + if self._context is None: + self._context = ConnectionPolicyTargetContext( + self._version, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ConnectionPolicyTargetInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConnectionPolicyTargetInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "ConnectionPolicyTargetInstance": + """ + Fetch the ConnectionPolicyTargetInstance + + + :returns: The fetched ConnectionPolicyTargetInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ConnectionPolicyTargetInstance": + """ + Asynchronous coroutine to fetch the ConnectionPolicyTargetInstance + + + :returns: The fetched ConnectionPolicyTargetInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + friendly_name: Union[str, object] = values.unset, + target: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> "ConnectionPolicyTargetInstance": + """ + Update the ConnectionPolicyTargetInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. + + :returns: The updated ConnectionPolicyTargetInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=enabled, + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + target: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> "ConnectionPolicyTargetInstance": + """ + Asynchronous coroutine to update the ConnectionPolicyTargetInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. + + :returns: The updated ConnectionPolicyTargetInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + target=target, + priority=priority, + weight=weight, + enabled=enabled, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V1.ConnectionPolicyTargetInstance {}>".format(context) + + +class ConnectionPolicyTargetContext(InstanceContext): + + def __init__(self, version: Version, connection_policy_sid: str, sid: str): + """ + Initialize the ConnectionPolicyTargetContext + + :param version: Version that contains the resource + :param connection_policy_sid: The SID of the Connection Policy that owns the Target. + :param sid: The unique string that we created to identify the Target resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "connection_policy_sid": connection_policy_sid, + "sid": sid, + } + self._uri = "/ConnectionPolicies/{connection_policy_sid}/Targets/{sid}".format( + **self._solution + ) + + def delete(self) -> bool: + """ + Deletes the ConnectionPolicyTargetInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ConnectionPolicyTargetInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> ConnectionPolicyTargetInstance: + """ + Fetch the ConnectionPolicyTargetInstance + + + :returns: The fetched ConnectionPolicyTargetInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> ConnectionPolicyTargetInstance: + """ + Asynchronous coroutine to fetch the ConnectionPolicyTargetInstance + + + :returns: The fetched ConnectionPolicyTargetInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + + def update( + self, + friendly_name: Union[str, object] = values.unset, + target: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ConnectionPolicyTargetInstance: + """ + Update the ConnectionPolicyTargetInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. + + :returns: The updated ConnectionPolicyTargetInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Target": target, + "Priority": priority, + "Weight": weight, + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + + async def update_async( + self, + friendly_name: Union[str, object] = values.unset, + target: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ConnectionPolicyTargetInstance: + """ + Asynchronous coroutine to update the ConnectionPolicyTargetInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. + + :returns: The updated ConnectionPolicyTargetInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Target": target, + "Priority": priority, + "Weight": weight, + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V1.ConnectionPolicyTargetContext {}>".format(context) + + +class ConnectionPolicyTargetPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConnectionPolicyTargetInstance: + """ + Build an instance of ConnectionPolicyTargetInstance + + :param payload: Payload response from the API + """ + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V1.ConnectionPolicyTargetPage>" + + +class ConnectionPolicyTargetList(ListResource): + + def __init__(self, version: Version, connection_policy_sid: str): + """ + Initialize the ConnectionPolicyTargetList + + :param version: Version that contains the resource + :param connection_policy_sid: The SID of the Connection Policy from which to read the Targets. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "connection_policy_sid": connection_policy_sid, + } + self._uri = "/ConnectionPolicies/{connection_policy_sid}/Targets".format( + **self._solution + ) + + def create( + self, + target: str, + friendly_name: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ConnectionPolicyTargetInstance: + """ + Create the ConnectionPolicyTargetInstance + + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. The default is `true`. + + :returns: The created ConnectionPolicyTargetInstance + """ + + data = values.of( + { + "Target": target, + "FriendlyName": friendly_name, + "Priority": priority, + "Weight": weight, + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + ) + + async def create_async( + self, + target: str, + friendly_name: Union[str, object] = values.unset, + priority: Union[int, object] = values.unset, + weight: Union[int, object] = values.unset, + enabled: Union[bool, object] = values.unset, + ) -> ConnectionPolicyTargetInstance: + """ + Asynchronously create the ConnectionPolicyTargetInstance + + :param target: The SIP address you want Twilio to route your calls to. This must be a `sip:` schema. `sips` is NOT supported. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param priority: The relative importance of the target. Can be an integer from 0 to 65535, inclusive, and the default is 10. The lowest number represents the most important target. + :param weight: The value that determines the relative share of the load the Target should receive compared to other Targets with the same priority. Can be an integer from 1 to 65535, inclusive, and the default is 10. Targets with higher values receive more load than those with lower ones with the same priority. + :param enabled: Whether the Target is enabled. The default is `true`. + + :returns: The created ConnectionPolicyTargetInstance + """ + + data = values.of( + { + "Target": target, + "FriendlyName": friendly_name, + "Priority": priority, + "Weight": weight, + "Enabled": serialize.boolean_to_string(enabled), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConnectionPolicyTargetInstance]: + """ + Streams ConnectionPolicyTargetInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConnectionPolicyTargetInstance]: + """ + Asynchronously streams ConnectionPolicyTargetInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConnectionPolicyTargetInstance]: + """ + Lists ConnectionPolicyTargetInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConnectionPolicyTargetInstance]: + """ + Asynchronously lists ConnectionPolicyTargetInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConnectionPolicyTargetPage: + """ + Retrieve a single page of ConnectionPolicyTargetInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConnectionPolicyTargetInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConnectionPolicyTargetPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConnectionPolicyTargetPage: + """ + Asynchronously retrieve a single page of ConnectionPolicyTargetInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of ConnectionPolicyTargetInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConnectionPolicyTargetPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> ConnectionPolicyTargetPage: + """ + Retrieve a specific page of ConnectionPolicyTargetInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConnectionPolicyTargetInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConnectionPolicyTargetPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> ConnectionPolicyTargetPage: + """ + Asynchronously retrieve a specific page of ConnectionPolicyTargetInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConnectionPolicyTargetInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConnectionPolicyTargetPage(self._version, response, self._solution) + + def get(self, sid: str) -> ConnectionPolicyTargetContext: + """ + Constructs a ConnectionPolicyTargetContext + + :param sid: The unique string that we created to identify the Target resource to update. + """ + return ConnectionPolicyTargetContext( + self._version, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ConnectionPolicyTargetContext: + """ + Constructs a ConnectionPolicyTargetContext + + :param sid: The unique string that we created to identify the Target resource to update. + """ + return ConnectionPolicyTargetContext( + self._version, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V1.ConnectionPolicyTargetList>" diff --git a/twilio/rest/voice/v1/dialing_permissions/__init__.py b/twilio/rest/voice/v1/dialing_permissions/__init__.py new file mode 100644 index 0000000000..2346430adc --- /dev/null +++ b/twilio/rest/voice/v1/dialing_permissions/__init__.py @@ -0,0 +1,78 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.voice.v1.dialing_permissions.bulk_country_update import ( + BulkCountryUpdateList, +) +from twilio.rest.voice.v1.dialing_permissions.country import CountryList +from twilio.rest.voice.v1.dialing_permissions.settings import SettingsList + + +class DialingPermissionsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the DialingPermissionsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/DialingPermissions" + + self._bulk_country_updates: Optional[BulkCountryUpdateList] = None + self._countries: Optional[CountryList] = None + self._settings: Optional[SettingsList] = None + + @property + def bulk_country_updates(self) -> BulkCountryUpdateList: + """ + Access the bulk_country_updates + """ + if self._bulk_country_updates is None: + self._bulk_country_updates = BulkCountryUpdateList(self._version) + return self._bulk_country_updates + + @property + def countries(self) -> CountryList: + """ + Access the countries + """ + if self._countries is None: + self._countries = CountryList(self._version) + return self._countries + + @property + def settings(self) -> SettingsList: + """ + Access the settings + """ + if self._settings is None: + self._settings = SettingsList(self._version) + return self._settings + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V1.DialingPermissionsList>" diff --git a/twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py b/twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py new file mode 100644 index 0000000000..4059be8dd7 --- /dev/null +++ b/twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py @@ -0,0 +1,118 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class BulkCountryUpdateInstance(InstanceResource): + """ + :ivar update_count: The number of countries updated + :ivar update_request: A bulk update request to change voice dialing country permissions stored as a URL-encoded, JSON array of update objects. For example : `[ { \"iso_code\": \"GB\", \"low_risk_numbers_enabled\": \"true\", \"high_risk_special_numbers_enabled\":\"true\", \"high_risk_tollfraud_numbers_enabled\": \"false\" } ]` + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.update_count: Optional[int] = deserialize.integer( + payload.get("update_count") + ) + self.update_request: Optional[str] = payload.get("update_request") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Voice.V1.BulkCountryUpdateInstance>" + + +class BulkCountryUpdateList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BulkCountryUpdateList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/DialingPermissions/BulkCountryUpdates" + + def create(self, update_request: str) -> BulkCountryUpdateInstance: + """ + Create the BulkCountryUpdateInstance + + :param update_request: URL encoded JSON array of update objects. example : `[ { \\\"iso_code\\\": \\\"GB\\\", \\\"low_risk_numbers_enabled\\\": \\\"true\\\", \\\"high_risk_special_numbers_enabled\\\":\\\"true\\\", \\\"high_risk_tollfraud_numbers_enabled\\\": \\\"false\\\" } ]` + + :returns: The created BulkCountryUpdateInstance + """ + + data = values.of( + { + "UpdateRequest": update_request, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BulkCountryUpdateInstance(self._version, payload) + + async def create_async(self, update_request: str) -> BulkCountryUpdateInstance: + """ + Asynchronously create the BulkCountryUpdateInstance + + :param update_request: URL encoded JSON array of update objects. example : `[ { \\\"iso_code\\\": \\\"GB\\\", \\\"low_risk_numbers_enabled\\\": \\\"true\\\", \\\"high_risk_special_numbers_enabled\\\":\\\"true\\\", \\\"high_risk_tollfraud_numbers_enabled\\\": \\\"false\\\" } ]` + + :returns: The created BulkCountryUpdateInstance + """ + + data = values.of( + { + "UpdateRequest": update_request, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return BulkCountryUpdateInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V1.BulkCountryUpdateList>" diff --git a/twilio/rest/voice/v1/dialing_permissions/country/__init__.py b/twilio/rest/voice/v1/dialing_permissions/country/__init__.py new file mode 100644 index 0000000000..6a60c23a2f --- /dev/null +++ b/twilio/rest/voice/v1/dialing_permissions/country/__init__.py @@ -0,0 +1,570 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.voice.v1.dialing_permissions.country.highrisk_special_prefix import ( + HighriskSpecialPrefixList, +) + + +class CountryInstance(InstanceResource): + """ + :ivar iso_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). + :ivar name: The name of the country. + :ivar continent: The name of the continent in which the country is located. + :ivar country_codes: The E.164 assigned [country codes(s)](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :ivar low_risk_numbers_enabled: Whether dialing to low-risk numbers is enabled. + :ivar high_risk_special_numbers_enabled: Whether dialing to high-risk special services numbers is enabled. These prefixes include number ranges allocated by the country and include premium numbers, special services, shared cost, and others + :ivar high_risk_tollfraud_numbers_enabled: Whether dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers is enabled. These prefixes include narrow number ranges that have a high-risk of international revenue sharing fraud (IRSF) attacks, also known as [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html). These prefixes are collected from anti-fraud databases and verified by analyzing calls on our network. These prefixes are not available for download and are updated frequently + :ivar url: The absolute URL of this resource. + :ivar links: A list of URLs related to this resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], iso_code: Optional[str] = None + ): + super().__init__(version) + + self.iso_code: Optional[str] = payload.get("iso_code") + self.name: Optional[str] = payload.get("name") + self.continent: Optional[str] = payload.get("continent") + self.country_codes: Optional[List[str]] = payload.get("country_codes") + self.low_risk_numbers_enabled: Optional[bool] = payload.get( + "low_risk_numbers_enabled" + ) + self.high_risk_special_numbers_enabled: Optional[bool] = payload.get( + "high_risk_special_numbers_enabled" + ) + self.high_risk_tollfraud_numbers_enabled: Optional[bool] = payload.get( + "high_risk_tollfraud_numbers_enabled" + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + self._solution = { + "iso_code": iso_code or self.iso_code, + } + self._context: Optional[CountryContext] = None + + @property + def _proxy(self) -> "CountryContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CountryContext for this CountryInstance + """ + if self._context is None: + self._context = CountryContext( + self._version, + iso_code=self._solution["iso_code"], + ) + return self._context + + def fetch(self) -> "CountryInstance": + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CountryInstance": + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + return await self._proxy.fetch_async() + + @property + def highrisk_special_prefixes(self) -> HighriskSpecialPrefixList: + """ + Access the highrisk_special_prefixes + """ + return self._proxy.highrisk_special_prefixes + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V1.CountryInstance {}>".format(context) + + +class CountryContext(InstanceContext): + + def __init__(self, version: Version, iso_code: str): + """ + Initialize the CountryContext + + :param version: Version that contains the resource + :param iso_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the DialingPermissions Country resource to fetch + """ + super().__init__(version) + + # Path Solution + self._solution = { + "iso_code": iso_code, + } + self._uri = "/DialingPermissions/Countries/{iso_code}".format(**self._solution) + + self._highrisk_special_prefixes: Optional[HighriskSpecialPrefixList] = None + + def fetch(self) -> CountryInstance: + """ + Fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CountryInstance( + self._version, + payload, + iso_code=self._solution["iso_code"], + ) + + async def fetch_async(self) -> CountryInstance: + """ + Asynchronous coroutine to fetch the CountryInstance + + + :returns: The fetched CountryInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CountryInstance( + self._version, + payload, + iso_code=self._solution["iso_code"], + ) + + @property + def highrisk_special_prefixes(self) -> HighriskSpecialPrefixList: + """ + Access the highrisk_special_prefixes + """ + if self._highrisk_special_prefixes is None: + self._highrisk_special_prefixes = HighriskSpecialPrefixList( + self._version, + self._solution["iso_code"], + ) + return self._highrisk_special_prefixes + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V1.CountryContext {}>".format(context) + + +class CountryPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: + """ + Build an instance of CountryInstance + + :param payload: Payload response from the API + """ + return CountryInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V1.CountryPage>" + + +class CountryList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CountryList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/DialingPermissions/Countries" + + def stream( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CountryInstance]: + """ + Streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param str continent: Filter to retrieve the country permissions by specifying the continent + :param str country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + iso_code=iso_code, + continent=continent, + country_code=country_code, + low_risk_numbers_enabled=low_risk_numbers_enabled, + high_risk_special_numbers_enabled=high_risk_special_numbers_enabled, + high_risk_tollfraud_numbers_enabled=high_risk_tollfraud_numbers_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CountryInstance]: + """ + Asynchronously streams CountryInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param str continent: Filter to retrieve the country permissions by specifying the continent + :param str country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + iso_code=iso_code, + continent=continent, + country_code=country_code, + low_risk_numbers_enabled=low_risk_numbers_enabled, + high_risk_special_numbers_enabled=high_risk_special_numbers_enabled, + high_risk_tollfraud_numbers_enabled=high_risk_tollfraud_numbers_enabled, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param str continent: Filter to retrieve the country permissions by specifying the continent + :param str country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + iso_code=iso_code, + continent=continent, + country_code=country_code, + low_risk_numbers_enabled=low_risk_numbers_enabled, + high_risk_special_numbers_enabled=high_risk_special_numbers_enabled, + high_risk_tollfraud_numbers_enabled=high_risk_tollfraud_numbers_enabled, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CountryInstance]: + """ + Asynchronously lists CountryInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param str continent: Filter to retrieve the country permissions by specifying the continent + :param str country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param bool low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param bool high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param bool high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + iso_code=iso_code, + continent=continent, + country_code=country_code, + low_risk_numbers_enabled=low_risk_numbers_enabled, + high_risk_special_numbers_enabled=high_risk_special_numbers_enabled, + high_risk_tollfraud_numbers_enabled=high_risk_tollfraud_numbers_enabled, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param continent: Filter to retrieve the country permissions by specifying the continent + :param country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "IsoCode": iso_code, + "Continent": continent, + "CountryCode": country_code, + "LowRiskNumbersEnabled": serialize.boolean_to_string( + low_risk_numbers_enabled + ), + "HighRiskSpecialNumbersEnabled": serialize.boolean_to_string( + high_risk_special_numbers_enabled + ), + "HighRiskTollfraudNumbersEnabled": serialize.boolean_to_string( + high_risk_tollfraud_numbers_enabled + ), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + async def page_async( + self, + iso_code: Union[str, object] = values.unset, + continent: Union[str, object] = values.unset, + country_code: Union[str, object] = values.unset, + low_risk_numbers_enabled: Union[bool, object] = values.unset, + high_risk_special_numbers_enabled: Union[bool, object] = values.unset, + high_risk_tollfraud_numbers_enabled: Union[bool, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CountryPage: + """ + Asynchronously retrieve a single page of CountryInstance records from the API. + Request is executed immediately + + :param iso_code: Filter to retrieve the country permissions by specifying the [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) + :param continent: Filter to retrieve the country permissions by specifying the continent + :param country_code: Filter the results by specified [country codes](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) + :param low_risk_numbers_enabled: Filter to retrieve the country permissions with dialing to low-risk numbers enabled. Can be: `true` or `false`. + :param high_risk_special_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk special service numbers enabled. Can be: `true` or `false` + :param high_risk_tollfraud_numbers_enabled: Filter to retrieve the country permissions with dialing to high-risk [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html) numbers enabled. Can be: `true` or `false`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CountryInstance + """ + data = values.of( + { + "IsoCode": iso_code, + "Continent": continent, + "CountryCode": country_code, + "LowRiskNumbersEnabled": serialize.boolean_to_string( + low_risk_numbers_enabled + ), + "HighRiskSpecialNumbersEnabled": serialize.boolean_to_string( + high_risk_special_numbers_enabled + ), + "HighRiskTollfraudNumbersEnabled": serialize.boolean_to_string( + high_risk_tollfraud_numbers_enabled + ), + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CountryPage(self._version, response) + + def get_page(self, target_url: str) -> CountryPage: + """ + Retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CountryPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CountryPage: + """ + Asynchronously retrieve a specific page of CountryInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CountryInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CountryPage(self._version, response) + + def get(self, iso_code: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the DialingPermissions Country resource to fetch + """ + return CountryContext(self._version, iso_code=iso_code) + + def __call__(self, iso_code: str) -> CountryContext: + """ + Constructs a CountryContext + + :param iso_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the DialingPermissions Country resource to fetch + """ + return CountryContext(self._version, iso_code=iso_code) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V1.CountryList>" diff --git a/twilio/rest/voice/v1/dialing_permissions/country/highrisk_special_prefix.py b/twilio/rest/voice/v1/dialing_permissions/country/highrisk_special_prefix.py new file mode 100644 index 0000000000..75300e928c --- /dev/null +++ b/twilio/rest/voice/v1/dialing_permissions/country/highrisk_special_prefix.py @@ -0,0 +1,290 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class HighriskSpecialPrefixInstance(InstanceResource): + """ + :ivar prefix: A prefix is a contiguous number range for a block of E.164 numbers that includes the E.164 assigned country code. For example, a North American Numbering Plan prefix like `+1510720` written like `+1(510) 720` matches all numbers inclusive from `+1(510) 720-0000` to `+1(510) 720-9999`. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], iso_code: str): + super().__init__(version) + + self.prefix: Optional[str] = payload.get("prefix") + + self._solution = { + "iso_code": iso_code, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V1.HighriskSpecialPrefixInstance {}>".format(context) + + +class HighriskSpecialPrefixPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> HighriskSpecialPrefixInstance: + """ + Build an instance of HighriskSpecialPrefixInstance + + :param payload: Payload response from the API + """ + return HighriskSpecialPrefixInstance( + self._version, payload, iso_code=self._solution["iso_code"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V1.HighriskSpecialPrefixPage>" + + +class HighriskSpecialPrefixList(ListResource): + + def __init__(self, version: Version, iso_code: str): + """ + Initialize the HighriskSpecialPrefixList + + :param version: Version that contains the resource + :param iso_code: The [ISO 3166-1 country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) to identify the country permissions from which high-risk special service number prefixes are fetched + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "iso_code": iso_code, + } + self._uri = ( + "/DialingPermissions/Countries/{iso_code}/HighRiskSpecialPrefixes".format( + **self._solution + ) + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[HighriskSpecialPrefixInstance]: + """ + Streams HighriskSpecialPrefixInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[HighriskSpecialPrefixInstance]: + """ + Asynchronously streams HighriskSpecialPrefixInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[HighriskSpecialPrefixInstance]: + """ + Lists HighriskSpecialPrefixInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[HighriskSpecialPrefixInstance]: + """ + Asynchronously lists HighriskSpecialPrefixInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> HighriskSpecialPrefixPage: + """ + Retrieve a single page of HighriskSpecialPrefixInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of HighriskSpecialPrefixInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return HighriskSpecialPrefixPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> HighriskSpecialPrefixPage: + """ + Asynchronously retrieve a single page of HighriskSpecialPrefixInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of HighriskSpecialPrefixInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return HighriskSpecialPrefixPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> HighriskSpecialPrefixPage: + """ + Retrieve a specific page of HighriskSpecialPrefixInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of HighriskSpecialPrefixInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return HighriskSpecialPrefixPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> HighriskSpecialPrefixPage: + """ + Asynchronously retrieve a specific page of HighriskSpecialPrefixInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of HighriskSpecialPrefixInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return HighriskSpecialPrefixPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V1.HighriskSpecialPrefixList>" diff --git a/twilio/rest/voice/v1/dialing_permissions/settings.py b/twilio/rest/voice/v1/dialing_permissions/settings.py new file mode 100644 index 0000000000..9e7aa0babb --- /dev/null +++ b/twilio/rest/voice/v1/dialing_permissions/settings.py @@ -0,0 +1,262 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Any, Dict, Optional, Union +from twilio.base import serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class SettingsInstance(InstanceResource): + """ + :ivar dialing_permissions_inheritance: `true` if the sub-account will inherit voice dialing permissions from the Master Project; otherwise `false`. + :ivar url: The absolute URL of this resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.dialing_permissions_inheritance: Optional[bool] = payload.get( + "dialing_permissions_inheritance" + ) + self.url: Optional[str] = payload.get("url") + + self._context: Optional[SettingsContext] = None + + @property + def _proxy(self) -> "SettingsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SettingsContext for this SettingsInstance + """ + if self._context is None: + self._context = SettingsContext( + self._version, + ) + return self._context + + def fetch(self) -> "SettingsInstance": + """ + Fetch the SettingsInstance + + + :returns: The fetched SettingsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SettingsInstance": + """ + Asynchronous coroutine to fetch the SettingsInstance + + + :returns: The fetched SettingsInstance + """ + return await self._proxy.fetch_async() + + def update( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> "SettingsInstance": + """ + Update the SettingsInstance + + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: The updated SettingsInstance + """ + return self._proxy.update( + dialing_permissions_inheritance=dialing_permissions_inheritance, + ) + + async def update_async( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> "SettingsInstance": + """ + Asynchronous coroutine to update the SettingsInstance + + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: The updated SettingsInstance + """ + return await self._proxy.update_async( + dialing_permissions_inheritance=dialing_permissions_inheritance, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Voice.V1.SettingsInstance>" + + +class SettingsContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the SettingsContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/Settings" + + def fetch(self) -> SettingsInstance: + """ + Fetch the SettingsInstance + + + :returns: The fetched SettingsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SettingsInstance( + self._version, + payload, + ) + + async def fetch_async(self) -> SettingsInstance: + """ + Asynchronous coroutine to fetch the SettingsInstance + + + :returns: The fetched SettingsInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SettingsInstance( + self._version, + payload, + ) + + def update( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> SettingsInstance: + """ + Update the SettingsInstance + + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: The updated SettingsInstance + """ + + data = values.of( + { + "DialingPermissionsInheritance": serialize.boolean_to_string( + dialing_permissions_inheritance + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SettingsInstance(self._version, payload) + + async def update_async( + self, dialing_permissions_inheritance: Union[bool, object] = values.unset + ) -> SettingsInstance: + """ + Asynchronous coroutine to update the SettingsInstance + + :param dialing_permissions_inheritance: `true` for the sub-account to inherit voice dialing permissions from the Master Project; otherwise `false`. + + :returns: The updated SettingsInstance + """ + + data = values.of( + { + "DialingPermissionsInheritance": serialize.boolean_to_string( + dialing_permissions_inheritance + ), + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SettingsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Voice.V1.SettingsContext>" + + +class SettingsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SettingsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> SettingsContext: + """ + Constructs a SettingsContext + + """ + return SettingsContext(self._version) + + def __call__(self) -> SettingsContext: + """ + Constructs a SettingsContext + + """ + return SettingsContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V1.SettingsList>" diff --git a/twilio/rest/voice/v1/ip_record.py b/twilio/rest/voice/v1/ip_record.py new file mode 100644 index 0000000000..05e9741fa5 --- /dev/null +++ b/twilio/rest/voice/v1/ip_record.py @@ -0,0 +1,619 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class IpRecordInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IP Record resource. + :ivar sid: The unique string that we created to identify the IP Record resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar ip_address: An IP address in dotted decimal notation, IPv4 only. + :ivar cidr_prefix_length: An integer representing the length of the [CIDR](https://tools.ietf.org/html/rfc4632) prefix to use with this IP address. By default the entire IP address is used, which for IPv4 is value 32. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.ip_address: Optional[str] = payload.get("ip_address") + self.cidr_prefix_length: Optional[int] = deserialize.integer( + payload.get("cidr_prefix_length") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[IpRecordContext] = None + + @property + def _proxy(self) -> "IpRecordContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: IpRecordContext for this IpRecordInstance + """ + if self._context is None: + self._context = IpRecordContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the IpRecordInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpRecordInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "IpRecordInstance": + """ + Fetch the IpRecordInstance + + + :returns: The fetched IpRecordInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "IpRecordInstance": + """ + Asynchronous coroutine to fetch the IpRecordInstance + + + :returns: The fetched IpRecordInstance + """ + return await self._proxy.fetch_async() + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> "IpRecordInstance": + """ + Update the IpRecordInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated IpRecordInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + ) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> "IpRecordInstance": + """ + Asynchronous coroutine to update the IpRecordInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated IpRecordInstance + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V1.IpRecordInstance {}>".format(context) + + +class IpRecordContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the IpRecordContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/IpRecords/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the IpRecordInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the IpRecordInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> IpRecordInstance: + """ + Fetch the IpRecordInstance + + + :returns: The fetched IpRecordInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return IpRecordInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> IpRecordInstance: + """ + Asynchronous coroutine to fetch the IpRecordInstance + + + :returns: The fetched IpRecordInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return IpRecordInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, friendly_name: Union[str, object] = values.unset + ) -> IpRecordInstance: + """ + Update the IpRecordInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated IpRecordInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpRecordInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, friendly_name: Union[str, object] = values.unset + ) -> IpRecordInstance: + """ + Asynchronous coroutine to update the IpRecordInstance + + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + + :returns: The updated IpRecordInstance + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpRecordInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V1.IpRecordContext {}>".format(context) + + +class IpRecordPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> IpRecordInstance: + """ + Build an instance of IpRecordInstance + + :param payload: Payload response from the API + """ + return IpRecordInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V1.IpRecordPage>" + + +class IpRecordList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the IpRecordList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/IpRecords" + + def create( + self, + ip_address: str, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpRecordInstance: + """ + Create the IpRecordInstance + + :param ip_address: An IP address in dotted decimal notation, IPv4 only. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the [CIDR](https://tools.ietf.org/html/rfc4632) prefix to use with this IP address. By default the entire IP address is used, which for IPv4 is value 32. + + :returns: The created IpRecordInstance + """ + + data = values.of( + { + "IpAddress": ip_address, + "FriendlyName": friendly_name, + "CidrPrefixLength": cidr_prefix_length, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpRecordInstance(self._version, payload) + + async def create_async( + self, + ip_address: str, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> IpRecordInstance: + """ + Asynchronously create the IpRecordInstance + + :param ip_address: An IP address in dotted decimal notation, IPv4 only. + :param friendly_name: A descriptive string that you create to describe the resource. It is not unique and can be up to 255 characters long. + :param cidr_prefix_length: An integer representing the length of the [CIDR](https://tools.ietf.org/html/rfc4632) prefix to use with this IP address. By default the entire IP address is used, which for IPv4 is value 32. + + :returns: The created IpRecordInstance + """ + + data = values.of( + { + "IpAddress": ip_address, + "FriendlyName": friendly_name, + "CidrPrefixLength": cidr_prefix_length, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return IpRecordInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[IpRecordInstance]: + """ + Streams IpRecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[IpRecordInstance]: + """ + Asynchronously streams IpRecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpRecordInstance]: + """ + Lists IpRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[IpRecordInstance]: + """ + Asynchronously lists IpRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpRecordPage: + """ + Retrieve a single page of IpRecordInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpRecordInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpRecordPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> IpRecordPage: + """ + Asynchronously retrieve a single page of IpRecordInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of IpRecordInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return IpRecordPage(self._version, response) + + def get_page(self, target_url: str) -> IpRecordPage: + """ + Retrieve a specific page of IpRecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpRecordInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return IpRecordPage(self._version, response) + + async def get_page_async(self, target_url: str) -> IpRecordPage: + """ + Asynchronously retrieve a specific page of IpRecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of IpRecordInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return IpRecordPage(self._version, response) + + def get(self, sid: str) -> IpRecordContext: + """ + Constructs a IpRecordContext + + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. + """ + return IpRecordContext(self._version, sid=sid) + + def __call__(self, sid: str) -> IpRecordContext: + """ + Constructs a IpRecordContext + + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. + """ + return IpRecordContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V1.IpRecordList>" diff --git a/twilio/rest/voice/v1/source_ip_mapping.py b/twilio/rest/voice/v1/source_ip_mapping.py new file mode 100644 index 0000000000..749d2b0034 --- /dev/null +++ b/twilio/rest/voice/v1/source_ip_mapping.py @@ -0,0 +1,599 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Voice + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class SourceIpMappingInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the IP Record resource. + :ivar ip_record_sid: The Twilio-provided string that uniquely identifies the IP Record resource to map from. + :ivar sip_domain_sid: The SID of the SIP Domain that the IP Record is mapped to. + :ivar date_created: The date and time in GMT that the resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_updated: The date and time in GMT that the resource was last updated specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.ip_record_sid: Optional[str] = payload.get("ip_record_sid") + self.sip_domain_sid: Optional[str] = payload.get("sip_domain_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SourceIpMappingContext] = None + + @property + def _proxy(self) -> "SourceIpMappingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SourceIpMappingContext for this SourceIpMappingInstance + """ + if self._context is None: + self._context = SourceIpMappingContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SourceIpMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SourceIpMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SourceIpMappingInstance": + """ + Fetch the SourceIpMappingInstance + + + :returns: The fetched SourceIpMappingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SourceIpMappingInstance": + """ + Asynchronous coroutine to fetch the SourceIpMappingInstance + + + :returns: The fetched SourceIpMappingInstance + """ + return await self._proxy.fetch_async() + + def update(self, sip_domain_sid: str) -> "SourceIpMappingInstance": + """ + Update the SourceIpMappingInstance + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The updated SourceIpMappingInstance + """ + return self._proxy.update( + sip_domain_sid=sip_domain_sid, + ) + + async def update_async(self, sip_domain_sid: str) -> "SourceIpMappingInstance": + """ + Asynchronous coroutine to update the SourceIpMappingInstance + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The updated SourceIpMappingInstance + """ + return await self._proxy.update_async( + sip_domain_sid=sip_domain_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V1.SourceIpMappingInstance {}>".format(context) + + +class SourceIpMappingContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SourceIpMappingContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/SourceIpMappings/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the SourceIpMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SourceIpMappingInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SourceIpMappingInstance: + """ + Fetch the SourceIpMappingInstance + + + :returns: The fetched SourceIpMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SourceIpMappingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SourceIpMappingInstance: + """ + Asynchronous coroutine to fetch the SourceIpMappingInstance + + + :returns: The fetched SourceIpMappingInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SourceIpMappingInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update(self, sip_domain_sid: str) -> SourceIpMappingInstance: + """ + Update the SourceIpMappingInstance + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The updated SourceIpMappingInstance + """ + + data = values.of( + { + "SipDomainSid": sip_domain_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SourceIpMappingInstance( + self._version, payload, sid=self._solution["sid"] + ) + + async def update_async(self, sip_domain_sid: str) -> SourceIpMappingInstance: + """ + Asynchronous coroutine to update the SourceIpMappingInstance + + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The updated SourceIpMappingInstance + """ + + data = values.of( + { + "SipDomainSid": sip_domain_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SourceIpMappingInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Voice.V1.SourceIpMappingContext {}>".format(context) + + +class SourceIpMappingPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SourceIpMappingInstance: + """ + Build an instance of SourceIpMappingInstance + + :param payload: Payload response from the API + """ + return SourceIpMappingInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V1.SourceIpMappingPage>" + + +class SourceIpMappingList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SourceIpMappingList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SourceIpMappings" + + def create( + self, ip_record_sid: str, sip_domain_sid: str + ) -> SourceIpMappingInstance: + """ + Create the SourceIpMappingInstance + + :param ip_record_sid: The Twilio-provided string that uniquely identifies the IP Record resource to map from. + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The created SourceIpMappingInstance + """ + + data = values.of( + { + "IpRecordSid": ip_record_sid, + "SipDomainSid": sip_domain_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SourceIpMappingInstance(self._version, payload) + + async def create_async( + self, ip_record_sid: str, sip_domain_sid: str + ) -> SourceIpMappingInstance: + """ + Asynchronously create the SourceIpMappingInstance + + :param ip_record_sid: The Twilio-provided string that uniquely identifies the IP Record resource to map from. + :param sip_domain_sid: The SID of the SIP Domain that the IP Record should be mapped to. + + :returns: The created SourceIpMappingInstance + """ + + data = values.of( + { + "IpRecordSid": ip_record_sid, + "SipDomainSid": sip_domain_sid, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SourceIpMappingInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SourceIpMappingInstance]: + """ + Streams SourceIpMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SourceIpMappingInstance]: + """ + Asynchronously streams SourceIpMappingInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SourceIpMappingInstance]: + """ + Lists SourceIpMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SourceIpMappingInstance]: + """ + Asynchronously lists SourceIpMappingInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SourceIpMappingPage: + """ + Retrieve a single page of SourceIpMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SourceIpMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SourceIpMappingPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SourceIpMappingPage: + """ + Asynchronously retrieve a single page of SourceIpMappingInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SourceIpMappingInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SourceIpMappingPage(self._version, response) + + def get_page(self, target_url: str) -> SourceIpMappingPage: + """ + Retrieve a specific page of SourceIpMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SourceIpMappingInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SourceIpMappingPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SourceIpMappingPage: + """ + Asynchronously retrieve a specific page of SourceIpMappingInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SourceIpMappingInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SourceIpMappingPage(self._version, response) + + def get(self, sid: str) -> SourceIpMappingContext: + """ + Constructs a SourceIpMappingContext + + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. + """ + return SourceIpMappingContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SourceIpMappingContext: + """ + Constructs a SourceIpMappingContext + + :param sid: The Twilio-provided string that uniquely identifies the IP Record resource to update. + """ + return SourceIpMappingContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Voice.V1.SourceIpMappingList>" diff --git a/twilio/rest/wireless/WirelessBase.py b/twilio/rest/wireless/WirelessBase.py new file mode 100644 index 0000000000..0228c4d666 --- /dev/null +++ b/twilio/rest/wireless/WirelessBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional + +from twilio.base.domain import Domain +from twilio.rest import Client +from twilio.rest.wireless.v1 import V1 + + +class WirelessBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Wireless Domain + + :returns: Domain for Wireless + """ + super().__init__(twilio, "https://wireless.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Wireless + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Wireless>" diff --git a/twilio/rest/wireless/__init__.py b/twilio/rest/wireless/__init__.py new file mode 100644 index 0000000000..3b7a40977c --- /dev/null +++ b/twilio/rest/wireless/__init__.py @@ -0,0 +1,43 @@ +from warnings import warn + +from twilio.rest.wireless.WirelessBase import WirelessBase +from twilio.rest.wireless.v1.command import CommandList +from twilio.rest.wireless.v1.rate_plan import RatePlanList +from twilio.rest.wireless.v1.sim import SimList +from twilio.rest.wireless.v1.usage_record import UsageRecordList + + +class Wireless(WirelessBase): + @property + def usage_records(self) -> UsageRecordList: + warn( + "usage_records is deprecated. Use v1.usage_records instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.usage_records + + @property + def commands(self) -> CommandList: + warn( + "commands is deprecated. Use v1.commands instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.commands + + @property + def rate_plans(self) -> RatePlanList: + warn( + "rate_plans is deprecated. Use v1.rate_plans instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.rate_plans + + @property + def sims(self) -> SimList: + warn( + "sims is deprecated. Use v1.sims instead.", DeprecationWarning, stacklevel=2 + ) + return self.v1.sims diff --git a/twilio/rest/wireless/v1/__init__.py b/twilio/rest/wireless/v1/__init__.py new file mode 100644 index 0000000000..8f4d0dc5d7 --- /dev/null +++ b/twilio/rest/wireless/v1/__init__.py @@ -0,0 +1,67 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Wireless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from typing import Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.wireless.v1.command import CommandList +from twilio.rest.wireless.v1.rate_plan import RatePlanList +from twilio.rest.wireless.v1.sim import SimList +from twilio.rest.wireless.v1.usage_record import UsageRecordList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Wireless + + :param domain: The Twilio.wireless domain + """ + super().__init__(domain, "v1") + self._commands: Optional[CommandList] = None + self._rate_plans: Optional[RatePlanList] = None + self._sims: Optional[SimList] = None + self._usage_records: Optional[UsageRecordList] = None + + @property + def commands(self) -> CommandList: + if self._commands is None: + self._commands = CommandList(self) + return self._commands + + @property + def rate_plans(self) -> RatePlanList: + if self._rate_plans is None: + self._rate_plans = RatePlanList(self) + return self._rate_plans + + @property + def sims(self) -> SimList: + if self._sims is None: + self._sims = SimList(self) + return self._sims + + @property + def usage_records(self) -> UsageRecordList: + if self._usage_records is None: + self._usage_records = UsageRecordList(self) + return self._usage_records + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "<Twilio.Wireless.V1>" diff --git a/twilio/rest/wireless/v1/command.py b/twilio/rest/wireless/v1/command.py new file mode 100644 index 0000000000..a6e8f0b39d --- /dev/null +++ b/twilio/rest/wireless/v1/command.py @@ -0,0 +1,669 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Wireless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class CommandInstance(InstanceResource): + + class CommandMode(object): + TEXT = "text" + BINARY = "binary" + + class Direction(object): + FROM_SIM = "from_sim" + TO_SIM = "to_sim" + + class Status(object): + QUEUED = "queued" + SENT = "sent" + DELIVERED = "delivered" + RECEIVED = "received" + FAILED = "failed" + + class Transport(object): + SMS = "sms" + IP = "ip" + + """ + :ivar sid: The unique string that we created to identify the Command resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Command resource. + :ivar sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) that the Command was sent to or from. + :ivar command: The message being sent to or from the SIM. For text mode messages, this can be up to 160 characters. For binary mode messages, this is a series of up to 140 bytes of data encoded using base64. + :ivar command_mode: + :ivar transport: + :ivar delivery_receipt_requested: Whether to request a delivery receipt. + :ivar status: + :ivar direction: + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.command: Optional[str] = payload.get("command") + self.command_mode: Optional["CommandInstance.CommandMode"] = payload.get( + "command_mode" + ) + self.transport: Optional["CommandInstance.Transport"] = payload.get("transport") + self.delivery_receipt_requested: Optional[bool] = payload.get( + "delivery_receipt_requested" + ) + self.status: Optional["CommandInstance.Status"] = payload.get("status") + self.direction: Optional["CommandInstance.Direction"] = payload.get("direction") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[CommandContext] = None + + @property + def _proxy(self) -> "CommandContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CommandContext for this CommandInstance + """ + if self._context is None: + self._context = CommandContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CommandInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CommandInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "CommandInstance": + """ + Fetch the CommandInstance + + + :returns: The fetched CommandInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CommandInstance": + """ + Asynchronous coroutine to fetch the CommandInstance + + + :returns: The fetched CommandInstance + """ + return await self._proxy.fetch_async() + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Wireless.V1.CommandInstance {}>".format(context) + + +class CommandContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CommandContext + + :param version: Version that contains the resource + :param sid: The SID of the Command resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Commands/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the CommandInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CommandInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> CommandInstance: + """ + Fetch the CommandInstance + + + :returns: The fetched CommandInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> CommandInstance: + """ + Asynchronous coroutine to fetch the CommandInstance + + + :returns: The fetched CommandInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return CommandInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Wireless.V1.CommandContext {}>".format(context) + + +class CommandPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CommandInstance: + """ + Build an instance of CommandInstance + + :param payload: Payload response from the API + """ + return CommandInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Wireless.V1.CommandPage>" + + +class CommandList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CommandList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Commands" + + def create( + self, + command: str, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union["CommandInstance.CommandMode", object] = values.unset, + include_sid: Union[str, object] = values.unset, + delivery_receipt_requested: Union[bool, object] = values.unset, + ) -> CommandInstance: + """ + Create the CommandInstance + + :param command: The message body of the Command. Can be plain text in text mode or a Base64 encoded byte string in binary mode. + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to send the Command to. + :param callback_method: The HTTP method we use to call `callback_url`. Can be: `POST` or `GET`, and the default is `POST`. + :param callback_url: The URL we call using the `callback_url` when the Command has finished sending, whether the command was delivered or it failed. + :param command_mode: + :param include_sid: Whether to include the SID of the command in the message body. Can be: `none`, `start`, or `end`, and the default behavior is `none`. When sending a Command to a SIM in text mode, we can automatically include the SID of the Command in the message body, which could be used to ensure that the device does not process the same Command more than once. A value of `start` will prepend the message with the Command SID, and `end` will append it to the end, separating the Command SID from the message body with a space. The length of the Command SID is included in the 160 character limit so the SMS body must be 128 characters or less before the Command SID is included. + :param delivery_receipt_requested: Whether to request delivery receipt from the recipient. For Commands that request delivery receipt, the Command state transitions to 'delivered' once the server has received a delivery receipt from the device. The default value is `true`. + + :returns: The created CommandInstance + """ + + data = values.of( + { + "Command": command, + "Sim": sim, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "CommandMode": command_mode, + "IncludeSid": include_sid, + "DeliveryReceiptRequested": serialize.boolean_to_string( + delivery_receipt_requested + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CommandInstance(self._version, payload) + + async def create_async( + self, + command: str, + sim: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + command_mode: Union["CommandInstance.CommandMode", object] = values.unset, + include_sid: Union[str, object] = values.unset, + delivery_receipt_requested: Union[bool, object] = values.unset, + ) -> CommandInstance: + """ + Asynchronously create the CommandInstance + + :param command: The message body of the Command. Can be plain text in text mode or a Base64 encoded byte string in binary mode. + :param sim: The `sid` or `unique_name` of the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to send the Command to. + :param callback_method: The HTTP method we use to call `callback_url`. Can be: `POST` or `GET`, and the default is `POST`. + :param callback_url: The URL we call using the `callback_url` when the Command has finished sending, whether the command was delivered or it failed. + :param command_mode: + :param include_sid: Whether to include the SID of the command in the message body. Can be: `none`, `start`, or `end`, and the default behavior is `none`. When sending a Command to a SIM in text mode, we can automatically include the SID of the Command in the message body, which could be used to ensure that the device does not process the same Command more than once. A value of `start` will prepend the message with the Command SID, and `end` will append it to the end, separating the Command SID from the message body with a space. The length of the Command SID is included in the 160 character limit so the SMS body must be 128 characters or less before the Command SID is included. + :param delivery_receipt_requested: Whether to request delivery receipt from the recipient. For Commands that request delivery receipt, the Command state transitions to 'delivered' once the server has received a delivery receipt from the device. The default value is `true`. + + :returns: The created CommandInstance + """ + + data = values.of( + { + "Command": command, + "Sim": sim, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "CommandMode": command_mode, + "IncludeSid": include_sid, + "DeliveryReceiptRequested": serialize.boolean_to_string( + delivery_receipt_requested + ), + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return CommandInstance(self._version, payload) + + def stream( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CommandInstance]: + """ + Streams CommandInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param "CommandInstance.Status" status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param "CommandInstance.Direction" direction: Only return Commands with this direction value. + :param "CommandInstance.Transport" transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + sim=sim, + status=status, + direction=direction, + transport=transport, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[CommandInstance]: + """ + Asynchronously streams CommandInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param "CommandInstance.Status" status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param "CommandInstance.Direction" direction: Only return Commands with this direction value. + :param "CommandInstance.Transport" transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + sim=sim, + status=status, + direction=direction, + transport=transport, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CommandInstance]: + """ + Lists CommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param "CommandInstance.Status" status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param "CommandInstance.Direction" direction: Only return Commands with this direction value. + :param "CommandInstance.Transport" transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + sim=sim, + status=status, + direction=direction, + transport=transport, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CommandInstance]: + """ + Asynchronously lists CommandInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param "CommandInstance.Status" status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param "CommandInstance.Direction" direction: Only return Commands with this direction value. + :param "CommandInstance.Transport" transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + sim=sim, + status=status, + direction=direction, + transport=transport, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CommandPage: + """ + Retrieve a single page of CommandInstance records from the API. + Request is executed immediately + + :param sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param direction: Only return Commands with this direction value. + :param transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CommandInstance + """ + data = values.of( + { + "Sim": sim, + "Status": status, + "Direction": direction, + "Transport": transport, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CommandPage(self._version, response) + + async def page_async( + self, + sim: Union[str, object] = values.unset, + status: Union["CommandInstance.Status", object] = values.unset, + direction: Union["CommandInstance.Direction", object] = values.unset, + transport: Union["CommandInstance.Transport", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> CommandPage: + """ + Asynchronously retrieve a single page of CommandInstance records from the API. + Request is executed immediately + + :param sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read. + :param status: The status of the resources to read. Can be: `queued`, `sent`, `delivered`, `received`, or `failed`. + :param direction: Only return Commands with this direction value. + :param transport: Only return Commands with this transport value. Can be: `sms` or `ip`. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of CommandInstance + """ + data = values.of( + { + "Sim": sim, + "Status": status, + "Direction": direction, + "Transport": transport, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CommandPage(self._version, response) + + def get_page(self, target_url: str) -> CommandPage: + """ + Retrieve a specific page of CommandInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CommandInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CommandPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CommandPage: + """ + Asynchronously retrieve a specific page of CommandInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CommandInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CommandPage(self._version, response) + + def get(self, sid: str) -> CommandContext: + """ + Constructs a CommandContext + + :param sid: The SID of the Command resource to fetch. + """ + return CommandContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CommandContext: + """ + Constructs a CommandContext + + :param sid: The SID of the Command resource to fetch. + """ + return CommandContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Wireless.V1.CommandList>" diff --git a/twilio/rest/wireless/v1/rate_plan.py b/twilio/rest/wireless/v1/rate_plan.py new file mode 100644 index 0000000000..23efabe9b0 --- /dev/null +++ b/twilio/rest/wireless/v1/rate_plan.py @@ -0,0 +1,728 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Wireless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, serialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class RatePlanInstance(InstanceResource): + + class DataLimitStrategy(object): + BLOCK = "block" + THROTTLE = "throttle" + + """ + :ivar sid: The unique string that we created to identify the RatePlan resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the RatePlan resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar data_enabled: Whether SIMs can use GPRS/3G/4G/LTE data connectivity. + :ivar data_metering: The model used to meter data usage. Can be: `payg` and `quota-1`, `quota-10`, and `quota-50`. Learn more about the available [data metering models](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#payg-vs-quota-data-plans). + :ivar data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on the home network (T-Mobile USA). The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. + :ivar messaging_enabled: Whether SIMs can make, send, and receive SMS using [Commands](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :ivar voice_enabled: Deprecated. Whether SIMs can make and receive voice calls. + :ivar national_roaming_enabled: Whether SIMs can roam on networks other than the home network (T-Mobile USA) in the United States. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming). + :ivar national_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on non-home networks in the United States. The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. + :ivar international_roaming: The list of services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States. Can contain: `data` and `messaging`. + :ivar international_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month when roaming outside the United States. Can be up to 2TB. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar date_updated: The date and time in GMT when the resource was last updated specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.data_enabled: Optional[bool] = payload.get("data_enabled") + self.data_metering: Optional[str] = payload.get("data_metering") + self.data_limit: Optional[int] = deserialize.integer(payload.get("data_limit")) + self.messaging_enabled: Optional[bool] = payload.get("messaging_enabled") + self.voice_enabled: Optional[bool] = payload.get("voice_enabled") + self.national_roaming_enabled: Optional[bool] = payload.get( + "national_roaming_enabled" + ) + self.national_roaming_data_limit: Optional[int] = deserialize.integer( + payload.get("national_roaming_data_limit") + ) + self.international_roaming: Optional[List[str]] = payload.get( + "international_roaming" + ) + self.international_roaming_data_limit: Optional[int] = deserialize.integer( + payload.get("international_roaming_data_limit") + ) + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[RatePlanContext] = None + + @property + def _proxy(self) -> "RatePlanContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RatePlanContext for this RatePlanInstance + """ + if self._context is None: + self._context = RatePlanContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RatePlanInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RatePlanInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "RatePlanInstance": + """ + Fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "RatePlanInstance": + """ + Asynchronous coroutine to fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "RatePlanInstance": + """ + Update the RatePlanInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + + :returns: The updated RatePlanInstance + """ + return self._proxy.update( + unique_name=unique_name, + friendly_name=friendly_name, + ) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "RatePlanInstance": + """ + Asynchronous coroutine to update the RatePlanInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + + :returns: The updated RatePlanInstance + """ + return await self._proxy.update_async( + unique_name=unique_name, + friendly_name=friendly_name, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Wireless.V1.RatePlanInstance {}>".format(context) + + +class RatePlanContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the RatePlanContext + + :param version: Version that contains the resource + :param sid: The SID of the RatePlan resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/RatePlans/{sid}".format(**self._solution) + + def delete(self) -> bool: + """ + Deletes the RatePlanInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RatePlanInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> RatePlanInstance: + """ + Fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> RatePlanInstance: + """ + Asynchronous coroutine to fetch the RatePlanInstance + + + :returns: The fetched RatePlanInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> RatePlanInstance: + """ + Update the RatePlanInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + + :returns: The updated RatePlanInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> RatePlanInstance: + """ + Asynchronous coroutine to update the RatePlanInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + + :returns: The updated RatePlanInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Wireless.V1.RatePlanContext {}>".format(context) + + +class RatePlanPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RatePlanInstance: + """ + Build an instance of RatePlanInstance + + :param payload: Payload response from the API + """ + return RatePlanInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Wireless.V1.RatePlanPage>" + + +class RatePlanList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RatePlanList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/RatePlans" + + def create( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + national_roaming_data_limit: Union[int, object] = values.unset, + international_roaming_data_limit: Union[int, object] = values.unset, + data_limit_strategy: Union[ + "RatePlanInstance.DataLimitStrategy", object + ] = values.unset, + ) -> RatePlanInstance: + """ + Create the RatePlanInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + :param data_enabled: Whether SIMs can use GPRS/3G/4G/LTE data connectivity. + :param data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on the home network (T-Mobile USA). The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB and the default value is `1000`. + :param data_metering: The model used to meter data usage. Can be: `payg` and `quota-1`, `quota-10`, and `quota-50`. Learn more about the available [data metering models](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#payg-vs-quota-data-plans). + :param messaging_enabled: Whether SIMs can make, send, and receive SMS using [Commands](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_enabled: Deprecated. + :param national_roaming_enabled: Whether SIMs can roam on networks other than the home network (T-Mobile USA) in the United States. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming). + :param international_roaming: The list of services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States. Can contain: `data` and `messaging`. + :param national_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on non-home networks in the United States. The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming) for more info. + :param international_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month when roaming outside the United States. Can be up to 2TB. + :param data_limit_strategy: + + :returns: The created RatePlanInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "DataEnabled": serialize.boolean_to_string(data_enabled), + "DataLimit": data_limit, + "DataMetering": data_metering, + "MessagingEnabled": serialize.boolean_to_string(messaging_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "NationalRoamingEnabled": serialize.boolean_to_string( + national_roaming_enabled + ), + "InternationalRoaming": serialize.map( + international_roaming, lambda e: e + ), + "NationalRoamingDataLimit": national_roaming_data_limit, + "InternationalRoamingDataLimit": international_roaming_data_limit, + "DataLimitStrategy": data_limit_strategy, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.create( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RatePlanInstance(self._version, payload) + + async def create_async( + self, + unique_name: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + data_enabled: Union[bool, object] = values.unset, + data_limit: Union[int, object] = values.unset, + data_metering: Union[str, object] = values.unset, + messaging_enabled: Union[bool, object] = values.unset, + voice_enabled: Union[bool, object] = values.unset, + national_roaming_enabled: Union[bool, object] = values.unset, + international_roaming: Union[List[str], object] = values.unset, + national_roaming_data_limit: Union[int, object] = values.unset, + international_roaming_data_limit: Union[int, object] = values.unset, + data_limit_strategy: Union[ + "RatePlanInstance.DataLimitStrategy", object + ] = values.unset, + ) -> RatePlanInstance: + """ + Asynchronously create the RatePlanInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :param friendly_name: A descriptive string that you create to describe the resource. It does not have to be unique. + :param data_enabled: Whether SIMs can use GPRS/3G/4G/LTE data connectivity. + :param data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on the home network (T-Mobile USA). The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB and the default value is `1000`. + :param data_metering: The model used to meter data usage. Can be: `payg` and `quota-1`, `quota-10`, and `quota-50`. Learn more about the available [data metering models](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#payg-vs-quota-data-plans). + :param messaging_enabled: Whether SIMs can make, send, and receive SMS using [Commands](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_enabled: Deprecated. + :param national_roaming_enabled: Whether SIMs can roam on networks other than the home network (T-Mobile USA) in the United States. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming). + :param international_roaming: The list of services that SIMs capable of using GPRS/3G/4G/LTE data connectivity can use outside of the United States. Can contain: `data` and `messaging`. + :param national_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month on non-home networks in the United States. The metering period begins the day of activation and ends on the same day in the following month. Can be up to 2TB. See [national roaming](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource#national-roaming) for more info. + :param international_roaming_data_limit: The total data usage (download and upload combined) in Megabytes that the Network allows during one month when roaming outside the United States. Can be up to 2TB. + :param data_limit_strategy: + + :returns: The created RatePlanInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "DataEnabled": serialize.boolean_to_string(data_enabled), + "DataLimit": data_limit, + "DataMetering": data_metering, + "MessagingEnabled": serialize.boolean_to_string(messaging_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "NationalRoamingEnabled": serialize.boolean_to_string( + national_roaming_enabled + ), + "InternationalRoaming": serialize.map( + international_roaming, lambda e: e + ), + "NationalRoamingDataLimit": national_roaming_data_limit, + "InternationalRoamingDataLimit": international_roaming_data_limit, + "DataLimitStrategy": data_limit_strategy, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.create_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return RatePlanInstance(self._version, payload) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[RatePlanInstance]: + """ + Streams RatePlanInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[RatePlanInstance]: + """ + Asynchronously streams RatePlanInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RatePlanInstance]: + """ + Lists RatePlanInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[RatePlanInstance]: + """ + Asynchronously lists RatePlanInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RatePlanPage: + """ + Retrieve a single page of RatePlanInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RatePlanInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RatePlanPage(self._version, response) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> RatePlanPage: + """ + Asynchronously retrieve a single page of RatePlanInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of RatePlanInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return RatePlanPage(self._version, response) + + def get_page(self, target_url: str) -> RatePlanPage: + """ + Retrieve a specific page of RatePlanInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RatePlanInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RatePlanPage(self._version, response) + + async def get_page_async(self, target_url: str) -> RatePlanPage: + """ + Asynchronously retrieve a specific page of RatePlanInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RatePlanInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RatePlanPage(self._version, response) + + def get(self, sid: str) -> RatePlanContext: + """ + Constructs a RatePlanContext + + :param sid: The SID of the RatePlan resource to update. + """ + return RatePlanContext(self._version, sid=sid) + + def __call__(self, sid: str) -> RatePlanContext: + """ + Constructs a RatePlanContext + + :param sid: The SID of the RatePlan resource to update. + """ + return RatePlanContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Wireless.V1.RatePlanList>" diff --git a/twilio/rest/wireless/v1/sim/__init__.py b/twilio/rest/wireless/v1/sim/__init__.py new file mode 100644 index 0000000000..cba0eeec71 --- /dev/null +++ b/twilio/rest/wireless/v1/sim/__init__.py @@ -0,0 +1,942 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Wireless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values +from twilio.base.instance_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page +from twilio.rest.wireless.v1.sim.data_session import DataSessionList +from twilio.rest.wireless.v1.sim.usage_record import UsageRecordList + + +class SimInstance(InstanceResource): + + class ResetStatus(object): + RESETTING = "resetting" + + class Status(object): + NEW = "new" + READY = "ready" + ACTIVE = "active" + SUSPENDED = "suspended" + DEACTIVATED = "deactivated" + CANCELED = "canceled" + SCHEDULED = "scheduled" + UPDATING = "updating" + + """ + :ivar sid: The unique string that we created to identify the Sim resource. + :ivar unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the resource's `sid` in the URL to address the resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource belongs. + :ivar rate_plan_sid: The SID of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource is assigned. + :ivar friendly_name: The string that you assigned to describe the Sim resource. + :ivar iccid: The [ICCID](https://en.wikipedia.org/wiki/SIM_card#ICCID) associated with the SIM. + :ivar e_id: Deprecated. + :ivar status: + :ivar reset_status: + :ivar commands_callback_url: The URL we call using the `commands_callback_method` when the SIM originates a machine-to-machine [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :ivar commands_callback_method: The HTTP method we use to call `commands_callback_url`. Can be: `POST` or `GET`. Default is `POST`. + :ivar sms_fallback_method: Deprecated. + :ivar sms_fallback_url: Deprecated. + :ivar sms_method: Deprecated. + :ivar sms_url: Deprecated. + :ivar voice_fallback_method: Deprecated. The HTTP method we use to call `voice_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. + :ivar voice_fallback_url: Deprecated. The URL we call using the `voice_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `voice_url`. + :ivar voice_method: Deprecated. The HTTP method we use to call `voice_url`. Can be: `GET` or `POST`. Default is `POST`. + :ivar voice_url: Deprecated. The URL we call using the `voice_method` when the SIM-connected device makes a voice call. + :ivar date_created: The date and time in GMT when the resource was created specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar date_updated: The date and time in GMT when the Sim resource was last updated specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar url: The absolute URL of the resource. + :ivar links: The URLs of related subresources. + :ivar ip_address: Deprecated. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.account_sid: Optional[str] = payload.get("account_sid") + self.rate_plan_sid: Optional[str] = payload.get("rate_plan_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.iccid: Optional[str] = payload.get("iccid") + self.e_id: Optional[str] = payload.get("e_id") + self.status: Optional["SimInstance.Status"] = payload.get("status") + self.reset_status: Optional["SimInstance.ResetStatus"] = payload.get( + "reset_status" + ) + self.commands_callback_url: Optional[str] = payload.get("commands_callback_url") + self.commands_callback_method: Optional[str] = payload.get( + "commands_callback_method" + ) + self.sms_fallback_method: Optional[str] = payload.get("sms_fallback_method") + self.sms_fallback_url: Optional[str] = payload.get("sms_fallback_url") + self.sms_method: Optional[str] = payload.get("sms_method") + self.sms_url: Optional[str] = payload.get("sms_url") + self.voice_fallback_method: Optional[str] = payload.get("voice_fallback_method") + self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") + self.voice_method: Optional[str] = payload.get("voice_method") + self.voice_url: Optional[str] = payload.get("voice_url") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.ip_address: Optional[str] = payload.get("ip_address") + + self._solution = { + "sid": sid or self.sid, + } + self._context: Optional[SimContext] = None + + @property + def _proxy(self) -> "SimContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SimContext for this SimInstance + """ + if self._context is None: + self._context = SimContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the SimInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SimInstance + + + :returns: True if delete succeeds, False otherwise + """ + return await self._proxy.delete_async() + + def fetch(self) -> "SimInstance": + """ + Fetch the SimInstance + + + :returns: The fetched SimInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "SimInstance": + """ + Asynchronous coroutine to fetch the SimInstance + + + :returns: The fetched SimInstance + """ + return await self._proxy.fetch_async() + + def update( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union["SimInstance.Status", object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + reset_status: Union["SimInstance.ResetStatus", object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> "SimInstance": + """ + Update the SimInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param callback_url: The URL we should call using the `callback_url` when the SIM has finished updating. When the SIM transitions from `new` to `ready` or from any status to `deactivated`, we call this URL when the status changes to an intermediate status (`ready` or `deactivated`) and again when the status changes to its final status (`active` or `canceled`). + :param friendly_name: A descriptive string that you create to describe the Sim resource. It does not need to be unique. + :param rate_plan: The SID or unique name of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource should be assigned. + :param status: + :param commands_callback_method: The HTTP method we should use to call `commands_callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param commands_callback_url: The URL we should call using the `commands_callback_method` when the SIM sends a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_fallback_url: The URL we should call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `sms_url`. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_url: The URL we should call using the `sms_method` when the SIM-connected device sends an SMS message that is not a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_fallback_method: Deprecated. + :param voice_fallback_url: Deprecated. + :param voice_method: Deprecated. + :param voice_url: Deprecated. + :param reset_status: + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a [Subaccount](https://www.twilio.com/docs/iam/api/subaccounts) of the requesting Account. Only valid when the Sim resource's status is `new`. For more information, see the [Move SIMs between Subaccounts documentation](https://www.twilio.com/docs/iot/wireless/api/sim-resource#move-sims-between-subaccounts). + + :returns: The updated SimInstance + """ + return self._proxy.update( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + reset_status=reset_status, + account_sid=account_sid, + ) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union["SimInstance.Status", object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + reset_status: Union["SimInstance.ResetStatus", object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> "SimInstance": + """ + Asynchronous coroutine to update the SimInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param callback_url: The URL we should call using the `callback_url` when the SIM has finished updating. When the SIM transitions from `new` to `ready` or from any status to `deactivated`, we call this URL when the status changes to an intermediate status (`ready` or `deactivated`) and again when the status changes to its final status (`active` or `canceled`). + :param friendly_name: A descriptive string that you create to describe the Sim resource. It does not need to be unique. + :param rate_plan: The SID or unique name of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource should be assigned. + :param status: + :param commands_callback_method: The HTTP method we should use to call `commands_callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param commands_callback_url: The URL we should call using the `commands_callback_method` when the SIM sends a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_fallback_url: The URL we should call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `sms_url`. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_url: The URL we should call using the `sms_method` when the SIM-connected device sends an SMS message that is not a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_fallback_method: Deprecated. + :param voice_fallback_url: Deprecated. + :param voice_method: Deprecated. + :param voice_url: Deprecated. + :param reset_status: + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a [Subaccount](https://www.twilio.com/docs/iam/api/subaccounts) of the requesting Account. Only valid when the Sim resource's status is `new`. For more information, see the [Move SIMs between Subaccounts documentation](https://www.twilio.com/docs/iot/wireless/api/sim-resource#move-sims-between-subaccounts). + + :returns: The updated SimInstance + """ + return await self._proxy.update_async( + unique_name=unique_name, + callback_method=callback_method, + callback_url=callback_url, + friendly_name=friendly_name, + rate_plan=rate_plan, + status=status, + commands_callback_method=commands_callback_method, + commands_callback_url=commands_callback_url, + sms_fallback_method=sms_fallback_method, + sms_fallback_url=sms_fallback_url, + sms_method=sms_method, + sms_url=sms_url, + voice_fallback_method=voice_fallback_method, + voice_fallback_url=voice_fallback_url, + voice_method=voice_method, + voice_url=voice_url, + reset_status=reset_status, + account_sid=account_sid, + ) + + @property + def data_sessions(self) -> DataSessionList: + """ + Access the data_sessions + """ + return self._proxy.data_sessions + + @property + def usage_records(self) -> UsageRecordList: + """ + Access the usage_records + """ + return self._proxy.usage_records + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Wireless.V1.SimInstance {}>".format(context) + + +class SimContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the SimContext + + :param version: Version that contains the resource + :param sid: The SID or the `unique_name` of the Sim resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Sims/{sid}".format(**self._solution) + + self._data_sessions: Optional[DataSessionList] = None + self._usage_records: Optional[UsageRecordList] = None + + def delete(self) -> bool: + """ + Deletes the SimInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the SimInstance + + + :returns: True if delete succeeds, False otherwise + """ + + headers = values.of({}) + + return await self._version.delete_async( + method="DELETE", uri=self._uri, headers=headers + ) + + def fetch(self) -> SimInstance: + """ + Fetch the SimInstance + + + :returns: The fetched SimInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = self._version.fetch(method="GET", uri=self._uri, headers=headers) + + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + async def fetch_async(self) -> SimInstance: + """ + Asynchronous coroutine to fetch the SimInstance + + + :returns: The fetched SimInstance + """ + + headers = values.of({}) + + headers["Accept"] = "application/json" + + payload = await self._version.fetch_async( + method="GET", uri=self._uri, headers=headers + ) + + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def update( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union["SimInstance.Status", object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + reset_status: Union["SimInstance.ResetStatus", object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> SimInstance: + """ + Update the SimInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param callback_url: The URL we should call using the `callback_url` when the SIM has finished updating. When the SIM transitions from `new` to `ready` or from any status to `deactivated`, we call this URL when the status changes to an intermediate status (`ready` or `deactivated`) and again when the status changes to its final status (`active` or `canceled`). + :param friendly_name: A descriptive string that you create to describe the Sim resource. It does not need to be unique. + :param rate_plan: The SID or unique name of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource should be assigned. + :param status: + :param commands_callback_method: The HTTP method we should use to call `commands_callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param commands_callback_url: The URL we should call using the `commands_callback_method` when the SIM sends a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_fallback_url: The URL we should call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `sms_url`. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_url: The URL we should call using the `sms_method` when the SIM-connected device sends an SMS message that is not a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_fallback_method: Deprecated. + :param voice_fallback_url: Deprecated. + :param voice_method: Deprecated. + :param voice_url: Deprecated. + :param reset_status: + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a [Subaccount](https://www.twilio.com/docs/iam/api/subaccounts) of the requesting Account. Only valid when the Sim resource's status is `new`. For more information, see the [Move SIMs between Subaccounts documentation](https://www.twilio.com/docs/iot/wireless/api/sim-resource#move-sims-between-subaccounts). + + :returns: The updated SimInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "FriendlyName": friendly_name, + "RatePlan": rate_plan, + "Status": status, + "CommandsCallbackMethod": commands_callback_method, + "CommandsCallbackUrl": commands_callback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "ResetStatus": reset_status, + "AccountSid": account_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = self._version.update( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + async def update_async( + self, + unique_name: Union[str, object] = values.unset, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + status: Union["SimInstance.Status", object] = values.unset, + commands_callback_method: Union[str, object] = values.unset, + commands_callback_url: Union[str, object] = values.unset, + sms_fallback_method: Union[str, object] = values.unset, + sms_fallback_url: Union[str, object] = values.unset, + sms_method: Union[str, object] = values.unset, + sms_url: Union[str, object] = values.unset, + voice_fallback_method: Union[str, object] = values.unset, + voice_fallback_url: Union[str, object] = values.unset, + voice_method: Union[str, object] = values.unset, + voice_url: Union[str, object] = values.unset, + reset_status: Union["SimInstance.ResetStatus", object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> SimInstance: + """ + Asynchronous coroutine to update the SimInstance + + :param unique_name: An application-defined string that uniquely identifies the resource. It can be used in place of the `sid` in the URL path to address the resource. + :param callback_method: The HTTP method we should use to call `callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param callback_url: The URL we should call using the `callback_url` when the SIM has finished updating. When the SIM transitions from `new` to `ready` or from any status to `deactivated`, we call this URL when the status changes to an intermediate status (`ready` or `deactivated`) and again when the status changes to its final status (`active` or `canceled`). + :param friendly_name: A descriptive string that you create to describe the Sim resource. It does not need to be unique. + :param rate_plan: The SID or unique name of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource should be assigned. + :param status: + :param commands_callback_method: The HTTP method we should use to call `commands_callback_url`. Can be: `POST` or `GET`. The default is `POST`. + :param commands_callback_url: The URL we should call using the `commands_callback_method` when the SIM sends a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. + :param sms_fallback_method: The HTTP method we should use to call `sms_fallback_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_fallback_url: The URL we should call using the `sms_fallback_method` when an error occurs while retrieving or executing the TwiML requested from `sms_url`. + :param sms_method: The HTTP method we should use to call `sms_url`. Can be: `GET` or `POST`. Default is `POST`. + :param sms_url: The URL we should call using the `sms_method` when the SIM-connected device sends an SMS message that is not a [Command](https://www.twilio.com/docs/iot/wireless/api/command-resource). + :param voice_fallback_method: Deprecated. + :param voice_fallback_url: Deprecated. + :param voice_method: Deprecated. + :param voice_url: Deprecated. + :param reset_status: + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource should belong. The Account SID can only be that of the requesting Account or that of a [Subaccount](https://www.twilio.com/docs/iam/api/subaccounts) of the requesting Account. Only valid when the Sim resource's status is `new`. For more information, see the [Move SIMs between Subaccounts documentation](https://www.twilio.com/docs/iot/wireless/api/sim-resource#move-sims-between-subaccounts). + + :returns: The updated SimInstance + """ + + data = values.of( + { + "UniqueName": unique_name, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "FriendlyName": friendly_name, + "RatePlan": rate_plan, + "Status": status, + "CommandsCallbackMethod": commands_callback_method, + "CommandsCallbackUrl": commands_callback_url, + "SmsFallbackMethod": sms_fallback_method, + "SmsFallbackUrl": sms_fallback_url, + "SmsMethod": sms_method, + "SmsUrl": sms_url, + "VoiceFallbackMethod": voice_fallback_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceMethod": voice_method, + "VoiceUrl": voice_url, + "ResetStatus": reset_status, + "AccountSid": account_sid, + } + ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" + + headers["Accept"] = "application/json" + + payload = await self._version.update_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + return SimInstance(self._version, payload, sid=self._solution["sid"]) + + @property + def data_sessions(self) -> DataSessionList: + """ + Access the data_sessions + """ + if self._data_sessions is None: + self._data_sessions = DataSessionList( + self._version, + self._solution["sid"], + ) + return self._data_sessions + + @property + def usage_records(self) -> UsageRecordList: + """ + Access the usage_records + """ + if self._usage_records is None: + self._usage_records = UsageRecordList( + self._version, + self._solution["sid"], + ) + return self._usage_records + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Wireless.V1.SimContext {}>".format(context) + + +class SimPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SimInstance: + """ + Build an instance of SimInstance + + :param payload: Payload response from the API + """ + return SimInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Wireless.V1.SimPage>" + + +class SimList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SimList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Sims" + + def stream( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SimInstance]: + """ + Streams SimInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "SimInstance.Status" status: Only return Sim resources with this status. + :param str iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param str rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param str e_id: Deprecated. + :param str sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SimInstance]: + """ + Asynchronously streams SimInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param "SimInstance.Status" status: Only return Sim resources with this status. + :param str iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param str rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param str e_id: Deprecated. + :param str sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + page_size=limits["page_size"], + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SimInstance]: + """ + Lists SimInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "SimInstance.Status" status: Only return Sim resources with this status. + :param str iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param str rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param str e_id: Deprecated. + :param str sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SimInstance]: + """ + Asynchronously lists SimInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param "SimInstance.Status" status: Only return Sim resources with this status. + :param str iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param str rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param str e_id: Deprecated. + :param str sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + status=status, + iccid=iccid, + rate_plan=rate_plan, + e_id=e_id, + sim_registration_code=sim_registration_code, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SimPage: + """ + Retrieve a single page of SimInstance records from the API. + Request is executed immediately + + :param status: Only return Sim resources with this status. + :param iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param e_id: Deprecated. + :param sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SimInstance + """ + data = values.of( + { + "Status": status, + "Iccid": iccid, + "RatePlan": rate_plan, + "EId": e_id, + "SimRegistrationCode": sim_registration_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SimPage(self._version, response) + + async def page_async( + self, + status: Union["SimInstance.Status", object] = values.unset, + iccid: Union[str, object] = values.unset, + rate_plan: Union[str, object] = values.unset, + e_id: Union[str, object] = values.unset, + sim_registration_code: Union[str, object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> SimPage: + """ + Asynchronously retrieve a single page of SimInstance records from the API. + Request is executed immediately + + :param status: Only return Sim resources with this status. + :param iccid: Only return Sim resources with this ICCID. This will return a list with a maximum size of 1. + :param rate_plan: The SID or unique name of a [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :param e_id: Deprecated. + :param sim_registration_code: Only return Sim resources with this registration code. This will return a list with a maximum size of 1. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of SimInstance + """ + data = values.of( + { + "Status": status, + "Iccid": iccid, + "RatePlan": rate_plan, + "EId": e_id, + "SimRegistrationCode": sim_registration_code, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SimPage(self._version, response) + + def get_page(self, target_url: str) -> SimPage: + """ + Retrieve a specific page of SimInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SimInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SimPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SimPage: + """ + Asynchronously retrieve a specific page of SimInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SimInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SimPage(self._version, response) + + def get(self, sid: str) -> SimContext: + """ + Constructs a SimContext + + :param sid: The SID or the `unique_name` of the Sim resource to update. + """ + return SimContext(self._version, sid=sid) + + def __call__(self, sid: str) -> SimContext: + """ + Constructs a SimContext + + :param sid: The SID or the `unique_name` of the Sim resource to update. + """ + return SimContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Wireless.V1.SimList>" diff --git a/twilio/rest/wireless/v1/sim/data_session.py b/twilio/rest/wireless/v1/sim/data_session.py new file mode 100644 index 0000000000..b4c50d608d --- /dev/null +++ b/twilio/rest/wireless/v1/sim/data_session.py @@ -0,0 +1,327 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Wireless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import deserialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DataSessionInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the DataSession resource. + :ivar sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) that the Data Session is for. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the DataSession resource. + :ivar radio_link: The generation of wireless technology that the device was using. + :ivar operator_mcc: The 'mobile country code' is the unique ID of the home country where the Data Session took place. See: [MCC/MNC lookup](http://mcc-mnc.com/). + :ivar operator_mnc: The 'mobile network code' is the unique ID specific to the mobile operator network where the Data Session took place. + :ivar operator_country: The three letter country code representing where the device's Data Session took place. This is determined by looking up the `operator_mcc`. + :ivar operator_name: The friendly name of the mobile operator network that the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource)-connected device is attached to. This is determined by looking up the `operator_mnc`. + :ivar cell_id: The unique ID of the cellular tower that the device was attached to at the moment when the Data Session was last updated. + :ivar cell_location_estimate: An object that describes the estimated location in latitude and longitude where the device's Data Session took place. The location is derived from the `cell_id` when the Data Session was last updated. See [Cell Location Estimate Object](https://www.twilio.com/docs/iot/wireless/api/datasession-resource#cell-location-estimate-object). + :ivar packets_uploaded: The number of packets uploaded by the device between the `start` time and when the Data Session was last updated. + :ivar packets_downloaded: The number of packets downloaded by the device between the `start` time and when the Data Session was last updated. + :ivar last_updated: The date that the resource was last updated, given as GMT in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar start: The date that the Data Session started, given as GMT in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar end: The date that the record ended, given as GMT in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar imei: The 'international mobile equipment identity' is the unique ID of the device using the SIM to connect. An IMEI is a 15-digit string: 14 digits for the device identifier plus a check digit calculated using the Luhn formula. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sim_sid: str): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.radio_link: Optional[str] = payload.get("radio_link") + self.operator_mcc: Optional[str] = payload.get("operator_mcc") + self.operator_mnc: Optional[str] = payload.get("operator_mnc") + self.operator_country: Optional[str] = payload.get("operator_country") + self.operator_name: Optional[str] = payload.get("operator_name") + self.cell_id: Optional[str] = payload.get("cell_id") + self.cell_location_estimate: Optional[Dict[str, object]] = payload.get( + "cell_location_estimate" + ) + self.packets_uploaded: Optional[int] = deserialize.integer( + payload.get("packets_uploaded") + ) + self.packets_downloaded: Optional[int] = deserialize.integer( + payload.get("packets_downloaded") + ) + self.last_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("last_updated") + ) + self.start: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("start") + ) + self.end: Optional[datetime] = deserialize.iso8601_datetime(payload.get("end")) + self.imei: Optional[str] = payload.get("imei") + + self._solution = { + "sim_sid": sim_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Wireless.V1.DataSessionInstance {}>".format(context) + + +class DataSessionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> DataSessionInstance: + """ + Build an instance of DataSessionInstance + + :param payload: Payload response from the API + """ + return DataSessionInstance( + self._version, payload, sim_sid=self._solution["sim_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Wireless.V1.DataSessionPage>" + + +class DataSessionList(ListResource): + + def __init__(self, version: Version, sim_sid: str): + """ + Initialize the DataSessionList + + :param version: Version that contains the resource + :param sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) with the Data Sessions to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sim_sid": sim_sid, + } + self._uri = "/Sims/{sim_sid}/DataSessions".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[DataSessionInstance]: + """ + Streams DataSessionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[DataSessionInstance]: + """ + Asynchronously streams DataSessionInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(page_size=limits["page_size"]) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DataSessionInstance]: + """ + Lists DataSessionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[DataSessionInstance]: + """ + Asynchronously lists DataSessionInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DataSessionPage: + """ + Retrieve a single page of DataSessionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DataSessionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DataSessionPage(self._version, response, self._solution) + + async def page_async( + self, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> DataSessionPage: + """ + Asynchronously retrieve a single page of DataSessionInstance records from the API. + Request is executed immediately + + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of DataSessionInstance + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DataSessionPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> DataSessionPage: + """ + Retrieve a specific page of DataSessionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DataSessionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DataSessionPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> DataSessionPage: + """ + Asynchronously retrieve a specific page of DataSessionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DataSessionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DataSessionPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Wireless.V1.DataSessionList>" diff --git a/twilio/rest/wireless/v1/sim/usage_record.py b/twilio/rest/wireless/v1/sim/usage_record.py new file mode 100644 index 0000000000..1cd26b6c2e --- /dev/null +++ b/twilio/rest/wireless/v1/sim/usage_record.py @@ -0,0 +1,353 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Wireless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UsageRecordInstance(InstanceResource): + + class Granularity(object): + HOURLY = "hourly" + DAILY = "daily" + ALL = "all" + + """ + :ivar sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) that this Usage Record is for. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resource. + :ivar period: The time period for which the usage is reported. Contains `start` and `end` datetime values given as GMT in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar commands: An object that describes the SIM's usage of Commands during the specified period. See [Commands Usage Object](https://www.twilio.com/docs/iot/wireless/api/sim-usagerecord-resource#commands-usage-object). + :ivar data: An object that describes the SIM's data usage during the specified period. See [Data Usage Object](https://www.twilio.com/docs/iot/wireless/api/sim-usagerecord-resource#data-usage-object). + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sim_sid: str): + super().__init__(version) + + self.sim_sid: Optional[str] = payload.get("sim_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.period: Optional[Dict[str, object]] = payload.get("period") + self.commands: Optional[Dict[str, object]] = payload.get("commands") + self.data: Optional[Dict[str, object]] = payload.get("data") + + self._solution = { + "sim_sid": sim_sid, + } + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "<Twilio.Wireless.V1.UsageRecordInstance {}>".format(context) + + +class UsageRecordPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UsageRecordInstance: + """ + Build an instance of UsageRecordInstance + + :param payload: Payload response from the API + """ + return UsageRecordInstance( + self._version, payload, sim_sid=self._solution["sim_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Wireless.V1.UsageRecordPage>" + + +class UsageRecordList(ListResource): + + def __init__(self, version: Version, sim_sid: str): + """ + Initialize the UsageRecordList + + :param version: Version that contains the resource + :param sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read the usage from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sim_sid": sim_sid, + } + self._uri = "/Sims/{sim_sid}/UsageRecords".format(**self._solution) + + def stream( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UsageRecordInstance]: + """ + Streams UsageRecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param datetime start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UsageRecordInstance]: + """ + Asynchronously streams UsageRecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param datetime start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UsageRecordInstance]: + """ + Lists UsageRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param datetime start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UsageRecordInstance]: + """ + Asynchronously lists UsageRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param datetime start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UsageRecordPage: + """ + Retrieve a single page of UsageRecordInstance records from the API. + Request is executed immediately + + :param end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UsageRecordInstance + """ + data = values.of( + { + "End": serialize.iso8601_datetime(end), + "Start": serialize.iso8601_datetime(start), + "Granularity": granularity, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response, self._solution) + + async def page_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UsageRecordPage: + """ + Asynchronously retrieve a single page of UsageRecordInstance records from the API. + Request is executed immediately + + :param end: Only include usage that occurred on or before this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is the current time. + :param start: Only include usage that has occurred on or after this date, specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). The default is one month before the `end` parameter value. + :param granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. The default is `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UsageRecordInstance + """ + data = values.of( + { + "End": serialize.iso8601_datetime(end), + "Start": serialize.iso8601_datetime(start), + "Granularity": granularity, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response, self._solution) + + def get_page(self, target_url: str) -> UsageRecordPage: + """ + Retrieve a specific page of UsageRecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UsageRecordInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UsageRecordPage(self._version, response, self._solution) + + async def get_page_async(self, target_url: str) -> UsageRecordPage: + """ + Asynchronously retrieve a specific page of UsageRecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UsageRecordInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UsageRecordPage(self._version, response, self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Wireless.V1.UsageRecordList>" diff --git a/twilio/rest/wireless/v1/usage_record.py b/twilio/rest/wireless/v1/usage_record.py new file mode 100644 index 0000000000..07135cf98b --- /dev/null +++ b/twilio/rest/wireless/v1/usage_record.py @@ -0,0 +1,340 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Wireless + This is the public Twilio REST API. + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from datetime import datetime +from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator +from twilio.base import serialize, values + +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class UsageRecordInstance(InstanceResource): + + class Granularity(object): + HOURLY = "hourly" + DAILY = "daily" + ALL = "all" + + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AccountUsageRecord resource. + :ivar period: The time period for which usage is reported. Contains `start` and `end` properties that describe the period using GMT date-time values specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. + :ivar commands: An object that describes the aggregated Commands usage for all SIMs during the specified period. See [Commands Usage Object](https://www.twilio.com/docs/iot/wireless/api/account-usagerecord-resource#commands-usage-object). + :ivar data: An object that describes the aggregated Data usage for all SIMs over the period. See [Data Usage Object](https://www.twilio.com/docs/iot/wireless/api/account-usagerecord-resource#data-usage-object). + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.period: Optional[Dict[str, object]] = payload.get("period") + self.commands: Optional[Dict[str, object]] = payload.get("commands") + self.data: Optional[Dict[str, object]] = payload.get("data") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "<Twilio.Wireless.V1.UsageRecordInstance>" + + +class UsageRecordPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> UsageRecordInstance: + """ + Build an instance of UsageRecordInstance + + :param payload: Payload response from the API + """ + return UsageRecordInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Wireless.V1.UsageRecordPage>" + + +class UsageRecordList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the UsageRecordList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/UsageRecords" + + def stream( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UsageRecordInstance]: + """ + Streams UsageRecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param datetime start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UsageRecordInstance]: + """ + Asynchronously streams UsageRecordInstance records from the API as a generator stream. + This operation lazily loads records as efficiently as possible until the limit + is reached. + The results are returned as a generator, so this operation is memory efficient. + + :param datetime end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param datetime start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + end=end, start=start, granularity=granularity, page_size=limits["page_size"] + ) + + return self._version.stream_async(page, limits["limit"]) + + def list( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UsageRecordInstance]: + """ + Lists UsageRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param datetime start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return list( + self.stream( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UsageRecordInstance]: + """ + Asynchronously lists UsageRecordInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :param datetime end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param datetime start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param "UsageRecordInstance.Granularity" granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. min(limit, 1000) + + :returns: list that will contain up to limit results + """ + return [ + record + async for record in await self.stream_async( + end=end, + start=start, + granularity=granularity, + limit=limit, + page_size=page_size, + ) + ] + + def page( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UsageRecordPage: + """ + Retrieve a single page of UsageRecordInstance records from the API. + Request is executed immediately + + :param end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UsageRecordInstance + """ + data = values.of( + { + "End": serialize.iso8601_datetime(end), + "Start": serialize.iso8601_datetime(start), + "Granularity": granularity, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response) + + async def page_async( + self, + end: Union[datetime, object] = values.unset, + start: Union[datetime, object] = values.unset, + granularity: Union["UsageRecordInstance.Granularity", object] = values.unset, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UsageRecordPage: + """ + Asynchronously retrieve a single page of UsageRecordInstance records from the API. + Request is executed immediately + + :param end: Only include usage that has occurred on or before this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param start: Only include usage that has occurred on or after this date. Format is [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html). + :param granularity: How to summarize the usage by time. Can be: `daily`, `hourly`, or `all`. A value of `all` returns one Usage Record that describes the usage for the entire period. + :param page_token: PageToken provided by the API + :param page_number: Page Number, this value is simply for client state + :param page_size: Number of records to return, defaults to 50 + + :returns: Page of UsageRecordInstance + """ + data = values.of( + { + "End": serialize.iso8601_datetime(end), + "Start": serialize.iso8601_datetime(start), + "Granularity": granularity, + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UsageRecordPage(self._version, response) + + def get_page(self, target_url: str) -> UsageRecordPage: + """ + Retrieve a specific page of UsageRecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UsageRecordInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UsageRecordPage(self._version, response) + + async def get_page_async(self, target_url: str) -> UsageRecordPage: + """ + Asynchronously retrieve a specific page of UsageRecordInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UsageRecordInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UsageRecordPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "<Twilio.Wireless.V1.UsageRecordList>" diff --git a/twilio/twiml.py b/twilio/twiml.py deleted file mode 100644 index f4e6df792c..0000000000 --- a/twilio/twiml.py +++ /dev/null @@ -1,502 +0,0 @@ -""" -Make sure to check out the TwiML overview and tutorial -""" -import xml.etree.ElementTree as ET -from six import iteritems - - -class TwimlException(Exception): - pass - - -class Verb(object): - """Twilio basic verb object. - """ - GET = "GET" - POST = "POST" - nestables = None - - def __init__(self, **kwargs): - self.name = self.__class__.__name__ - self.body = None - self.verbs = [] - self.attrs = {} - - if kwargs.get("waitMethod", "GET") not in ["GET", "POST"]: - raise TwimlException("Invalid waitMethod parameter, " - "must be 'GET' or 'POST'") - - if kwargs.get("method", "GET") not in ["GET", "POST"]: - raise TwimlException("Invalid method parameter, " - "must be 'GET' or 'POST'") - - for k, v in kwargs.items(): - if k == "sender": - k = "from" - if v is not None: - self.attrs[k] = v - - def __str__(self): - return self.toxml() - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, traceback): - return False - - def toxml(self, xml_declaration=True): - """ - Return the contents of this verb as an XML string - - :param bool xml_declaration: Include the XML declaration. Defaults to - True - """ - xml = ET.tostring(self.xml()).decode('utf-8') - - if xml_declaration: - return '<?xml version="1.0" encoding="UTF-8"?>' + xml - else: - return xml - - def xml(self): - el = ET.Element(self.name) - - keys = self.attrs.keys() - keys = sorted(keys) - for a in keys: - value = self.attrs[a] - - if isinstance(value, bool): - el.set(a, str(value).lower()) - else: - el.set(a, str(value)) - - if self.body: - el.text = self.body - - for verb in self.verbs: - el.append(verb.xml()) - - return el - - def append(self, verb): - if not self.nestables or verb.name not in self.nestables: - raise TwimlException("%s is not nestable inside %s" % - (verb.name, self.name)) - self.verbs.append(verb) - return verb - - -class Response(Verb): - """Twilio response object.""" - nestables = [ - 'Say', - 'Play', - 'Gather', - 'Record', - 'Dial', - 'Redirect', - 'Pause', - 'Hangup', - 'Reject', - 'Sms', - 'Enqueue', - 'Leave' - ] - - def __init__(self, **kwargs): - """Version: Twilio API version e.g. 2008-08-01 """ - super(Response, self).__init__(**kwargs) - - def say(self, text, **kwargs): - """Return a newly created :class:`Say` verb, nested inside this - :class:`Response` """ - return self.append(Say(text, **kwargs)) - - def play(self, url, **kwargs): - """Return a newly created :class:`Play` verb, nested inside this - :class:`Response` """ - return self.append(Play(url, **kwargs)) - - def pause(self, **kwargs): - """Return a newly created :class:`Pause` verb, nested inside this - :class:`Response` """ - return self.append(Pause(**kwargs)) - - def redirect(self, url=None, **kwargs): - """Return a newly created :class:`Redirect` verb, nested inside this - :class:`Response` """ - return self.append(Redirect(url, **kwargs)) - - def hangup(self, **kwargs): - """Return a newly created :class:`Hangup` verb, nested inside this - :class:`Response` """ - return self.append(Hangup(**kwargs)) - - def reject(self, reason=None, **kwargs): - """Return a newly created :class:`Hangup` verb, nested inside this - :class:`Response` """ - return self.append(Reject(reason=reason, **kwargs)) - - def gather(self, **kwargs): - """Return a newly created :class:`Gather` verb, nested inside this - :class:`Response` """ - return self.append(Gather(**kwargs)) - - def dial(self, number=None, **kwargs): - """Return a newly created :class:`Dial` verb, nested inside this - :class:`Response` """ - return self.append(Dial(number, **kwargs)) - - def enqueue(self, name, **kwargs): - """Return a newly created :class:`Enqueue` verb, nested inside this - :class:`Response` """ - return self.append(Enqueue(name, **kwargs)) - - def leave(self, **kwargs): - """Return a newly created :class:`Leave` verb, nested inside this - :class:`Response` """ - return self.append(Leave(**kwargs)) - - def record(self, **kwargs): - """Return a newly created :class:`Record` verb, nested inside this - :class:`Response` """ - return self.append(Record(**kwargs)) - - def sms(self, msg, **kwargs): - """Return a newly created :class:`Sms` verb, nested inside this - :class:`Response` """ - return self.append(Sms(msg, **kwargs)) - - # All add* methods are deprecated - def addSay(self, *args, **kwargs): - return self.say(*args, **kwargs) - - def addPlay(self, *args, **kwargs): - return self.play(*args, **kwargs) - - def addPause(self, *args, **kwargs): - return self.pause(*args, **kwargs) - - def addRedirect(self, *args, **kwargs): - return self.redirect(*args, **kwargs) - - def addHangup(self, *args, **kwargs): - return self.hangup(*args, **kwargs) - - def addReject(self, *args, **kwargs): - return self.reject(*args, **kwargs) - - def addGather(self, *args, **kwargs): - return self.gather(*args, **kwargs) - - def addDial(self, *args, **kwargs): - return self.dial(*args, **kwargs) - - def addRecord(self, *args, **kwargs): - return self.record(*args, **kwargs) - - def addSms(self, *args, **kwargs): - return self.sms(*args, **kwargs) - - -class Say(Verb): - """The :class:`Say` verb converts text to speech that is read back to the - caller. - - :param voice: allows you to choose a male or female voice to read text - back. - - :param language: allows you pick a voice with a specific language's accent - and pronunciations. Twilio currently supports languages - 'en' (English), 'es' (Spanish), 'fr' (French), and 'de' - (German), 'en-gb' (English Great Britain"). - - :param loop: specifies how many times you'd like the text repeated. - Specifying '0' will cause the the :class:`Say` verb to loop - until the call is hung up. - """ - MAN = 'man' - WOMAN = 'woman' - - ENGLISH = 'en' - BRITISH = 'en-gb' - SPANISH = 'es' - FRENCH = 'fr' - GERMAN = 'de' - - def __init__(self, text, **kwargs): - super(Say, self).__init__(**kwargs) - self.body = text - - -class Play(Verb): - """Play an audio file at a URL - - :param url: point to af audio file. The MIME type on the file must be set - correctly. - - :param loop: specifies how many times you'd like the text repeated. - Specifying '0' will cause the the :class:`Say` verb to loop - until the call is hung up. Defaults to 1. - """ - def __init__(self, url, **kwargs): - super(Play, self).__init__(**kwargs) - self.body = url - - -class Pause(Verb): - """Pause the call - - :param length: specifies how many seconds Twilio will wait silently before - continuing on. - """ - - -class Redirect(Verb): - """Redirect call flow to another URL - - :param url: specifies the url which Twilio should query to retrieve new - TwiML. The default is the current url - - :param method: specifies the HTTP method to use when retrieving the url - """ - GET = 'GET' - POST = 'POST' - - def __init__(self, url="", **kwargs): - super(Redirect, self).__init__(**kwargs) - self.body = url - - -class Hangup(Verb): - """Hangup the call - """ - - -class Reject(Verb): - """Hangup the call - - :param reason: not sure - """ - - -class Gather(Verb): - """Gather digits from the caller's keypad - - :param action: URL to which the digits entered will be sent - :param method: submit to 'action' url using GET or POST - :param numDigits: how many digits to gather before returning - :param timeout: wait for this many seconds before returning - :param finishOnKey: key that triggers the end of caller input - """ - GET = 'GET' - POST = 'POST' - nestables = ['Say', 'Play', 'Pause'] - - def __init__(self, **kwargs): - super(Gather, self).__init__(**kwargs) - - def say(self, text, **kwargs): - return self.append(Say(text, **kwargs)) - - def play(self, url, **kwargs): - return self.append(Play(url, **kwargs)) - - def pause(self, **kwargs): - return self.append(Pause(**kwargs)) - - def addSay(self, *args, **kwargs): - return self.say(*args, **kwargs) - - def addPlay(self, *args, **kwargs): - return self.play(*args, **kwargs) - - def addPause(self, *args, **kwargs): - return self.pause(*args, **kwargs) - - -class Number(Verb): - """Specify phone number in a nested Dial element. - - :param number: phone number to dial - :param sendDigits: key to press after connecting to the number - """ - def __init__(self, number, **kwargs): - super(Number, self).__init__(**kwargs) - self.body = number - - -class Client(Verb): - """Specify a client name to call in a nested Dial element. - - :param name: Client name to connect to - """ - def __init__(self, name, **kwargs): - super(Client, self).__init__(**kwargs) - self.body = name - - -class Sms(Verb): - """ Send a Sms Message to a phone number - - :param to: whom to send message to - :param sender: whom to send message from. - :param action: url to request after the message is queued - :param method: submit to 'action' url using GET or POST - :param statusCallback: url to hit when the message is actually sent - """ - GET = 'GET' - POST = 'POST' - - def __init__(self, msg, **kwargs): - super(Sms, self).__init__(**kwargs) - self.body = msg - - -class Conference(Verb): - """Specify conference in a nested Dial element. - - :param name: friendly name of conference - :param bool muted: keep this participant muted - :param bool beep: play a beep when this participant enters/leaves - :param bool startConferenceOnEnter: start conf when this participants joins - :param bool endConferenceOnExit: end conf when this participants leaves - :param waitUrl: TwiML url that executes before conference starts - :param waitMethod: HTTP method for waitUrl GET/POST - """ - GET = 'GET' - POST = 'POST' - - def __init__(self, name, **kwargs): - super(Conference, self).__init__(**kwargs) - self.body = name - - -class Dial(Verb): - """Dial another phone number and connect it to this call - - :param action: submit the result of the dial to this URL - :param method: submit to 'action' url using GET or POST - :param int timeout: The number of seconds to waits for the called - party to answer the call - :param bool hangupOnStar: Allow the calling party to hang up on the - called party by pressing the '*' key - :param int timeLimit: The maximum duration of the Call in seconds - :param callerId: The caller ID that will appear to the called party - :param bool record: Record both legs of a call within this <Dial> - """ - GET = 'GET' - POST = 'POST' - nestables = ['Number', 'Conference', 'Client', 'Queue', 'Sip'] - - def __init__(self, number=None, **kwargs): - super(Dial, self).__init__(**kwargs) - if number and len(number.split(',')) > 1: - for n in number.split(','): - self.append(Number(n.strip())) - else: - self.body = number - - def client(self, name, **kwargs): - return self.append(Client(name, **kwargs)) - - def number(self, number, **kwargs): - return self.append(Number(number, **kwargs)) - - def conference(self, name, **kwargs): - return self.append(Conference(name, **kwargs)) - - def queue(self, name, **kwargs): - return self.append(Queue(name, **kwargs)) - - def sip(self, sip_address=None, **kwargs): - return self.append(Sip(sip_address, **kwargs)) - - def addNumber(self, *args, **kwargs): - return self.number(*args, **kwargs) - - def addConference(self, *args, **kwargs): - return self.conference(*args, **kwargs) - - -class Queue(Verb): - """Specify queue in a nested Dial element. - - :param name: friendly name for the queue - :param url: url to a twiml document that executes after a call is dequeued - and before the call is connected - :param method: HTTP method for url GET/POST - """ - GET = 'GET' - POST = 'POST' - - def __init__(self, name, **kwargs): - super(Queue, self).__init__(**kwargs) - self.body = name - - -class Enqueue(Verb): - """Enqueue the call into a specific queue. - - :param name: friendly name for the queue - :param action: url to a twiml document that executes when the call - leaves the queue. When dequeued via a <Dial> verb, - this url is executed after the bridged parties disconnect - :param method: HTTP method for action GET/POST - :param wait_url: url to a twiml document that executes - while the call is on the queue - :param wait_url_method: HTTP method for wait_url GET/POST - """ - GET = 'GET' - POST = 'POST' - - def __init__(self, name, **kwargs): - super(Enqueue, self).__init__(**kwargs) - self.body = name - - -class Leave(Verb): - """Signals the call to leave its queue - """ - GET = 'GET' - POST = 'POST' - - -class Record(Verb): - """Record audio from caller - - :param action: submit the result of the dial to this URL - :param method: submit to 'action' url using GET or POST - :param maxLength: maximum number of seconds to record - :param timeout: seconds of silence before considering the recording done - """ - GET = 'GET' - POST = 'POST' - - -class Sip(Verb): - """Dial out to a SIP endpoint - - :param url: call screening URL none - :param method: call screening method POST - :param username: Username for SIP authentication - :param password: Password for SIP authentication - """ - nestables = ['Headers', 'Uri'] - - def __init__(self, sip_address=None, **kwargs): - super(Sip, self).__init__(**kwargs) - if sip_address: - self.body = sip_address - - def uri(self, uri, **kwargs): - return self.append(Uri(uri, **kwargs)) - - -class Uri(Verb): - """A uniform resource indentifier""" - def __init__(self, uri, **kwargs): - super(Uri, self).__init__(**kwargs) - self.body = uri diff --git a/twilio/twiml/__init__.py b/twilio/twiml/__init__.py new file mode 100644 index 0000000000..70a4df8309 --- /dev/null +++ b/twilio/twiml/__init__.py @@ -0,0 +1,140 @@ +import json +import re +import xml.etree.ElementTree as ET + + +def lower_camel(string): + if not string or "_" not in string: + return string + + result = "".join([x.title() for x in string.split("_")]) + return result[0].lower() + result[1:] + + +def format_language(language): + """ + Attempt to format language parameter as 'ww-WW'. + + :param string language: language parameter + """ + if not language: + return language + + if not re.match("^[a-zA-Z]{2}[_-][a-zA-Z]{2}$", language): + raise TwiMLException("Invalid value for language parameter.") + + return language[0:2].lower() + "-" + language[3:5].upper() + + +class TwiMLException(Exception): + pass + + +class TwiML(object): + MAP = { + "from_": "from", + "xml_lang": "xml:lang", + "interpret_as": "interpret-as", + "for_": "for", + "break_": "break", + } + + def __init__(self, **kwargs): + self.name = self.__class__.__name__ + self.value = None + self.verbs = [] + self.attrs = {} + + for k, v in kwargs.items(): + if v is not None: + self.attrs[lower_camel(self.MAP.get(k, k))] = v + + def __str__(self): + return self.to_xml() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + return False + + def to_xml(self, xml_declaration=True): + """ + Return the contents of this verb as an XML string + + :param bool xml_declaration: Include the XML declaration. Defaults to True + """ + xml = ET.tostring(self.xml(), encoding="utf-8").decode("utf-8") + return ( + '<?xml version="1.0" encoding="UTF-8"?>{}'.format(xml) + if xml_declaration + else xml + ) + + def append(self, verb): + """ + Add a TwiML doc + + :param verb: TwiML Document + + :returns: self + """ + self.nest(verb) + return self + + def nest(self, verb): + """ + Add a TwiML doc. Unlike `append()`, this returns the created verb. + + :param verb: TwiML Document + + :returns: the TwiML verb + """ + if not isinstance(verb, TwiML) and not isinstance(verb, str): + raise TwiMLException("Only nesting of TwiML and strings are allowed") + + self.verbs.append(verb) + return verb + + def xml(self): + el = ET.Element(self.name) + + keys = self.attrs.keys() + keys = sorted(keys) + for a in keys: + value = self.attrs[a] + + if isinstance(value, bool): + el.set(a, str(value).lower()) + else: + el.set(a, str(value)) + + if self.value: + if isinstance(self.value, dict): + self.value = json.dumps(self.value) + + el.text = self.value + + last_child = None + + for verb in self.verbs: + if isinstance(verb, str): + if last_child is not None: + last_child.tail = verb + else: + el.text = verb + else: + last_child = verb.xml() + el.append(last_child) + + return el + + def add_child(self, name, value=None, **kwargs): + return self.nest(GenericNode(name, value, **kwargs)) + + +class GenericNode(TwiML): + def __init__(self, name, value, **kwargs): + super(GenericNode, self).__init__(**kwargs) + self.name = name + self.value = value diff --git a/twilio/twiml/fax_response.py b/twilio/twiml/fax_response.py new file mode 100644 index 0000000000..89233bd407 --- /dev/null +++ b/twilio/twiml/fax_response.py @@ -0,0 +1,59 @@ +# coding=utf-8 +r""" +This code was generated by +\ / _ _ _| _ _ + | (_)\/(_)(_|\/| |(/_ v1.0.0 + / / +""" + +from twilio.twiml import ( + TwiML, +) + + +class FaxResponse(TwiML): + """<Response> TwiML for Faxes""" + + def __init__(self, **kwargs): + super(FaxResponse, self).__init__(**kwargs) + self.name = "Response" + + def receive( + self, + action=None, + method=None, + media_type=None, + page_size=None, + store_media=None, + **kwargs + ): + """ + Create a <Receive> element + + :param action: Receive action URL + :param method: Receive action URL method + :param media_type: The media type used to store media in the fax media store + :param page_size: What size to interpret received pages as + :param store_media: Whether or not to store received media in the fax media store + :param kwargs: additional attributes + + :returns: <Receive> element + """ + return self.nest( + Receive( + action=action, + method=method, + media_type=media_type, + page_size=page_size, + store_media=store_media, + **kwargs + ) + ) + + +class Receive(TwiML): + """<Receive> TwiML Verb""" + + def __init__(self, **kwargs): + super(Receive, self).__init__(**kwargs) + self.name = "Receive" diff --git a/twilio/twiml/messaging_response.py b/twilio/twiml/messaging_response.py new file mode 100644 index 0000000000..ec36c74c06 --- /dev/null +++ b/twilio/twiml/messaging_response.py @@ -0,0 +1,125 @@ +# coding=utf-8 +r""" +This code was generated by +\ / _ _ _| _ _ + | (_)\/(_)(_|\/| |(/_ v1.0.0 + / / +""" + +from twilio.twiml import ( + TwiML, +) + + +class MessagingResponse(TwiML): + """<Response> TwiML for Messages""" + + def __init__(self, **kwargs): + super(MessagingResponse, self).__init__(**kwargs) + self.name = "Response" + + def message( + self, + body=None, + to=None, + from_=None, + action=None, + method=None, + status_callback=None, + **kwargs + ): + """ + Create a <Message> element + + :param body: Message Body + :param to: Phone Number to send Message to + :param from: Phone Number to send Message from + :param action: A URL specifying where Twilio should send status callbacks for the created outbound message. + :param method: Action URL Method + :param status_callback: Status callback URL. Deprecated in favor of action. + :param kwargs: additional attributes + + :returns: <Message> element + """ + return self.nest( + Message( + body=body, + to=to, + from_=from_, + action=action, + method=method, + status_callback=status_callback, + **kwargs + ) + ) + + def redirect(self, url, method=None, **kwargs): + """ + Create a <Redirect> element + + :param url: Redirect URL + :param method: Redirect URL method + :param kwargs: additional attributes + + :returns: <Redirect> element + """ + return self.nest(Redirect(url, method=method, **kwargs)) + + +class Redirect(TwiML): + """<Redirect> TwiML Verb""" + + def __init__(self, url, **kwargs): + super(Redirect, self).__init__(**kwargs) + self.name = "Redirect" + self.value = url + + +class Message(TwiML): + """<Message> TwiML Verb""" + + def __init__(self, body=None, **kwargs): + super(Message, self).__init__(**kwargs) + self.name = "Message" + if body: + self.value = body + + def body(self, message, **kwargs): + """ + Create a <Body> element + + :param message: Message Body + :param kwargs: additional attributes + + :returns: <Body> element + """ + return self.nest(Body(message, **kwargs)) + + def media(self, url, **kwargs): + """ + Create a <Media> element + + :param url: Media URL + :param kwargs: additional attributes + + :returns: <Media> element + """ + return self.nest(Media(url, **kwargs)) + + +class Media(TwiML): + """<Media> TwiML Noun""" + + def __init__(self, url, **kwargs): + super(Media, self).__init__(**kwargs) + self.name = "Media" + self.value = url + + +class Body(TwiML): + """<Body> TwiML Noun""" + + def __init__(self, message, **kwargs): + super(Body, self).__init__(**kwargs) + self.name = "Body" + self.value = message diff --git a/twilio/twiml/voice_response.py b/twilio/twiml/voice_response.py new file mode 100644 index 0000000000..18078b90a3 --- /dev/null +++ b/twilio/twiml/voice_response.py @@ -0,0 +1,3065 @@ +# coding=utf-8 +r""" +This code was generated by +\ / _ _ _| _ _ + | (_)\/(_)(_|\/| |(/_ v1.0.0 + / / +""" + +from twilio.twiml import ( + TwiML, +) + + +class VoiceResponse(TwiML): + """<Response> TwiML for Voice""" + + def __init__(self, **kwargs): + super(VoiceResponse, self).__init__(**kwargs) + self.name = "Response" + + def connect(self, action=None, method=None, **kwargs): + """ + Create a <Connect> element + + :param action: Action URL + :param method: Action URL method + :param kwargs: additional attributes + + :returns: <Connect> element + """ + return self.nest(Connect(action=action, method=method, **kwargs)) + + def dial( + self, + number=None, + action=None, + method=None, + timeout=None, + hangup_on_star=None, + time_limit=None, + caller_id=None, + record=None, + trim=None, + recording_status_callback=None, + recording_status_callback_method=None, + recording_status_callback_event=None, + answer_on_bridge=None, + ring_tone=None, + recording_track=None, + sequential=None, + refer_url=None, + refer_method=None, + events=None, + **kwargs + ): + """ + Create a <Dial> element + + :param number: Phone number to dial + :param action: Action URL + :param method: Action URL method + :param timeout: Time to wait for answer + :param hangup_on_star: Hangup call on star press + :param time_limit: Max time length + :param caller_id: Caller ID to display + :param record: Record the call + :param trim: Trim the recording + :param recording_status_callback: Recording status callback URL + :param recording_status_callback_method: Recording status callback URL method + :param recording_status_callback_event: Recording status callback events + :param answer_on_bridge: Preserve the ringing behavior of the inbound call until the Dialed call picks up + :param ring_tone: Ringtone allows you to override the ringback tone that Twilio will play back to the caller while executing the Dial + :param recording_track: To indicate which audio track should be recorded + :param sequential: Used to determine if child TwiML nouns should be dialed in order, one after the other (sequential) or dial all at once (parallel). Default is false, parallel + :param refer_url: Webhook that will receive future SIP REFER requests + :param refer_method: The HTTP method to use for the refer Webhook + :param events: Subscription to events + :param kwargs: additional attributes + + :returns: <Dial> element + """ + return self.nest( + Dial( + number=number, + action=action, + method=method, + timeout=timeout, + hangup_on_star=hangup_on_star, + time_limit=time_limit, + caller_id=caller_id, + record=record, + trim=trim, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + recording_status_callback_event=recording_status_callback_event, + answer_on_bridge=answer_on_bridge, + ring_tone=ring_tone, + recording_track=recording_track, + sequential=sequential, + refer_url=refer_url, + refer_method=refer_method, + events=events, + **kwargs + ) + ) + + def echo(self, **kwargs): + """ + Create a <Echo> element + + :param kwargs: additional attributes + + :returns: <Echo> element + """ + return self.nest(Echo(**kwargs)) + + def enqueue( + self, + name=None, + action=None, + max_queue_size=None, + method=None, + wait_url=None, + wait_url_method=None, + workflow_sid=None, + **kwargs + ): + """ + Create a <Enqueue> element + + :param name: Friendly name + :param action: Action URL + :param max_queue_size: Maximum size of queue + :param method: Action URL method + :param wait_url: Wait URL + :param wait_url_method: Wait URL method + :param workflow_sid: TaskRouter Workflow SID + :param kwargs: additional attributes + + :returns: <Enqueue> element + """ + return self.nest( + Enqueue( + name=name, + action=action, + max_queue_size=max_queue_size, + method=method, + wait_url=wait_url, + wait_url_method=wait_url_method, + workflow_sid=workflow_sid, + **kwargs + ) + ) + + def gather( + self, + input=None, + action=None, + method=None, + timeout=None, + speech_timeout=None, + max_speech_time=None, + profanity_filter=None, + finish_on_key=None, + num_digits=None, + partial_result_callback=None, + partial_result_callback_method=None, + language=None, + hints=None, + barge_in=None, + debug=None, + action_on_empty_result=None, + speech_model=None, + enhanced=None, + **kwargs + ): + """ + Create a <Gather> element + + :param input: Input type Twilio should accept + :param action: Action URL + :param method: Action URL method + :param timeout: Time to wait to gather input + :param speech_timeout: Time to wait to gather speech input and it should be either auto or a positive integer. + :param max_speech_time: Max allowed time for speech input + :param profanity_filter: Profanity Filter on speech + :param finish_on_key: Finish gather on key + :param num_digits: Number of digits to collect + :param partial_result_callback: Partial result callback URL + :param partial_result_callback_method: Partial result callback URL method + :param language: Language to use + :param hints: Speech recognition hints + :param barge_in: Stop playing media upon speech + :param debug: Allow debug for gather + :param action_on_empty_result: Force webhook to the action URL event if there is no input + :param speech_model: Specify the model that is best suited for your use case + :param enhanced: Use enhanced speech model + :param kwargs: additional attributes + + :returns: <Gather> element + """ + return self.nest( + Gather( + input=input, + action=action, + method=method, + timeout=timeout, + speech_timeout=speech_timeout, + max_speech_time=max_speech_time, + profanity_filter=profanity_filter, + finish_on_key=finish_on_key, + num_digits=num_digits, + partial_result_callback=partial_result_callback, + partial_result_callback_method=partial_result_callback_method, + language=language, + hints=hints, + barge_in=barge_in, + debug=debug, + action_on_empty_result=action_on_empty_result, + speech_model=speech_model, + enhanced=enhanced, + **kwargs + ) + ) + + def hangup(self, **kwargs): + """ + Create a <Hangup> element + + :param kwargs: additional attributes + + :returns: <Hangup> element + """ + return self.nest(Hangup(**kwargs)) + + def leave(self, **kwargs): + """ + Create a <Leave> element + + :param kwargs: additional attributes + + :returns: <Leave> element + """ + return self.nest(Leave(**kwargs)) + + def pause(self, length=None, **kwargs): + """ + Create a <Pause> element + + :param length: Length in seconds to pause + :param kwargs: additional attributes + + :returns: <Pause> element + """ + return self.nest(Pause(length=length, **kwargs)) + + def play(self, url=None, loop=None, digits=None, **kwargs): + """ + Create a <Play> element + + :param url: Media URL + :param loop: Times to loop media + :param digits: Play DTMF tones for digits + :param kwargs: additional attributes + + :returns: <Play> element + """ + return self.nest(Play(url=url, loop=loop, digits=digits, **kwargs)) + + def queue( + self, + name, + url=None, + method=None, + reservation_sid=None, + post_work_activity_sid=None, + **kwargs + ): + """ + Create a <Queue> element + + :param name: Queue name + :param url: Action URL + :param method: Action URL method + :param reservation_sid: TaskRouter Reservation SID + :param post_work_activity_sid: TaskRouter Activity SID + :param kwargs: additional attributes + + :returns: <Queue> element + """ + return self.nest( + Queue( + name, + url=url, + method=method, + reservation_sid=reservation_sid, + post_work_activity_sid=post_work_activity_sid, + **kwargs + ) + ) + + def record( + self, + action=None, + method=None, + timeout=None, + finish_on_key=None, + max_length=None, + play_beep=None, + trim=None, + recording_status_callback=None, + recording_status_callback_method=None, + recording_status_callback_event=None, + transcribe=None, + transcribe_callback=None, + **kwargs + ): + """ + Create a <Record> element + + :param action: Action URL + :param method: Action URL method + :param timeout: Timeout to begin recording + :param finish_on_key: Finish recording on key + :param max_length: Max time to record in seconds + :param play_beep: Play beep + :param trim: Trim the recording + :param recording_status_callback: Status callback URL + :param recording_status_callback_method: Status callback URL method + :param recording_status_callback_event: Recording status callback events + :param transcribe: Transcribe the recording + :param transcribe_callback: Transcribe callback URL + :param kwargs: additional attributes + + :returns: <Record> element + """ + return self.nest( + Record( + action=action, + method=method, + timeout=timeout, + finish_on_key=finish_on_key, + max_length=max_length, + play_beep=play_beep, + trim=trim, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + recording_status_callback_event=recording_status_callback_event, + transcribe=transcribe, + transcribe_callback=transcribe_callback, + **kwargs + ) + ) + + def redirect(self, url, method=None, **kwargs): + """ + Create a <Redirect> element + + :param url: Redirect URL + :param method: Redirect URL method + :param kwargs: additional attributes + + :returns: <Redirect> element + """ + return self.nest(Redirect(url, method=method, **kwargs)) + + def reject(self, reason=None, **kwargs): + """ + Create a <Reject> element + + :param reason: Rejection reason + :param kwargs: additional attributes + + :returns: <Reject> element + """ + return self.nest(Reject(reason=reason, **kwargs)) + + def say(self, message=None, voice=None, loop=None, language=None, **kwargs): + """ + Create a <Say> element + + :param message: Message to say + :param voice: Voice to use + :param loop: Times to loop message + :param language: Message language + :param kwargs: additional attributes + + :returns: <Say> element + """ + return self.nest( + Say(message=message, voice=voice, loop=loop, language=language, **kwargs) + ) + + def sms( + self, + message, + to=None, + from_=None, + action=None, + method=None, + status_callback=None, + **kwargs + ): + """ + Create a <Sms> element + + :param message: Message body + :param to: Number to send message to + :param from: Number to send message from + :param action: Action URL + :param method: Action URL method + :param status_callback: Status callback URL + :param kwargs: additional attributes + + :returns: <Sms> element + """ + return self.nest( + Sms( + message, + to=to, + from_=from_, + action=action, + method=method, + status_callback=status_callback, + **kwargs + ) + ) + + def pay( + self, + input=None, + action=None, + bank_account_type=None, + status_callback=None, + status_callback_method=None, + timeout=None, + max_attempts=None, + security_code=None, + postal_code=None, + min_postal_code_length=None, + payment_connector=None, + payment_method=None, + token_type=None, + charge_amount=None, + currency=None, + description=None, + valid_card_types=None, + language=None, + **kwargs + ): + """ + Create a <Pay> element + + :param input: Input type Twilio should accept + :param action: Action URL + :param bank_account_type: Bank account type for ach transactions. If set, payment method attribute must be provided and value should be set to ach-debit. defaults to consumer-checking + :param status_callback: Status callback URL + :param status_callback_method: Status callback method + :param timeout: Time to wait to gather input + :param max_attempts: Maximum number of allowed retries when gathering input + :param security_code: Prompt for security code + :param postal_code: Prompt for postal code and it should be true/false or default postal code + :param min_postal_code_length: Prompt for minimum postal code length + :param payment_connector: Unique name for payment connector + :param payment_method: Payment method to be used. defaults to credit-card + :param token_type: Type of token + :param charge_amount: Amount to process. If value is greater than 0 then make the payment else create a payment token + :param currency: Currency of the amount attribute + :param description: Details regarding the payment + :param valid_card_types: Comma separated accepted card types + :param language: Language to use + :param kwargs: additional attributes + + :returns: <Pay> element + """ + return self.nest( + Pay( + input=input, + action=action, + bank_account_type=bank_account_type, + status_callback=status_callback, + status_callback_method=status_callback_method, + timeout=timeout, + max_attempts=max_attempts, + security_code=security_code, + postal_code=postal_code, + min_postal_code_length=min_postal_code_length, + payment_connector=payment_connector, + payment_method=payment_method, + token_type=token_type, + charge_amount=charge_amount, + currency=currency, + description=description, + valid_card_types=valid_card_types, + language=language, + **kwargs + ) + ) + + def prompt( + self, + for_=None, + error_type=None, + card_type=None, + attempt=None, + require_matching_inputs=None, + **kwargs + ): + """ + Create a <Prompt> element + + :param for_: Name of the payment source data element + :param error_type: Type of error + :param card_type: Type of the credit card + :param attempt: Current attempt count + :param require_matching_inputs: Require customer to input requested information twice and verify matching. + :param kwargs: additional attributes + + :returns: <Prompt> element + """ + return self.nest( + Prompt( + for_=for_, + error_type=error_type, + card_type=card_type, + attempt=attempt, + require_matching_inputs=require_matching_inputs, + **kwargs + ) + ) + + def start(self, action=None, method=None, **kwargs): + """ + Create a <Start> element + + :param action: Action URL + :param method: Action URL method + :param kwargs: additional attributes + + :returns: <Start> element + """ + return self.nest(Start(action=action, method=method, **kwargs)) + + def stop(self, **kwargs): + """ + Create a <Stop> element + + :param kwargs: additional attributes + + :returns: <Stop> element + """ + return self.nest(Stop(**kwargs)) + + def refer(self, action=None, method=None, **kwargs): + """ + Create a <Refer> element + + :param action: Action URL + :param method: Action URL method + :param kwargs: additional attributes + + :returns: <Refer> element + """ + return self.nest(Refer(action=action, method=method, **kwargs)) + + +class Refer(TwiML): + """<Refer> TwiML Verb""" + + def __init__(self, **kwargs): + super(Refer, self).__init__(**kwargs) + self.name = "Refer" + + def sip(self, sip_url, **kwargs): + """ + Create a <Sip> element + + :param sip_url: SIP URL + :param kwargs: additional attributes + + :returns: <Sip> element + """ + return self.nest(ReferSip(sip_url, **kwargs)) + + +class ReferSip(TwiML): + """<Sip> TwiML Noun used in <Refer>""" + + def __init__(self, sip_url, **kwargs): + super(ReferSip, self).__init__(**kwargs) + self.name = "Sip" + self.value = sip_url + + +class Stop(TwiML): + """<Stop> TwiML Verb""" + + def __init__(self, **kwargs): + super(Stop, self).__init__(**kwargs) + self.name = "Stop" + + def stream( + self, + name=None, + connector_name=None, + url=None, + track=None, + status_callback=None, + status_callback_method=None, + **kwargs + ): + """ + Create a <Stream> element + + :param name: Friendly name given to the Stream + :param connector_name: Unique name for Stream Connector + :param url: URL of the remote service where the Stream is routed + :param track: Track to be streamed to remote service + :param status_callback: Status Callback URL + :param status_callback_method: Status Callback URL method + :param kwargs: additional attributes + + :returns: <Stream> element + """ + return self.nest( + Stream( + name=name, + connector_name=connector_name, + url=url, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + **kwargs + ) + ) + + def siprec( + self, + name=None, + connector_name=None, + track=None, + status_callback=None, + status_callback_method=None, + **kwargs + ): + """ + Create a <Siprec> element + + :param name: Friendly name given to SIPREC + :param connector_name: Unique name for Connector + :param track: Track to be streamed to remote service + :param status_callback: Status Callback URL + :param status_callback_method: Status Callback URL method + :param kwargs: additional attributes + + :returns: <Siprec> element + """ + return self.nest( + Siprec( + name=name, + connector_name=connector_name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + **kwargs + ) + ) + + def transcription( + self, + name=None, + track=None, + status_callback_url=None, + status_callback_method=None, + inbound_track_label=None, + outbound_track_label=None, + partial_results=None, + language_code=None, + transcription_engine=None, + profanity_filter=None, + speech_model=None, + hints=None, + enable_automatic_punctuation=None, + intelligence_service=None, + **kwargs + ): + """ + Create a <Transcription> element + + :param name: Friendly name given to the Transcription + :param track: Track to be analyze by the provider + :param status_callback_url: Status Callback URL + :param status_callback_method: Status Callback URL method + :param inbound_track_label: Friendly name given to the Inbound Track + :param outbound_track_label: Friendly name given to the Outbound Track Label + :param partial_results: Indicates if partial results are going to be send to the customer + :param language_code: Language Code used by the transcription engine + :param transcription_engine: Transcription Engine to be used + :param profanity_filter: Enable Profanity Filter + :param speech_model: Speech Model used by the transcription engine + :param hints: Hints to be provided to the transcription engine + :param enable_automatic_punctuation: Enable Automatic Punctuation + :param intelligence_service: The SID or the unique name of the Intelligence Service to be used + :param kwargs: additional attributes + + :returns: <Transcription> element + """ + return self.nest( + Transcription( + name=name, + track=track, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + inbound_track_label=inbound_track_label, + outbound_track_label=outbound_track_label, + partial_results=partial_results, + language_code=language_code, + transcription_engine=transcription_engine, + profanity_filter=profanity_filter, + speech_model=speech_model, + hints=hints, + enable_automatic_punctuation=enable_automatic_punctuation, + intelligence_service=intelligence_service, + **kwargs + ) + ) + + +class Transcription(TwiML): + """<Transcription> TwiML Noun""" + + def __init__(self, **kwargs): + super(Transcription, self).__init__(**kwargs) + self.name = "Transcription" + + def config(self, name=None, value=None, **kwargs): + """ + Create a <Config> element + + :param name: The name of the custom config + :param value: The value of the custom config + :param kwargs: additional attributes + + :returns: <Config> element + """ + return self.nest(Config(name=name, value=value, **kwargs)) + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a <Parameter> element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: <Parameter> element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Parameter(TwiML): + """<Parameter> TwiML Noun""" + + def __init__(self, **kwargs): + super(Parameter, self).__init__(**kwargs) + self.name = "Parameter" + + +class Config(TwiML): + """<Config> TwiML Noun""" + + def __init__(self, **kwargs): + super(Config, self).__init__(**kwargs) + self.name = "Config" + + +class Siprec(TwiML): + """<Siprec> TwiML Noun""" + + def __init__(self, **kwargs): + super(Siprec, self).__init__(**kwargs) + self.name = "Siprec" + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a <Parameter> element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: <Parameter> element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Stream(TwiML): + """<Stream> TwiML Noun""" + + def __init__(self, **kwargs): + super(Stream, self).__init__(**kwargs) + self.name = "Stream" + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a <Parameter> element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: <Parameter> element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Start(TwiML): + """<Start> TwiML Verb""" + + def __init__(self, **kwargs): + super(Start, self).__init__(**kwargs) + self.name = "Start" + + def stream( + self, + name=None, + connector_name=None, + url=None, + track=None, + status_callback=None, + status_callback_method=None, + **kwargs + ): + """ + Create a <Stream> element + + :param name: Friendly name given to the Stream + :param connector_name: Unique name for Stream Connector + :param url: URL of the remote service where the Stream is routed + :param track: Track to be streamed to remote service + :param status_callback: Status Callback URL + :param status_callback_method: Status Callback URL method + :param kwargs: additional attributes + + :returns: <Stream> element + """ + return self.nest( + Stream( + name=name, + connector_name=connector_name, + url=url, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + **kwargs + ) + ) + + def siprec( + self, + name=None, + connector_name=None, + track=None, + status_callback=None, + status_callback_method=None, + **kwargs + ): + """ + Create a <Siprec> element + + :param name: Friendly name given to SIPREC + :param connector_name: Unique name for Connector + :param track: Track to be streamed to remote service + :param status_callback: Status Callback URL + :param status_callback_method: Status Callback URL method + :param kwargs: additional attributes + + :returns: <Siprec> element + """ + return self.nest( + Siprec( + name=name, + connector_name=connector_name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + **kwargs + ) + ) + + def transcription( + self, + name=None, + track=None, + status_callback_url=None, + status_callback_method=None, + inbound_track_label=None, + outbound_track_label=None, + partial_results=None, + language_code=None, + transcription_engine=None, + profanity_filter=None, + speech_model=None, + hints=None, + enable_automatic_punctuation=None, + intelligence_service=None, + **kwargs + ): + """ + Create a <Transcription> element + + :param name: Friendly name given to the Transcription + :param track: Track to be analyze by the provider + :param status_callback_url: Status Callback URL + :param status_callback_method: Status Callback URL method + :param inbound_track_label: Friendly name given to the Inbound Track + :param outbound_track_label: Friendly name given to the Outbound Track Label + :param partial_results: Indicates if partial results are going to be send to the customer + :param language_code: Language Code used by the transcription engine + :param transcription_engine: Transcription Engine to be used + :param profanity_filter: Enable Profanity Filter + :param speech_model: Speech Model used by the transcription engine + :param hints: Hints to be provided to the transcription engine + :param enable_automatic_punctuation: Enable Automatic Punctuation + :param intelligence_service: The SID or the unique name of the Intelligence Service to be used + :param kwargs: additional attributes + + :returns: <Transcription> element + """ + return self.nest( + Transcription( + name=name, + track=track, + status_callback_url=status_callback_url, + status_callback_method=status_callback_method, + inbound_track_label=inbound_track_label, + outbound_track_label=outbound_track_label, + partial_results=partial_results, + language_code=language_code, + transcription_engine=transcription_engine, + profanity_filter=profanity_filter, + speech_model=speech_model, + hints=hints, + enable_automatic_punctuation=enable_automatic_punctuation, + intelligence_service=intelligence_service, + **kwargs + ) + ) + + +class Prompt(TwiML): + """<Prompt> Twiml Verb""" + + def __init__(self, **kwargs): + super(Prompt, self).__init__(**kwargs) + self.name = "Prompt" + + def say(self, message=None, voice=None, loop=None, language=None, **kwargs): + """ + Create a <Say> element + + :param message: Message to say + :param voice: Voice to use + :param loop: Times to loop message + :param language: Message language + :param kwargs: additional attributes + + :returns: <Say> element + """ + return self.nest( + Say(message=message, voice=voice, loop=loop, language=language, **kwargs) + ) + + def play(self, url=None, loop=None, digits=None, **kwargs): + """ + Create a <Play> element + + :param url: Media URL + :param loop: Times to loop media + :param digits: Play DTMF tones for digits + :param kwargs: additional attributes + + :returns: <Play> element + """ + return self.nest(Play(url=url, loop=loop, digits=digits, **kwargs)) + + def pause(self, length=None, **kwargs): + """ + Create a <Pause> element + + :param length: Length in seconds to pause + :param kwargs: additional attributes + + :returns: <Pause> element + """ + return self.nest(Pause(length=length, **kwargs)) + + +class Pause(TwiML): + """<Pause> TwiML Verb""" + + def __init__(self, **kwargs): + super(Pause, self).__init__(**kwargs) + self.name = "Pause" + + +class Play(TwiML): + """<Play> TwiML Verb""" + + def __init__(self, url=None, **kwargs): + super(Play, self).__init__(**kwargs) + self.name = "Play" + if url: + self.value = url + + +class Say(TwiML): + """<Say> TwiML Verb""" + + def __init__(self, message=None, **kwargs): + super(Say, self).__init__(**kwargs) + self.name = "Say" + if message: + self.value = message + + def break_(self, strength=None, time=None, **kwargs): + """ + Create a <Break> element + + :param strength: Set a pause based on strength + :param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms + :param kwargs: additional attributes + + :returns: <Break> element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a <Emphasis> element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: <Emphasis> element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a <Lang> element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: <Lang> element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def p(self, words=None, **kwargs): + """ + Create a <P> element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns: <P> element + """ + return self.nest(SsmlP(words=words, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a <Phoneme> element + + :param words: Words to speak + :param alphabet: Specify the phonetic alphabet + :param ph: Specifiy the phonetic symbols for pronunciation + :param kwargs: additional attributes + + :returns: <Phoneme> element + """ + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) + + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): + """ + Create a <Prosody> element + + :param words: Words to speak + :param volume: Specify the volume, available values: default, silent, x-soft, soft, medium, loud, x-loud, +ndB, -ndB + :param rate: Specify the rate, available values: x-slow, slow, medium, fast, x-fast, n% + :param pitch: Specify the pitch, available values: default, x-low, low, medium, high, x-high, +n%, -n% + :param kwargs: additional attributes + + :returns: <Prosody> element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def s(self, words=None, **kwargs): + """ + Create a <S> element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns: <S> element + """ + return self.nest(SsmlS(words=words, **kwargs)) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a <Say-As> element + + :param words: Words to be interpreted + :param interpret-as: Specify the type of words are spoken + :param format: Specify the format of the date when interpret-as is set to date + :param kwargs: additional attributes + + :returns: <Say-As> element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a <Sub> element + + :param words: Words to be substituted + :param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation + :param kwargs: additional attributes + + :returns: <Sub> element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a <W> element + + :param words: Words to speak + :param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning + :param kwargs: additional attributes + + :returns: <W> element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlW(TwiML): + """Improving Pronunciation by Specifying Parts of Speech in <Say>""" + + def __init__(self, words=None, **kwargs): + super(SsmlW, self).__init__(**kwargs) + self.name = "w" + if words: + self.value = words + + def break_(self, strength=None, time=None, **kwargs): + """ + Create a <Break> element + + :param strength: Set a pause based on strength + :param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms + :param kwargs: additional attributes + + :returns: <Break> element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a <Emphasis> element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: <Emphasis> element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a <Phoneme> element + + :param words: Words to speak + :param alphabet: Specify the phonetic alphabet + :param ph: Specifiy the phonetic symbols for pronunciation + :param kwargs: additional attributes + + :returns: <Phoneme> element + """ + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) + + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): + """ + Create a <Prosody> element + + :param words: Words to speak + :param volume: Specify the volume, available values: default, silent, x-soft, soft, medium, loud, x-loud, +ndB, -ndB + :param rate: Specify the rate, available values: x-slow, slow, medium, fast, x-fast, n% + :param pitch: Specify the pitch, available values: default, x-low, low, medium, high, x-high, +n%, -n% + :param kwargs: additional attributes + + :returns: <Prosody> element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a <Say-As> element + + :param words: Words to be interpreted + :param interpret-as: Specify the type of words are spoken + :param format: Specify the format of the date when interpret-as is set to date + :param kwargs: additional attributes + + :returns: <Say-As> element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a <Sub> element + + :param words: Words to be substituted + :param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation + :param kwargs: additional attributes + + :returns: <Sub> element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + +class SsmlSub(TwiML): + """Pronouncing Acronyms and Abbreviations in <Say>""" + + def __init__(self, words, **kwargs): + super(SsmlSub, self).__init__(**kwargs) + self.name = "sub" + self.value = words + + +class SsmlSayAs(TwiML): + """Controlling How Special Types of Words Are Spoken in <Say>""" + + def __init__(self, words, **kwargs): + super(SsmlSayAs, self).__init__(**kwargs) + self.name = "say-as" + self.value = words + + +class SsmlProsody(TwiML): + """Controling Volume, Speaking Rate, and Pitch in <Say>""" + + def __init__(self, words=None, **kwargs): + super(SsmlProsody, self).__init__(**kwargs) + self.name = "prosody" + if words: + self.value = words + + def break_(self, strength=None, time=None, **kwargs): + """ + Create a <Break> element + + :param strength: Set a pause based on strength + :param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms + :param kwargs: additional attributes + + :returns: <Break> element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a <Emphasis> element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: <Emphasis> element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a <Lang> element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: <Lang> element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def p(self, words=None, **kwargs): + """ + Create a <P> element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns: <P> element + """ + return self.nest(SsmlP(words=words, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a <Phoneme> element + + :param words: Words to speak + :param alphabet: Specify the phonetic alphabet + :param ph: Specifiy the phonetic symbols for pronunciation + :param kwargs: additional attributes + + :returns: <Phoneme> element + """ + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) + + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): + """ + Create a <Prosody> element + + :param words: Words to speak + :param volume: Specify the volume, available values: default, silent, x-soft, soft, medium, loud, x-loud, +ndB, -ndB + :param rate: Specify the rate, available values: x-slow, slow, medium, fast, x-fast, n% + :param pitch: Specify the pitch, available values: default, x-low, low, medium, high, x-high, +n%, -n% + :param kwargs: additional attributes + + :returns: <Prosody> element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def s(self, words=None, **kwargs): + """ + Create a <S> element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns: <S> element + """ + return self.nest(SsmlS(words=words, **kwargs)) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a <Say-As> element + + :param words: Words to be interpreted + :param interpret-as: Specify the type of words are spoken + :param format: Specify the format of the date when interpret-as is set to date + :param kwargs: additional attributes + + :returns: <Say-As> element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a <Sub> element + + :param words: Words to be substituted + :param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation + :param kwargs: additional attributes + + :returns: <Sub> element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a <W> element + + :param words: Words to speak + :param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning + :param kwargs: additional attributes + + :returns: <W> element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlS(TwiML): + """Adding A Pause Between Sentences in <Say>""" + + def __init__(self, words=None, **kwargs): + super(SsmlS, self).__init__(**kwargs) + self.name = "s" + if words: + self.value = words + + def break_(self, strength=None, time=None, **kwargs): + """ + Create a <Break> element + + :param strength: Set a pause based on strength + :param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms + :param kwargs: additional attributes + + :returns: <Break> element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a <Emphasis> element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: <Emphasis> element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a <Lang> element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: <Lang> element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a <Phoneme> element + + :param words: Words to speak + :param alphabet: Specify the phonetic alphabet + :param ph: Specifiy the phonetic symbols for pronunciation + :param kwargs: additional attributes + + :returns: <Phoneme> element + """ + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) + + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): + """ + Create a <Prosody> element + + :param words: Words to speak + :param volume: Specify the volume, available values: default, silent, x-soft, soft, medium, loud, x-loud, +ndB, -ndB + :param rate: Specify the rate, available values: x-slow, slow, medium, fast, x-fast, n% + :param pitch: Specify the pitch, available values: default, x-low, low, medium, high, x-high, +n%, -n% + :param kwargs: additional attributes + + :returns: <Prosody> element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a <Say-As> element + + :param words: Words to be interpreted + :param interpret-as: Specify the type of words are spoken + :param format: Specify the format of the date when interpret-as is set to date + :param kwargs: additional attributes + + :returns: <Say-As> element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a <Sub> element + + :param words: Words to be substituted + :param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation + :param kwargs: additional attributes + + :returns: <Sub> element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a <W> element + + :param words: Words to speak + :param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning + :param kwargs: additional attributes + + :returns: <W> element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlPhoneme(TwiML): + """Using Phonetic Pronunciation in <Say>""" + + def __init__(self, words, **kwargs): + super(SsmlPhoneme, self).__init__(**kwargs) + self.name = "phoneme" + self.value = words + + +class SsmlLang(TwiML): + """Specifying Another Language for Specific Words in <Say>""" + + def __init__(self, words=None, **kwargs): + super(SsmlLang, self).__init__(**kwargs) + self.name = "lang" + if words: + self.value = words + + def break_(self, strength=None, time=None, **kwargs): + """ + Create a <Break> element + + :param strength: Set a pause based on strength + :param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms + :param kwargs: additional attributes + + :returns: <Break> element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a <Emphasis> element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: <Emphasis> element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a <Lang> element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: <Lang> element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def p(self, words=None, **kwargs): + """ + Create a <P> element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns: <P> element + """ + return self.nest(SsmlP(words=words, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a <Phoneme> element + + :param words: Words to speak + :param alphabet: Specify the phonetic alphabet + :param ph: Specifiy the phonetic symbols for pronunciation + :param kwargs: additional attributes + + :returns: <Phoneme> element + """ + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) + + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): + """ + Create a <Prosody> element + + :param words: Words to speak + :param volume: Specify the volume, available values: default, silent, x-soft, soft, medium, loud, x-loud, +ndB, -ndB + :param rate: Specify the rate, available values: x-slow, slow, medium, fast, x-fast, n% + :param pitch: Specify the pitch, available values: default, x-low, low, medium, high, x-high, +n%, -n% + :param kwargs: additional attributes + + :returns: <Prosody> element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def s(self, words=None, **kwargs): + """ + Create a <S> element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns: <S> element + """ + return self.nest(SsmlS(words=words, **kwargs)) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a <Say-As> element + + :param words: Words to be interpreted + :param interpret-as: Specify the type of words are spoken + :param format: Specify the format of the date when interpret-as is set to date + :param kwargs: additional attributes + + :returns: <Say-As> element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a <Sub> element + + :param words: Words to be substituted + :param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation + :param kwargs: additional attributes + + :returns: <Sub> element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a <W> element + + :param words: Words to speak + :param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning + :param kwargs: additional attributes + + :returns: <W> element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlP(TwiML): + """Adding a Pause Between Paragraphs in <Say>""" + + def __init__(self, words=None, **kwargs): + super(SsmlP, self).__init__(**kwargs) + self.name = "p" + if words: + self.value = words + + def break_(self, strength=None, time=None, **kwargs): + """ + Create a <Break> element + + :param strength: Set a pause based on strength + :param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms + :param kwargs: additional attributes + + :returns: <Break> element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a <Emphasis> element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: <Emphasis> element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a <Lang> element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: <Lang> element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a <Phoneme> element + + :param words: Words to speak + :param alphabet: Specify the phonetic alphabet + :param ph: Specifiy the phonetic symbols for pronunciation + :param kwargs: additional attributes + + :returns: <Phoneme> element + """ + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) + + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): + """ + Create a <Prosody> element + + :param words: Words to speak + :param volume: Specify the volume, available values: default, silent, x-soft, soft, medium, loud, x-loud, +ndB, -ndB + :param rate: Specify the rate, available values: x-slow, slow, medium, fast, x-fast, n% + :param pitch: Specify the pitch, available values: default, x-low, low, medium, high, x-high, +n%, -n% + :param kwargs: additional attributes + + :returns: <Prosody> element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def s(self, words=None, **kwargs): + """ + Create a <S> element + + :param words: Words to speak + :param kwargs: additional attributes + + :returns: <S> element + """ + return self.nest(SsmlS(words=words, **kwargs)) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a <Say-As> element + + :param words: Words to be interpreted + :param interpret-as: Specify the type of words are spoken + :param format: Specify the format of the date when interpret-as is set to date + :param kwargs: additional attributes + + :returns: <Say-As> element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a <Sub> element + + :param words: Words to be substituted + :param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation + :param kwargs: additional attributes + + :returns: <Sub> element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a <W> element + + :param words: Words to speak + :param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning + :param kwargs: additional attributes + + :returns: <W> element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlEmphasis(TwiML): + """Emphasizing Words in <Say>""" + + def __init__(self, words=None, **kwargs): + super(SsmlEmphasis, self).__init__(**kwargs) + self.name = "emphasis" + if words: + self.value = words + + def break_(self, strength=None, time=None, **kwargs): + """ + Create a <Break> element + + :param strength: Set a pause based on strength + :param time: Set a pause to a specific length of time in seconds or milliseconds, available values: [number]s, [number]ms + :param kwargs: additional attributes + + :returns: <Break> element + """ + return self.nest(SsmlBreak(strength=strength, time=time, **kwargs)) + + def emphasis(self, words=None, level=None, **kwargs): + """ + Create a <Emphasis> element + + :param words: Words to emphasize + :param level: Specify the degree of emphasis + :param kwargs: additional attributes + + :returns: <Emphasis> element + """ + return self.nest(SsmlEmphasis(words=words, level=level, **kwargs)) + + def lang(self, words=None, xml_lang=None, **kwargs): + """ + Create a <Lang> element + + :param words: Words to speak + :param xml:lang: Specify the language + :param kwargs: additional attributes + + :returns: <Lang> element + """ + return self.nest(SsmlLang(words=words, xml_lang=xml_lang, **kwargs)) + + def phoneme(self, words, alphabet=None, ph=None, **kwargs): + """ + Create a <Phoneme> element + + :param words: Words to speak + :param alphabet: Specify the phonetic alphabet + :param ph: Specifiy the phonetic symbols for pronunciation + :param kwargs: additional attributes + + :returns: <Phoneme> element + """ + return self.nest(SsmlPhoneme(words, alphabet=alphabet, ph=ph, **kwargs)) + + def prosody(self, words=None, volume=None, rate=None, pitch=None, **kwargs): + """ + Create a <Prosody> element + + :param words: Words to speak + :param volume: Specify the volume, available values: default, silent, x-soft, soft, medium, loud, x-loud, +ndB, -ndB + :param rate: Specify the rate, available values: x-slow, slow, medium, fast, x-fast, n% + :param pitch: Specify the pitch, available values: default, x-low, low, medium, high, x-high, +n%, -n% + :param kwargs: additional attributes + + :returns: <Prosody> element + """ + return self.nest( + SsmlProsody(words=words, volume=volume, rate=rate, pitch=pitch, **kwargs) + ) + + def say_as(self, words, interpret_as=None, format=None, **kwargs): + """ + Create a <Say-As> element + + :param words: Words to be interpreted + :param interpret-as: Specify the type of words are spoken + :param format: Specify the format of the date when interpret-as is set to date + :param kwargs: additional attributes + + :returns: <Say-As> element + """ + return self.nest( + SsmlSayAs(words, interpret_as=interpret_as, format=format, **kwargs) + ) + + def sub(self, words, alias=None, **kwargs): + """ + Create a <Sub> element + + :param words: Words to be substituted + :param alias: Substitute a different word (or pronunciation) for selected text such as an acronym or abbreviation + :param kwargs: additional attributes + + :returns: <Sub> element + """ + return self.nest(SsmlSub(words, alias=alias, **kwargs)) + + def w(self, words=None, role=None, **kwargs): + """ + Create a <W> element + + :param words: Words to speak + :param role: Customize the pronunciation of words by specifying the word’s part of speech or alternate meaning + :param kwargs: additional attributes + + :returns: <W> element + """ + return self.nest(SsmlW(words=words, role=role, **kwargs)) + + +class SsmlBreak(TwiML): + """Adding a Pause in <Say>""" + + def __init__(self, **kwargs): + super(SsmlBreak, self).__init__(**kwargs) + self.name = "break" + + +class Pay(TwiML): + """<Pay> Twiml Verb""" + + def __init__(self, **kwargs): + super(Pay, self).__init__(**kwargs) + self.name = "Pay" + + def prompt( + self, + for_=None, + error_type=None, + card_type=None, + attempt=None, + require_matching_inputs=None, + **kwargs + ): + """ + Create a <Prompt> element + + :param for_: Name of the payment source data element + :param error_type: Type of error + :param card_type: Type of the credit card + :param attempt: Current attempt count + :param require_matching_inputs: Require customer to input requested information twice and verify matching. + :param kwargs: additional attributes + + :returns: <Prompt> element + """ + return self.nest( + Prompt( + for_=for_, + error_type=error_type, + card_type=card_type, + attempt=attempt, + require_matching_inputs=require_matching_inputs, + **kwargs + ) + ) + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a <Parameter> element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: <Parameter> element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Sms(TwiML): + """<Sms> TwiML Noun""" + + def __init__(self, message, **kwargs): + super(Sms, self).__init__(**kwargs) + self.name = "Sms" + self.value = message + + +class Reject(TwiML): + """<Reject> TwiML Verb""" + + def __init__(self, **kwargs): + super(Reject, self).__init__(**kwargs) + self.name = "Reject" + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a <Parameter> element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: <Parameter> element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Redirect(TwiML): + """<Redirect> TwiML Verb""" + + def __init__(self, url, **kwargs): + super(Redirect, self).__init__(**kwargs) + self.name = "Redirect" + self.value = url + + +class Record(TwiML): + """<Record> TwiML Verb""" + + def __init__(self, **kwargs): + super(Record, self).__init__(**kwargs) + self.name = "Record" + + +class Queue(TwiML): + """<Queue> TwiML Noun""" + + def __init__(self, name, **kwargs): + super(Queue, self).__init__(**kwargs) + self.name = "Queue" + self.value = name + + +class Leave(TwiML): + """<Leave> TwiML Verb""" + + def __init__(self, **kwargs): + super(Leave, self).__init__(**kwargs) + self.name = "Leave" + + +class Hangup(TwiML): + """<Hangup> TwiML Verb""" + + def __init__(self, **kwargs): + super(Hangup, self).__init__(**kwargs) + self.name = "Hangup" + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a <Parameter> element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: <Parameter> element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Gather(TwiML): + """<Gather> TwiML Verb""" + + def __init__(self, **kwargs): + super(Gather, self).__init__(**kwargs) + self.name = "Gather" + + def say(self, message=None, voice=None, loop=None, language=None, **kwargs): + """ + Create a <Say> element + + :param message: Message to say + :param voice: Voice to use + :param loop: Times to loop message + :param language: Message language + :param kwargs: additional attributes + + :returns: <Say> element + """ + return self.nest( + Say(message=message, voice=voice, loop=loop, language=language, **kwargs) + ) + + def pause(self, length=None, **kwargs): + """ + Create a <Pause> element + + :param length: Length in seconds to pause + :param kwargs: additional attributes + + :returns: <Pause> element + """ + return self.nest(Pause(length=length, **kwargs)) + + def play(self, url=None, loop=None, digits=None, **kwargs): + """ + Create a <Play> element + + :param url: Media URL + :param loop: Times to loop media + :param digits: Play DTMF tones for digits + :param kwargs: additional attributes + + :returns: <Play> element + """ + return self.nest(Play(url=url, loop=loop, digits=digits, **kwargs)) + + +class Enqueue(TwiML): + """<Enqueue> TwiML Noun""" + + def __init__(self, name=None, **kwargs): + super(Enqueue, self).__init__(**kwargs) + self.name = "Enqueue" + if name: + self.value = name + + def task(self, body, priority=None, timeout=None, **kwargs): + """ + Create a <Task> element + + :param body: TaskRouter task attributes + :param priority: Task priority + :param timeout: Timeout associated with task + :param kwargs: additional attributes + + :returns: <Task> element + """ + return self.nest(Task(body, priority=priority, timeout=timeout, **kwargs)) + + +class Task(TwiML): + """<Task> TwiML Noun""" + + def __init__(self, body, **kwargs): + super(Task, self).__init__(**kwargs) + self.name = "Task" + self.value = body + + +class Echo(TwiML): + """<Echo> TwiML Verb""" + + def __init__(self, **kwargs): + super(Echo, self).__init__(**kwargs) + self.name = "Echo" + + +class Dial(TwiML): + """<Dial> TwiML Verb""" + + def __init__(self, number=None, **kwargs): + super(Dial, self).__init__(**kwargs) + self.name = "Dial" + if number: + self.value = number + + def client( + self, + identity=None, + url=None, + method=None, + status_callback_event=None, + status_callback=None, + status_callback_method=None, + **kwargs + ): + """ + Create a <Client> element + + :param identity: Client identity + :param url: Client URL + :param method: Client URL Method + :param status_callback_event: Events to trigger status callback + :param status_callback: Status Callback URL + :param status_callback_method: Status Callback URL Method + :param kwargs: additional attributes + + :returns: <Client> element + """ + return self.nest( + Client( + identity=identity, + url=url, + method=method, + status_callback_event=status_callback_event, + status_callback=status_callback, + status_callback_method=status_callback_method, + **kwargs + ) + ) + + def conference( + self, + name, + muted=None, + beep=None, + start_conference_on_enter=None, + end_conference_on_exit=None, + wait_url=None, + wait_method=None, + max_participants=None, + record=None, + region=None, + coach=None, + trim=None, + status_callback_event=None, + status_callback=None, + status_callback_method=None, + recording_status_callback=None, + recording_status_callback_method=None, + recording_status_callback_event=None, + event_callback_url=None, + jitter_buffer_size=None, + participant_label=None, + **kwargs + ): + """ + Create a <Conference> element + + :param name: Conference name + :param muted: Join the conference muted + :param beep: Play beep when joining + :param start_conference_on_enter: Start the conference on enter + :param end_conference_on_exit: End the conferenceon exit + :param wait_url: Wait URL + :param wait_method: Wait URL method + :param max_participants: Maximum number of participants + :param record: Record the conference + :param region: Conference region + :param coach: Call coach + :param trim: Trim the conference recording + :param status_callback_event: Events to call status callback URL + :param status_callback: Status callback URL + :param status_callback_method: Status callback URL method + :param recording_status_callback: Recording status callback URL + :param recording_status_callback_method: Recording status callback URL method + :param recording_status_callback_event: Recording status callback events + :param event_callback_url: Event callback URL + :param jitter_buffer_size: Size of jitter buffer for participant + :param participant_label: A label for participant + :param kwargs: additional attributes + + :returns: <Conference> element + """ + return self.nest( + Conference( + name, + muted=muted, + beep=beep, + start_conference_on_enter=start_conference_on_enter, + end_conference_on_exit=end_conference_on_exit, + wait_url=wait_url, + wait_method=wait_method, + max_participants=max_participants, + record=record, + region=region, + coach=coach, + trim=trim, + status_callback_event=status_callback_event, + status_callback=status_callback, + status_callback_method=status_callback_method, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + recording_status_callback_event=recording_status_callback_event, + event_callback_url=event_callback_url, + jitter_buffer_size=jitter_buffer_size, + participant_label=participant_label, + **kwargs + ) + ) + + def number( + self, + phone_number, + send_digits=None, + url=None, + method=None, + status_callback_event=None, + status_callback=None, + status_callback_method=None, + byoc=None, + machine_detection=None, + amd_status_callback_method=None, + amd_status_callback=None, + machine_detection_timeout=None, + machine_detection_speech_threshold=None, + machine_detection_speech_end_threshold=None, + machine_detection_silence_timeout=None, + **kwargs + ): + """ + Create a <Number> element + + :param phone_number: Phone Number to dial + :param send_digits: DTMF tones to play when the call is answered + :param url: TwiML URL + :param method: TwiML URL method + :param status_callback_event: Events to call status callback + :param status_callback: Status callback URL + :param status_callback_method: Status callback URL method + :param byoc: BYOC trunk SID (Beta) + :param machine_detection: Enable machine detection or end of greeting detection + :param amd_status_callback_method: HTTP Method to use with amd_status_callback + :param amd_status_callback: The URL we should call to send amd status information to your application + :param machine_detection_timeout: Number of seconds to wait for machine detection + :param machine_detection_speech_threshold: Number of milliseconds for measuring stick for the length of the speech activity + :param machine_detection_speech_end_threshold: Number of milliseconds of silence after speech activity + :param machine_detection_silence_timeout: Number of milliseconds of initial silence + :param kwargs: additional attributes + + :returns: <Number> element + """ + return self.nest( + Number( + phone_number, + send_digits=send_digits, + url=url, + method=method, + status_callback_event=status_callback_event, + status_callback=status_callback, + status_callback_method=status_callback_method, + byoc=byoc, + machine_detection=machine_detection, + amd_status_callback_method=amd_status_callback_method, + amd_status_callback=amd_status_callback, + machine_detection_timeout=machine_detection_timeout, + machine_detection_speech_threshold=machine_detection_speech_threshold, + machine_detection_speech_end_threshold=machine_detection_speech_end_threshold, + machine_detection_silence_timeout=machine_detection_silence_timeout, + **kwargs + ) + ) + + def queue( + self, + name, + url=None, + method=None, + reservation_sid=None, + post_work_activity_sid=None, + **kwargs + ): + """ + Create a <Queue> element + + :param name: Queue name + :param url: Action URL + :param method: Action URL method + :param reservation_sid: TaskRouter Reservation SID + :param post_work_activity_sid: TaskRouter Activity SID + :param kwargs: additional attributes + + :returns: <Queue> element + """ + return self.nest( + Queue( + name, + url=url, + method=method, + reservation_sid=reservation_sid, + post_work_activity_sid=post_work_activity_sid, + **kwargs + ) + ) + + def sim(self, sim_sid, **kwargs): + """ + Create a <Sim> element + + :param sim_sid: SIM SID + :param kwargs: additional attributes + + :returns: <Sim> element + """ + return self.nest(Sim(sim_sid, **kwargs)) + + def sip( + self, + sip_url, + username=None, + password=None, + url=None, + method=None, + status_callback_event=None, + status_callback=None, + status_callback_method=None, + machine_detection=None, + amd_status_callback_method=None, + amd_status_callback=None, + machine_detection_timeout=None, + machine_detection_speech_threshold=None, + machine_detection_speech_end_threshold=None, + machine_detection_silence_timeout=None, + **kwargs + ): + """ + Create a <Sip> element + + :param sip_url: SIP URL + :param username: SIP Username + :param password: SIP Password + :param url: Action URL + :param method: Action URL method + :param status_callback_event: Status callback events + :param status_callback: Status callback URL + :param status_callback_method: Status callback URL method + :param machine_detection: Enable machine detection or end of greeting detection + :param amd_status_callback_method: HTTP Method to use with amd_status_callback + :param amd_status_callback: The URL we should call to send amd status information to your application + :param machine_detection_timeout: Number of seconds to wait for machine detection + :param machine_detection_speech_threshold: Number of milliseconds for measuring stick for the length of the speech activity + :param machine_detection_speech_end_threshold: Number of milliseconds of silence after speech activity + :param machine_detection_silence_timeout: Number of milliseconds of initial silence + :param kwargs: additional attributes + + :returns: <Sip> element + """ + return self.nest( + Sip( + sip_url, + username=username, + password=password, + url=url, + method=method, + status_callback_event=status_callback_event, + status_callback=status_callback, + status_callback_method=status_callback_method, + machine_detection=machine_detection, + amd_status_callback_method=amd_status_callback_method, + amd_status_callback=amd_status_callback, + machine_detection_timeout=machine_detection_timeout, + machine_detection_speech_threshold=machine_detection_speech_threshold, + machine_detection_speech_end_threshold=machine_detection_speech_end_threshold, + machine_detection_silence_timeout=machine_detection_silence_timeout, + **kwargs + ) + ) + + def application( + self, + application_sid=None, + url=None, + method=None, + status_callback_event=None, + status_callback=None, + status_callback_method=None, + customer_id=None, + copy_parent_to=None, + **kwargs + ): + """ + Create a <Application> element + + :param application_sid: Application sid + :param url: TwiML URL + :param method: TwiML URL Method + :param status_callback_event: Events to trigger status callback + :param status_callback: Status Callback URL + :param status_callback_method: Status Callback URL Method + :param customer_id: Identity of the customer calling application + :param copy_parent_to: Copy parent call To field to called application side, otherwise use the application sid as To field + :param kwargs: additional attributes + + :returns: <Application> element + """ + return self.nest( + Application( + application_sid=application_sid, + url=url, + method=method, + status_callback_event=status_callback_event, + status_callback=status_callback, + status_callback_method=status_callback_method, + customer_id=customer_id, + copy_parent_to=copy_parent_to, + **kwargs + ) + ) + + +class Application(TwiML): + """<Application> TwiML Noun""" + + def __init__(self, application_sid=None, **kwargs): + super(Application, self).__init__(**kwargs) + self.name = "Application" + if application_sid: + self.value = application_sid + + def application_sid(self, sid, **kwargs): + """ + Create a <ApplicationSid> element + + :param sid: Application sid to dial + :param kwargs: additional attributes + + :returns: <ApplicationSid> element + """ + return self.nest(ApplicationSid(sid, **kwargs)) + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a <Parameter> element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: <Parameter> element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class ApplicationSid(TwiML): + """<ApplicationSid> TwiML Noun""" + + def __init__(self, sid, **kwargs): + super(ApplicationSid, self).__init__(**kwargs) + self.name = "ApplicationSid" + self.value = sid + + +class Sip(TwiML): + """<Sip> TwiML Noun""" + + def __init__(self, sip_url, **kwargs): + super(Sip, self).__init__(**kwargs) + self.name = "Sip" + self.value = sip_url + + +class Sim(TwiML): + """<Sim> TwiML Noun""" + + def __init__(self, sim_sid, **kwargs): + super(Sim, self).__init__(**kwargs) + self.name = "Sim" + self.value = sim_sid + + +class Number(TwiML): + """<Number> TwiML Noun""" + + def __init__(self, phone_number, **kwargs): + super(Number, self).__init__(**kwargs) + self.name = "Number" + self.value = phone_number + + +class Conference(TwiML): + """<Conference> TwiML Noun""" + + def __init__(self, name, **kwargs): + super(Conference, self).__init__(**kwargs) + self.name = "Conference" + self.value = name + + +class Client(TwiML): + """<Client> TwiML Noun""" + + def __init__(self, identity=None, **kwargs): + super(Client, self).__init__(**kwargs) + self.name = "Client" + if identity: + self.value = identity + + def identity(self, client_identity, **kwargs): + """ + Create a <Identity> element + + :param client_identity: Identity of the client to dial + :param kwargs: additional attributes + + :returns: <Identity> element + """ + return self.nest(Identity(client_identity, **kwargs)) + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a <Parameter> element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: <Parameter> element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Identity(TwiML): + """<Identity> TwiML Noun""" + + def __init__(self, client_identity, **kwargs): + super(Identity, self).__init__(**kwargs) + self.name = "Identity" + self.value = client_identity + + +class Connect(TwiML): + """<Connect> TwiML Verb""" + + def __init__(self, **kwargs): + super(Connect, self).__init__(**kwargs) + self.name = "Connect" + + def room(self, name, participant_identity=None, **kwargs): + """ + Create a <Room> element + + :param name: Room name + :param participant_identity: Participant identity when connecting to the Room + :param kwargs: additional attributes + + :returns: <Room> element + """ + return self.nest( + Room(name, participant_identity=participant_identity, **kwargs) + ) + + def autopilot(self, name, **kwargs): + """ + Create a <Autopilot> element + + :param name: Autopilot assistant sid or unique name + :param kwargs: additional attributes + + :returns: <Autopilot> element + """ + return self.nest(Autopilot(name, **kwargs)) + + def stream( + self, + name=None, + connector_name=None, + url=None, + track=None, + status_callback=None, + status_callback_method=None, + **kwargs + ): + """ + Create a <Stream> element + + :param name: Friendly name given to the Stream + :param connector_name: Unique name for Stream Connector + :param url: URL of the remote service where the Stream is routed + :param track: Track to be streamed to remote service + :param status_callback: Status Callback URL + :param status_callback_method: Status Callback URL method + :param kwargs: additional attributes + + :returns: <Stream> element + """ + return self.nest( + Stream( + name=name, + connector_name=connector_name, + url=url, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + **kwargs + ) + ) + + def virtual_agent( + self, + connector_name=None, + language=None, + sentiment_analysis=None, + status_callback=None, + status_callback_method=None, + **kwargs + ): + """ + Create a <VirtualAgent> element + + :param connector_name: Defines the conversation profile Dialogflow needs to use + :param language: Language to be used by Dialogflow to transcribe speech + :param sentiment_analysis: Whether sentiment analysis needs to be enabled or not + :param status_callback: URL to post status callbacks from Twilio + :param status_callback_method: HTTP method to use when requesting the status callback URL + :param kwargs: additional attributes + + :returns: <VirtualAgent> element + """ + return self.nest( + VirtualAgent( + connector_name=connector_name, + language=language, + sentiment_analysis=sentiment_analysis, + status_callback=status_callback, + status_callback_method=status_callback_method, + **kwargs + ) + ) + + def conversation( + self, + service_instance_sid=None, + inbound_autocreation=None, + routing_assignment_timeout=None, + inbound_timeout=None, + url=None, + method=None, + record=None, + trim=None, + recording_status_callback=None, + recording_status_callback_method=None, + recording_status_callback_event=None, + status_callback=None, + status_callback_method=None, + status_callback_event=None, + **kwargs + ): + """ + Create a <Conversation> element + + :param service_instance_sid: Service instance Sid + :param inbound_autocreation: Inbound autocreation + :param routing_assignment_timeout: Routing assignment timeout + :param inbound_timeout: Inbound timeout + :param url: TwiML URL + :param method: TwiML URL method + :param record: Record + :param trim: Trim + :param recording_status_callback: Recording status callback URL + :param recording_status_callback_method: Recording status callback URL method + :param recording_status_callback_event: Recording status callback events + :param status_callback: Status callback URL + :param status_callback_method: Status callback URL method + :param status_callback_event: Events to call status callback URL + :param kwargs: additional attributes + + :returns: <Conversation> element + """ + return self.nest( + Conversation( + service_instance_sid=service_instance_sid, + inbound_autocreation=inbound_autocreation, + routing_assignment_timeout=routing_assignment_timeout, + inbound_timeout=inbound_timeout, + url=url, + method=method, + record=record, + trim=trim, + recording_status_callback=recording_status_callback, + recording_status_callback_method=recording_status_callback_method, + recording_status_callback_event=recording_status_callback_event, + status_callback=status_callback, + status_callback_method=status_callback_method, + status_callback_event=status_callback_event, + **kwargs + ) + ) + + def conversation_relay( + self, + url=None, + language=None, + tts_language=None, + transcription_language=None, + tts_provider=None, + voice=None, + transcription_provider=None, + speech_model=None, + profanity_filter=None, + dtmf_detection=None, + welcome_greeting=None, + partial_prompts=None, + welcome_greeting_interruptible=None, + interruptible=None, + preemptible=None, + hints=None, + intelligence_service=None, + report_input_during_agent_speech=None, + elevenlabs_text_normalization=None, + interrupt_sensitivity=None, + debug=None, + **kwargs + ): + """ + Create a <ConversationRelay> element + + :param url: URL of the remote service where the session is connected to + :param language: Language to be used for both text-to-speech and transcription + :param tts_language: Language to be used for text-to-speech + :param transcription_language: Language to be used for transcription + :param tts_provider: Provider to be used for text-to-speech + :param voice: Voice to be used for text-to-speech + :param transcription_provider: Provider to be used for transcription + :param speech_model: Speech model to be used for transcription + :param profanity_filter: Whether profanities should be filtered out of the speech transcription + :param dtmf_detection: Whether DTMF tones should be detected and reported in speech transcription + :param welcome_greeting: The sentence to be played automatically when the session is connected + :param partial_prompts: Whether partial prompts should be reported to WebSocket server before the caller finishes speaking + :param welcome_greeting_interruptible: "Whether and how the input from a caller, such as speaking or DTMF can interrupt the welcome greeting + :param interruptible: Whether and how the input from a caller, such as speaking or DTMF can interrupt the play of text-to-speech + :param preemptible: Whether subsequent text-to-speech or play media can interrupt the on-going play of text-to-speech or media + :param hints: Phrases to help better accuracy in speech recognition of these pharases + :param intelligence_service: The Conversational Intelligence Service id or unique name to be used for the session + :param report_input_during_agent_speech: Whether prompts should be reported to WebSocket server when text-to-speech playing and interrupt is disabled + :param elevenlabs_text_normalization: When using ElevenLabs as TTS provider, this parameter allows you to enable or disable its text normalization feature + :param interrupt_sensitivity: Set the sensitivity of the interrupt feature for speech. The value can be low, medium, or high + :param debug: Multiple debug options to be used for troubleshooting + :param kwargs: additional attributes + + :returns: <ConversationRelay> element + """ + return self.nest( + ConversationRelay( + url=url, + language=language, + tts_language=tts_language, + transcription_language=transcription_language, + tts_provider=tts_provider, + voice=voice, + transcription_provider=transcription_provider, + speech_model=speech_model, + profanity_filter=profanity_filter, + dtmf_detection=dtmf_detection, + welcome_greeting=welcome_greeting, + partial_prompts=partial_prompts, + welcome_greeting_interruptible=welcome_greeting_interruptible, + interruptible=interruptible, + preemptible=preemptible, + hints=hints, + intelligence_service=intelligence_service, + report_input_during_agent_speech=report_input_during_agent_speech, + elevenlabs_text_normalization=elevenlabs_text_normalization, + interrupt_sensitivity=interrupt_sensitivity, + debug=debug, + **kwargs + ) + ) + + def assistant( + self, + id=None, + language=None, + tts_language=None, + transcription_language=None, + tts_provider=None, + voice=None, + transcription_provider=None, + speech_model=None, + profanity_filter=None, + dtmf_detection=None, + welcome_greeting=None, + partial_prompts=None, + welcome_greeting_interruptible=None, + interruptible=None, + preemptible=None, + hints=None, + intelligence_service=None, + report_input_during_agent_speech=None, + elevenlabs_text_normalization=None, + interrupt_sensitivity=None, + debug=None, + **kwargs + ): + """ + Create a <Assistant> element + + :param id: The assistant ID of the AI Assistant + :param language: Language to be used for both text-to-speech and transcription + :param tts_language: Language to be used for text-to-speech + :param transcription_language: Language to be used for transcription + :param tts_provider: Provider to be used for text-to-speech + :param voice: Voice to be used for text-to-speech + :param transcription_provider: Provider to be used for transcription + :param speech_model: Speech model to be used for transcription + :param profanity_filter: Whether profanities should be filtered out of the speech transcription + :param dtmf_detection: Whether DTMF tones should be detected and reported in speech transcription + :param welcome_greeting: The sentence to be played automatically when the session is connected + :param partial_prompts: Whether partial prompts should be reported to WebSocket server before the caller finishes speaking + :param welcome_greeting_interruptible: "Whether and how the input from a caller, such as speaking or DTMF can interrupt the welcome greeting + :param interruptible: Whether and how the input from a caller, such as speaking or DTMF can interrupt the play of text-to-speech + :param preemptible: Whether subsequent text-to-speech or play media can interrupt the on-going play of text-to-speech or media + :param hints: Phrases to help better accuracy in speech recognition of these pharases + :param intelligence_service: The Conversational Intelligence Service id or unique name to be used for the session + :param report_input_during_agent_speech: Whether prompts should be reported to WebSocket server when text-to-speech playing and interrupt is disabled + :param elevenlabs_text_normalization: When using ElevenLabs as TTS provider, this parameter allows you to enable or disable its text normalization feature + :param interrupt_sensitivity: Set the sensitivity of the interrupt feature for speech. The value can be low, medium, or high + :param debug: Multiple debug options to be used for troubleshooting + :param kwargs: additional attributes + + :returns: <Assistant> element + """ + return self.nest( + Assistant( + id=id, + language=language, + tts_language=tts_language, + transcription_language=transcription_language, + tts_provider=tts_provider, + voice=voice, + transcription_provider=transcription_provider, + speech_model=speech_model, + profanity_filter=profanity_filter, + dtmf_detection=dtmf_detection, + welcome_greeting=welcome_greeting, + partial_prompts=partial_prompts, + welcome_greeting_interruptible=welcome_greeting_interruptible, + interruptible=interruptible, + preemptible=preemptible, + hints=hints, + intelligence_service=intelligence_service, + report_input_during_agent_speech=report_input_during_agent_speech, + elevenlabs_text_normalization=elevenlabs_text_normalization, + interrupt_sensitivity=interrupt_sensitivity, + debug=debug, + **kwargs + ) + ) + + +class Assistant(TwiML): + """<Assistant> TwiML Noun""" + + def __init__(self, **kwargs): + super(Assistant, self).__init__(**kwargs) + self.name = "Assistant" + + def language( + self, + code=None, + tts_provider=None, + voice=None, + transcription_provider=None, + speech_model=None, + **kwargs + ): + """ + Create a <Language> element + + :param code: Language code of this language setting is for + :param tts_provider: Provider to be used for text-to-speech of this language + :param voice: Voice to be used for text-to-speech of this language + :param transcription_provider: Provider to be used for transcription of this language + :param speech_model: Speech model to be used for transcription of this language + :param kwargs: additional attributes + + :returns: <Language> element + """ + return self.nest( + Language( + code=code, + tts_provider=tts_provider, + voice=voice, + transcription_provider=transcription_provider, + speech_model=speech_model, + **kwargs + ) + ) + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a <Parameter> element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: <Parameter> element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Language(TwiML): + """<Language> TwiML Noun""" + + def __init__(self, **kwargs): + super(Language, self).__init__(**kwargs) + self.name = "Language" + + +class ConversationRelay(TwiML): + """<ConversationRelay> TwiML Noun""" + + def __init__(self, **kwargs): + super(ConversationRelay, self).__init__(**kwargs) + self.name = "ConversationRelay" + + def language( + self, + code=None, + tts_provider=None, + voice=None, + transcription_provider=None, + speech_model=None, + **kwargs + ): + """ + Create a <Language> element + + :param code: Language code of this language setting is for + :param tts_provider: Provider to be used for text-to-speech of this language + :param voice: Voice to be used for text-to-speech of this language + :param transcription_provider: Provider to be used for transcription of this language + :param speech_model: Speech model to be used for transcription of this language + :param kwargs: additional attributes + + :returns: <Language> element + """ + return self.nest( + Language( + code=code, + tts_provider=tts_provider, + voice=voice, + transcription_provider=transcription_provider, + speech_model=speech_model, + **kwargs + ) + ) + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a <Parameter> element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: <Parameter> element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Conversation(TwiML): + """<Conversation> TwiML Noun""" + + def __init__(self, **kwargs): + super(Conversation, self).__init__(**kwargs) + self.name = "Conversation" + + +class VirtualAgent(TwiML): + """<VirtualAgent> TwiML Noun""" + + def __init__(self, **kwargs): + super(VirtualAgent, self).__init__(**kwargs) + self.name = "VirtualAgent" + + def config(self, name=None, value=None, **kwargs): + """ + Create a <Config> element + + :param name: The name of the custom config + :param value: The value of the custom config + :param kwargs: additional attributes + + :returns: <Config> element + """ + return self.nest(Config(name=name, value=value, **kwargs)) + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a <Parameter> element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: <Parameter> element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Autopilot(TwiML): + """<Autopilot> TwiML Noun""" + + def __init__(self, name, **kwargs): + super(Autopilot, self).__init__(**kwargs) + self.name = "Autopilot" + self.value = name + + +class Room(TwiML): + """<Room> TwiML Noun""" + + def __init__(self, name, **kwargs): + super(Room, self).__init__(**kwargs) + self.name = "Room" + self.value = name diff --git a/twilio/util.py b/twilio/util.py deleted file mode 100644 index b2a7cc3c6c..0000000000 --- a/twilio/util.py +++ /dev/null @@ -1,164 +0,0 @@ -import base64 -import hmac -import time -from hashlib import sha1 - -from twilio import jwt -from twilio.compat import izip, urlencode -from six import iteritems - - -class RequestValidator(object): - - def __init__(self, token): - self.token = token.encode("utf-8") - - def compute_signature(self, uri, params): - """Compute the signature for a given request - - :param uri: full URI that Twilio requested on your server - :param params: post vars that Twilio sent with the request - :param auth: tuple with (account_sid, token) - - :returns: The computed signature - """ - s = uri - if len(params) > 0: - for k, v in sorted(params.items()): - s += k + v - - # compute signature and compare signatures - mac = hmac.new(self.token, s.encode("utf-8"), sha1) - computed = base64.b64encode(mac.digest()) - - return computed.strip() - - def validate(self, uri, params, signature): - """Validate a request from Twilio - - :param uri: full URI that Twilio requested on your server - :param params: post vars that Twilio sent with the request - :param signature: expexcted signature in HTTP X-Twilio-Signature header - :param auth: tuple with (account_sid, token) - - :returns: True if the request passes validation, False if not - """ - return secure_compare(self.compute_signature(uri, params), signature) - - -def secure_compare(string1, string2): - """Compare two strings while protecting against timing attacks - - :param string1: the first string - :param string2: the second string - - :returns: True if the strings are equal, False if not - """ - if len(string1) != len(string2): - return False - result = True - for c1, c2 in izip(string1, string2): - result &= c1 == c2 - return result - - -class TwilioCapability(object): - """ - A token to control permissions with Twilio Client - - :param string account_sid: the account sid to which this token - is granted access - :param string auth_token: the secret key used to sign the token. - Note, this auth token is not visible to the - user of the token. - - :returns: A new TwilioCapability with zero permissions - """ - - def __init__(self, account_sid, auth_token): - self.account_sid = account_sid - self.auth_token = auth_token - self.capabilities = {} - self.client_name = None - - def payload(self): - """Return the payload for this token.""" - if "outgoing" in self.capabilities and self.client_name is not None: - scope = self.capabilities["outgoing"] - scope.params["clientName"] = self.client_name - - capabilities = self.capabilities.values() - scope_uris = [str(scope_uri) for scope_uri in capabilities] - - return { - "scope": " ".join(scope_uris) - } - - def generate(self, expires=3600): - """Generate a valid JWT token with an expiration date. - - :param int expires: The token lifetime, in seconds. Defaults to - 1 hour (3600) - - """ - payload = self.payload() - payload['iss'] = self.account_sid - payload['exp'] = int(time.time() + expires) - return jwt.encode(payload, self.auth_token) - - def allow_client_outgoing(self, application_sid, **kwargs): - """Allow the user of this token to make outgoing connections. - - Keyword arguments are passed to the application. - - :param string application_sid: Application to contact - """ - scope_params = { - "appSid": application_sid, - } - if kwargs: - scope_params["appParams"] = urlencode(kwargs, doseq=True) - - self.capabilities["outgoing"] = ScopeURI("client", "outgoing", - scope_params) - - def allow_client_incoming(self, client_name): - """If the user of this token should be allowed to accept incoming - connections then configure the TwilioCapability through this method and - specify the client name. - - :param string client_name: Client name to accept calls from - - """ - self.client_name = client_name - self.capabilities["incoming"] = ScopeURI("client", "incoming", { - 'clientName': client_name - }) - - def allow_event_stream(self, **kwargs): - """Allow the user of this token to access their event stream.""" - scope_params = { - "path": "/2010-04-01/Events", - } - if kwargs: - scope_params['params'] = urlencode(kwargs, doseq=True) - - self.capabilities["events"] = ScopeURI("stream", "subscribe", - scope_params) - - -class ScopeURI(object): - - def __init__(self, service, privilege, params=None): - self.service = service - self.privilege = privilege - self.params = params - - def __str__(self): - if self.params: - sorted_params = sorted([(k, v) for k, v in iteritems(self.params)]) - encoded_params = urlencode(sorted_params) - param_string = '?%s' % encoded_params - else: - param_string = '' - return "scope:%s:%s%s" % (self.service, self.privilege, param_string)